axe/internal/auth/middleware.go
2026-10-18 22:07:25 +03:00

44 lines
1.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package auth
import (
"net/http"
"strings"
"github.com/gin-gonic/gin"
)
// Middleware пропускает запрос только с валидным Bearer-токеном и кладёт
// в контекст user_id и role; без токена или с ошибкой — 401.
func Middleware(secret string) gin.HandlerFunc {
return func(c *gin.Context) {
header := c.GetHeader("Authorization")
if !strings.HasPrefix(header, "Bearer ") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "no token"})
return
}
claims, err := ParseToken(secret, strings.TrimPrefix(header, "Bearer "))
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
return
}
c.Set("user_id", claims.UserID)
c.Set("role", claims.Role)
c.Next()
}
}
// RequireRole пропускает запрос, если роль в списке разрешённых.
// Ставится после Middleware: роль берётся из уже проверенного токена.
func RequireRole(roles ...string) gin.HandlerFunc {
return func(c *gin.Context) {
role := c.GetString("role")
for _, r := range roles {
if r == role {
c.Next()
return
}
}
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{"error": "forbidden"})
}
}