3x-ui/web/middleware/role_required.go
2025-10-08 00:56:59 +03:00

28 lines
684 B
Go
Raw 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 middleware
import (
"net/http"
"github.com/gin-gonic/gin"
)
// RoleRequired проверяет, есть ли у пользователя нужная роль.
func RoleRequired(roles ...string) gin.HandlerFunc {
allowed := make(map[string]bool)
for _, r := range roles {
allowed[r] = true
}
return func(c *gin.Context) {
roleVal, exists := c.Get("role") // где-то до этого роль должна быть положена в контекст
if !exists {
c.AbortWithStatus(http.StatusUnauthorized)
return
}
role, ok := roleVal.(string)
if !ok || !allowed[role] {
c.AbortWithStatus(http.StatusForbidden)
return
}
c.Next()
}
}