43 lines
1.3 KiB
Go
43 lines
1.3 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
)
|
|
|
|
// ctxKey est un type privé pour les clefs de contexte (évite les collisions).
|
|
type ctxKey string
|
|
|
|
// userIDKey est la clef de contexte sous laquelle on stocke l'ID utilisateur authentifié.
|
|
const userIDKey ctxKey = "userID"
|
|
|
|
// RequireAuth est un middleware qui valide l'access token Bearer et injecte
|
|
// l'ID utilisateur dans le contexte de la requête.
|
|
func (a *API) RequireAuth(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
header := r.Header.Get("Authorization")
|
|
const prefix = "Bearer "
|
|
if !strings.HasPrefix(header, prefix) {
|
|
writeError(w, http.StatusUnauthorized, "en-tête Authorization manquant ou invalide")
|
|
return
|
|
}
|
|
tokenString := strings.TrimSpace(strings.TrimPrefix(header, prefix))
|
|
|
|
claims, err := a.Auth.ParseAccessToken(tokenString)
|
|
if err != nil {
|
|
writeError(w, http.StatusUnauthorized, "token invalide ou expiré")
|
|
return
|
|
}
|
|
|
|
ctx := context.WithValue(r.Context(), userIDKey, claims.UserID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
|
|
// userIDFromContext récupère l'ID utilisateur stocké par RequireAuth.
|
|
func userIDFromContext(ctx context.Context) string {
|
|
id, _ := ctx.Value(userIDKey).(string)
|
|
return id
|
|
}
|