Files
tp/main_dc/yalarba/api_es/internal/middleware/auth.go
T
valitovgaziz bdcf6ad431 deleted: main_dc/yalarba/api_es/internal/handler/auth_handler.go
modified:   main_dc/yalarba/api_es/internal/handler/user_handler.go
	modified:   main_dc/yalarba/api_es/internal/middleware/auth.go
	modified:   main_dc/yalarba/api_es/internal/service/user_service.go
fix bag with secret key
2025-11-13 04:21:54 +05:00

67 lines
1.8 KiB
Go

package middleware
import (
"api_es/internal/utils"
"api_es/pkg/logger"
"context"
"net/http"
"strings"
"go.uber.org/zap"
)
type contextKey string
const (
UserIDKey contextKey = "userID"
UserEmailKey contextKey = "userEmail"
UserRoleKey contextKey = "userRole"
)
func AuthMiddleware(next http.Handler) http.Handler {
zapLogger := logger.Get()
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
zapLogger.Debug("Debug start AuthMiddleware")
authHeader := r.Header.Get("Authorization")
zapLogger.Debug("authHeader", zap.String("authHeader", authHeader))
if authHeader == "" {
http.Error(w, "Authorization header required", http.StatusUnauthorized)
return
}
tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
zapLogger.Debug("tokenString", zap.String("tokenString", tokenString))
if tokenString == "" {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
// Здесь нужно использовать ваш JWT утилити
jwtUtil := utils.NewJWTUtil("secret")
claims, err := jwtUtil.ValidateToken(tokenString)
if err != nil {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), UserIDKey, claims.UserID)
ctx = context.WithValue(ctx, UserEmailKey, claims.Email)
ctx = context.WithValue(ctx, UserRoleKey, claims.Role)
zapLogger.Debug("Debug end AuthMiddleware")
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func AdminMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role, ok := r.Context().Value(UserRoleKey).(string)
if !ok || role != "admin" {
http.Error(w, "Admin access required", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}