shelfy/internal/login/login.go
2025-06-06 09:42:55 +02:00

69 lines
1.7 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
}}