54 lines
1.3 KiB
Go
54 lines
1.3 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"aggios-app/backend/internal/config"
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
type contextKey string
|
|
|
|
const UserIDKey contextKey = "userID"
|
|
|
|
// Auth validates JWT tokens
|
|
func Auth(cfg *config.Config) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
authHeader := r.Header.Get("Authorization")
|
|
if authHeader == "" {
|
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
bearerToken := strings.Split(authHeader, " ")
|
|
if len(bearerToken) != 2 || bearerToken[0] != "Bearer" {
|
|
http.Error(w, "Invalid token format", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
token, err := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(cfg.JWT.Secret), nil
|
|
})
|
|
|
|
if err != nil || !token.Valid {
|
|
http.Error(w, "Invalid token", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
claims, ok := token.Claims.(jwt.MapClaims)
|
|
if !ok {
|
|
http.Error(w, "Invalid token claims", http.StatusUnauthorized)
|
|
return
|
|
}
|
|
|
|
userID := claims["user_id"].(string)
|
|
ctx := context.WithValue(r.Context(), UserIDKey, userID)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|