Files
tp/main_dc/yalarba/api_es/internal/middleware/auth.go
T
valitovgaziz 1c74d12df6 modified: main_dc/yalarba/api_es/go.mod
modified:   main_dc/yalarba/api_es/go.sum
	new file:   main_dc/yalarba/api_es/internal/dto/user.go
	new file:   main_dc/yalarba/api_es/internal/handler/all_handlers.go
	new file:   main_dc/yalarba/api_es/internal/handler/auth_handler.go
	new file:   main_dc/yalarba/api_es/internal/handler/user_handler.go
	deleted:    main_dc/yalarba/api_es/internal/handlers/all_handlers.go
	deleted:    main_dc/yalarba/api_es/internal/handlers/auth_handler.go
	deleted:    main_dc/yalarba/api_es/internal/handlers/user_handler.go
	new file:   main_dc/yalarba/api_es/internal/middleware/auth.go
	deleted:    main_dc/yalarba/api_es/internal/repositories/user_repository.go
	new file:   main_dc/yalarba/api_es/internal/repository/user_repository.go
	new file:   main_dc/yalarba/api_es/internal/service/user_service.go
	new file:   main_dc/yalarba/api_es/internal/utils/jwt.go
add service, handler, repository for user model
2025-11-12 05:19:26 +05:00

58 lines
1.5 KiB
Go

package middleware
import (
"context"
"net/http"
"strings"
"api_es/internal/utils"
)
type contextKey string
const (
UserIDKey contextKey = "userID"
UserEmailKey contextKey = "userEmail"
UserRoleKey contextKey = "userRole"
)
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.Replace(authHeader, "Bearer ", "", 1)
if tokenString == "" {
http.Error(w, "Invalid token", http.StatusUnauthorized)
return
}
// Здесь нужно использовать ваш JWT утилити
jwtUtil := utils.NewJWTUtil("your-secret-key")
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)
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)
})
}