feat(admin): added admin panel

This commit is contained in:
2025-06-18 17:29:01 +03:00
parent a157fc1cc3
commit 2c682c5123
5 changed files with 119 additions and 16 deletions

View File

@@ -11,9 +11,9 @@ import (
type contextKey string
const UserIDContextKey = contextKey("userID")
const ClaimsContextKey = contextKey("claims")
// AuthMiddleware проверяет JWT токен и добавляет user_id в контекст запроса.
// AuthMiddleware проверяет JWT токен и добавляет claims в контекст запроса.
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
@@ -52,14 +52,28 @@ func AuthMiddleware(next http.Handler) http.Handler {
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)
// Добавляем claims в контекст
ctx := context.WithValue(r.Context(), ClaimsContextKey, claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
// AdminMiddleware проверяет, что пользователь аутентифицирован и имеет роль 'admin'.
func AdminMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Получаем claims из контекста
claims, ok := r.Context().Value(ClaimsContextKey).(jwt.MapClaims)
if !ok {
http.Error(w, "Could not get claims from context", http.StatusInternalServerError)
return
}
role, ok := claims["role"].(string)
if !ok || role != "admin" {
http.Error(w, "Forbidden: insufficient permissions", http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}