whatapp-go-pvnet/backend/middleware/middleware.go

119 lines
3.3 KiB
Go
Raw Normal View History

2025-05-09 08:14:22 +00:00
package middleware
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"time"
"github.com/golang-jwt/jwt"
)
var secretKey = []byte("secret-key")
2025-05-11 07:57:12 +00:00
// AuthMiddleware protège les routes via JWT et redirige vers /login si non authentifié
2025-05-09 08:14:22 +00:00
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2025-05-11 07:57:12 +00:00
ctx, ok := RedirectToLoginIfUnauthenticated(w, r)
if !ok {
2025-05-09 08:14:22 +00:00
return
}
2025-05-11 07:57:12 +00:00
next.ServeHTTP(w, r.WithContext(ctx))
})
}
2025-05-11 08:45:42 +00:00
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: false, // true en prod
SameSite: http.SameSiteLaxMode,
})
http.Redirect(w, r, "/dashboard", http.StatusSeeOther)
}
}
2025-05-09 08:14:22 +00:00
2025-05-11 07:57:12 +00:00
// 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
2025-05-09 08:14:22 +00:00
2025-05-11 07:57:12 +00:00
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
2025-05-09 08:14:22 +00:00
}
2025-05-11 07:57:12 +00:00
}
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))
}
2025-05-09 08:14:22 +00:00
}
}
2025-05-11 07:57:12 +00:00
}
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")
2025-05-09 08:14:22 +00:00
}
2025-05-11 07:57:12 +00:00
return secretKey, nil
2025-05-09 08:14:22 +00:00
})
2025-05-11 07:57:12 +00:00
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
2025-05-09 08:14:22 +00:00
}