Files

66 lines
1.7 KiB
Go
Raw Permalink Normal View History

package middleware
import (
"context"
"messenger/internal/api/responses"
"messenger/internal/models"
"messenger/internal/service"
"net/http"
"strings"
)
type contextKey string
const UserContextKey contextKey = "user"
func JWTAuth(authService *service.AuthService) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Получаем токен из заголовка Authorization
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
responses.Unauthorized(w, "missing authorization header")
return
}
// Проверяем формат Bearer token
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
responses.Unauthorized(w, "invalid authorization header format")
return
}
token := parts[1]
// Валидируем токен
user, err := authService.ValidateToken(token)
if err != nil {
responses.Unauthorized(w, "invalid or expired token")
return
}
// Сохраняем пользователя в контексте
ctx := context.WithValue(r.Context(), UserContextKey, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
func GetUserFromContext(ctx context.Context) *models.User {
user, ok := ctx.Value(UserContextKey).(*models.User)
if !ok {
return nil
}
return user
}
func RequireGlobalAdmin(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user := GetUserFromContext(r.Context())
if user == nil || !user.IsGlobalAdmin() {
responses.Forbidden(w, "global admin access required")
return
}
next.ServeHTTP(w, r)
})
}