package middleware import ( "bytes" "context" "encoding/json" "fmt" "io" "net/http" "strings" "time" "github.com/golang-jwt/jwt" ) var secretKey = []byte("secret-key") // AuthMiddleware protège les routes via JWT et redirige vers /login si non authentifié func AuthMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx, ok := RedirectToLoginIfUnauthenticated(w, r) if !ok { return } next.ServeHTTP(w, r.WithContext(ctx)) }) } func AuthWithTokenHandler() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { token := r.URL.Query().Get("token") if token == "" { http.Error(w, "Token JWT manquant", http.StatusBadRequest) return } // Facultatif : tu peux valider ici que le token est correct avant de le poser _, err := jwt.Parse(token, func(t *jwt.Token) (interface{}, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("méthode de signature invalide") } return []byte("secret-key"), nil }) if err != nil { http.Error(w, "Token invalide", http.StatusUnauthorized) return } // ✅ Pose le token comme cookie http.SetCookie(w, &http.Cookie{ Name: "token", Value: token, Path: "/", HttpOnly: true, Secure: true, // Obligatoire avec SameSite=None SameSite: http.SameSiteNoneMode, }) http.Redirect(w, r, "/dashboard", http.StatusSeeOther) } } // RedirectToLoginIfUnauthenticated vérifie le JWT et injecte ssoid dans le contexte, sinon redirige vers /login func RedirectToLoginIfUnauthenticated(w http.ResponseWriter, r *http.Request) (context.Context, bool) { var tokenString string if authHeader := r.Header.Get("Authorization"); strings.HasPrefix(authHeader, "Bearer ") { tokenString = strings.TrimPrefix(authHeader, "Bearer ") } if tokenString == "" { if cookie, err := r.Cookie("token"); err == nil { tokenString = cookie.Value } } if tokenString == "" && r.Method == http.MethodPost || r.Method == http.MethodPut { if strings.Contains(r.Header.Get("Content-Type"), "application/json") { bodyCopy, _ := io.ReadAll(r.Body) var bodyMap map[string]interface{} if err := json.Unmarshal(bodyCopy, &bodyMap); err == nil { if val, ok := bodyMap["token"].(string); ok { tokenString = val r.Body = io.NopCloser(bytes.NewReader(bodyCopy)) } } } } if tokenString == "" { http.Redirect(w, r, "/login", http.StatusSeeOther) return nil, false } token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("méthode signature invalide") } return secretKey, nil }) if err != nil || !token.Valid { http.Redirect(w, r, "/login", http.StatusSeeOther) return nil, false } claims, ok := token.Claims.(jwt.MapClaims) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return nil, false } if exp, ok := claims["exp"].(float64); ok { if time.Now().Unix() > int64(exp) { http.Redirect(w, r, "/login", http.StatusSeeOther) return nil, false } } ssoid, ok := claims["username"].(string) if !ok || ssoid == "" { http.Redirect(w, r, "/login", http.StatusSeeOther) return nil, false } ctx := context.WithValue(r.Context(), "ssoid", ssoid) return ctx, true }