shelfy/handlers/main.go

86 lines
2.8 KiB
Go
Raw Normal View History

2025-06-06 07:42:55 +00:00
package handlers
import (
"context"
"fmt"
"net/http"
"time"
"github.com/golang-jwt/jwt"
)
var secretKey = []byte("secret-key")
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Récupérer le cookie
cookie, err := r.Cookie("token")
if err != nil {
// Si pas de cookie ou erreur de lecture
fmt.Println("Erreur : cookie 'token' manquant ou illisible :", err)
http.Error(w, "Token manquant ou invalide", http.StatusUnauthorized)
return
}
tokenString := cookie.Value
// fmt.Println("Token reçu :", tokenString)
// Parser et vérifier le token
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Vérifier que la méthode de signature est correcte
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("méthode de signature inattendue : %v", token.Header["alg"])
}
return []byte(secretKey), nil // Utiliser la clé secrète correcte
})
if err != nil {
fmt.Println("Erreur lors de la validation du token :", err)
http.Error(w, "Token invalide", http.StatusUnauthorized)
return
}
if !token.Valid {
fmt.Println("Token non valide")
http.Error(w, "Token invalide", http.StatusUnauthorized)
return
}
// Extraire les claims
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
fmt.Println("Erreur : claims introuvables ou invalides")
http.Error(w, "Token invalide", http.StatusUnauthorized)
return
}
// Vérifier l'expiration du token
if exp, ok := claims["exp"].(float64); ok {
if time.Now().Unix() > int64(exp) {
fmt.Println("Erreur : token expiré")
http.Error(w, "Token expiré", http.StatusUnauthorized)
return
}
} else {
fmt.Println("Erreur : claim 'exp' introuvable ou invalide")
http.Error(w, "Token invalide", http.StatusUnauthorized)
return
}
// Extraire le champ 'username'
userID, ok := claims["username"].(string)
if !ok {
fmt.Println("Erreur : claim 'username' introuvable ou invalide")
http.Error(w, "Token invalide", http.StatusUnauthorized)
return
}
fmt.Println("Utilisateur authentifié :", userID)
// Injecter userID dans le contexte
ctx := context.WithValue(r.Context(), "username", userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// streamHandler écrit des messages en boucle