Files
tp/main_dc/yalarba/api_yal/internal/middleware/auth.go
T
valitovgaziz d45c5841dc modified: main_dc/yalarba/api_yal/go.mod
modified:   main_dc/yalarba/api_yal/go.sum
	modified:   main_dc/yalarba/api_yal/internal/domain/auth/dto.go
	modified:   main_dc/yalarba/api_yal/internal/domain/auth/handler.go
	modified:   main_dc/yalarba/api_yal/internal/domain/auth/router.go
	modified:   main_dc/yalarba/api_yal/internal/domain/auth/servcie.go
	new file:   main_dc/yalarba/api_yal/internal/middleware/auth.go
	deleted:    main_dc/yalarba/api_yal/internal/middleware/authMiddleware.go
	modified:   main_dc/yalarba/api_yal/internal/router/router.go
set auth domain, not tested
2026-03-10 00:35:25 +05:00

101 lines
3.3 KiB
Go

package middleware
import (
"context"
"net/http"
"strings"
"api_yal/internal/logger"
"github.com/golang-jwt/jwt/v5"
"go.uber.org/zap"
)
type contextKey string
const (
// UserIDKey ключ для хранения ID пользователя в контексте
UserIDKey contextKey = "userID"
// UserEmailKey ключ для хранения email пользователя в контексте
UserEmailKey contextKey = "userEmail"
// UserRoleKey ключ для хранения роли пользователя в контексте
UserRoleKey contextKey = "userRole"
)
// AuthMiddleware создает middleware для проверки JWT токена
func AuthMiddleware(jwtSecret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
l := logger.Get()
// Получаем токен из заголовка Authorization
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
l.Debug("Отсутствует заголовок Authorization")
http.Error(w, "Authorization header required", http.StatusUnauthorized)
return
}
// Ожидаем формат "Bearer <token>"
parts := strings.Split(authHeader, " ")
if len(parts) != 2 || strings.ToLower(parts[0]) != "bearer" {
l.Debug("Неверный формат заголовка Authorization")
http.Error(w, "Invalid authorization header format", http.StatusUnauthorized)
return
}
tokenString := parts[1]
// Парсим и валидируем токен
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
// Проверяем метод подписи
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, jwt.ErrSignatureInvalid
}
return []byte(jwtSecret), nil
})
if err != nil || !token.Valid {
l.Debug("Невалидный токен: %v", zap.Error(err))
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
// Извлекаем claims
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
l.Debug("Не удалось извлечь claims из токена")
http.Error(w, "Invalid token claims", http.StatusUnauthorized)
return
}
// Добавляем информацию о пользователе в контекст
ctx := r.Context()
// Извлекаем userID из sub (subject)
if userID, ok := claims["sub"].(float64); ok {
ctx = context.WithValue(ctx, UserIDKey, uint(userID))
}
// Извлекаем email
if email, ok := claims["email"].(string); ok {
ctx = context.WithValue(ctx, UserEmailKey, email)
}
// Извлекаем роль
if role, ok := claims["role"].(string); ok {
ctx = context.WithValue(ctx, UserRoleKey, role)
}
// Передаем управление дальше с обновленным контекстом
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// AuthMiddlewareWithContext (для обратной совместимости)
func AuthMiddlewareWithContext(next http.Handler) http.Handler {
// Эта функция должна быть реализована в основном приложении
// с передачей jwtSecret из конфигурации
return next
}