Files
backend/internal/api/middleware.go
2025-06-18 09:01:14 +03:00

66 lines
1.6 KiB
Go

package api
import (
"context"
"net/http"
"os"
"strings"
"github.com/golang-jwt/jwt/v5"
)
type contextKey string
const UserIDContextKey = contextKey("userID")
// AuthMiddleware проверяет JWT токен и добавляет user_id в контекст запроса.
func AuthMiddleware(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, "Authorization header required", http.StatusUnauthorized)
return
}
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
if tokenString == authHeader {
http.Error(w, "Invalid token format", http.StatusUnauthorized)
return
}
jwtSecret := []byte(os.Getenv("JWT_SECRET_KEY"))
if len(jwtSecret) == 0 {
http.Error(w, "JWT secret not configured", http.StatusInternalServerError)
return
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return jwtSecret, nil
})
if err != nil || !token.Valid {
http.Error(w, "Invalid or expired token", http.StatusUnauthorized)
return
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
http.Error(w, "Invalid token claims", http.StatusUnauthorized)
return
}
userIDFloat, ok := claims["user_id"].(float64)
if !ok {
http.Error(w, "Invalid user_id in token", http.StatusUnauthorized)
return
}
userID := int(userIDFloat)
ctx := context.WithValue(r.Context(), UserIDContextKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}