shelfy/internal/login/login.go

128 lines
3.4 KiB
Go
Raw Normal View History

2025-06-06 07:42:55 +00:00
package login
import (
"app/shelfly/internal/jwt"
"app/shelfly/internal/models"
"encoding/json"
"fmt"
"net/http"
"golang.org/x/crypto/bcrypt"
"gorm.io/gorm"
)
func LoginHandler(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var u =models.User{}
var user =models.User{}
json.NewDecoder(r.Body).Decode(&u)
fmt.Printf("The user request value %v", u)
fmt.Println(u.Email)
user=u;
d :=db.Where("Email = ?", u.Email).First(&user)
if d.Error != nil {
fmt.Println("Erreur lors de la requête :", d.Error)
} else {
// Afficher les données récupérées
fmt.Printf("Utilisateur trouvé : %+v\n", user)
}
if u.Email != user.Email {
// Handle email mismatch
fmt.Fprint(w, "Invalid credentials")
w.WriteHeader(http.StatusUnauthorized)
return
}
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(u.Password)); err != nil {
fmt.Fprint(w, "Invalid credentials")
w.WriteHeader(http.StatusUnauthorized)
return
}
tokenString, err := jwt.CreateToken(user.Username)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
fmt.Errorf("No username found")
}
// 4. Configurer un cookie HTTP-only
http.SetCookie(w, &http.Cookie{
Name: "token",
Value: tokenString,
Path: "/",
HttpOnly: true, // Empêche laccès via JS (mitige XSS)
Secure: false, // Passez à true en HTTPS
// SameSite et Domain peuvent être précisés selon votre config
})
// 5. Réponse JSON (optionnel)
w.Header().Add("Hx-Redirect", "/dashboard")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"message": "Connected"}`))
return
2025-07-15 15:25:58 +00:00
}}
func LoginHandlerApi(db *gorm.DB) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// 1. Lire les données JSON envoyées par Flutter
var input struct {
Email string `json:"email"`
Password string `json:"password"`
}
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
http.Error(w, `{"error":"Invalid JSON format"}`, http.StatusBadRequest)
return
}
// 2. Rechercher l'utilisateur en base
var user models.User
if err := db.Where("email = ?", input.Email).First(&user).Error; err != nil {
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid email or password",
})
return
}
// 3. Comparer le mot de passe
if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(input.Password)); err != nil {
w.WriteHeader(http.StatusUnauthorized)
json.NewEncoder(w).Encode(map[string]string{
"error": "Invalid email or password",
})
return
}
// 4. Créer un token JWT
tokenString, err := jwt.CreateToken(user.Username) // à adapter selon ta fonction
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "Failed to generate token",
})
return
}
// 5. Répondre en JSON pour Flutter
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]interface{}{
"user": map[string]interface{}{
"id": user.ID,
"username": user.Username,
"email": user.Email,
2025-07-16 09:47:40 +00:00
"token": tokenString,
"password" : input.Password
2025-07-15 15:25:58 +00:00
// ajoute d'autres infos utiles ici si nécessaire
},
})
}
}