@@ -0,0 +1,86 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"gitea.d3m0k1d.ru/d3m0k1d/HellreigN/backend/internal/repository"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// TokenContextKey is the context key for storing authenticated token info.
|
||||
type TokenContextKey string
|
||||
|
||||
const tokenContextKey TokenContextKey = "token"
|
||||
|
||||
// AuthMiddleware validates that a Bearer token exists and is valid.
|
||||
// It stores the token info in the context for later use.
|
||||
// Returns 401 if token is missing or invalid.
|
||||
func (ag *AuthGroup) AuthMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
token := getTokenFromHeader(c)
|
||||
if token == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "missing authorization header"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// Look up user by token value
|
||||
tokens, err := ag.Repo.GetToken(token)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set(string(tokenContextKey), tokens)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequirePermission is a generic permission checker.
|
||||
func RequirePermission(check func(*repository.Tokens) bool) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
tokenVal, exists := c.Get(string(tokenContextKey))
|
||||
if !exists {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "authentication required"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
token, ok := tokenVal.(*repository.Tokens)
|
||||
if !ok {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "invalid token context"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
if !check(token) {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "insufficient permissions"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// RequireView requires permission_view.
|
||||
func RequireView() gin.HandlerFunc {
|
||||
return RequirePermission(func(t *repository.Tokens) bool {
|
||||
return t.PermissionView
|
||||
})
|
||||
}
|
||||
|
||||
// RequireManageAgent requires permission_manage_agent.
|
||||
func RequireManageAgent() gin.HandlerFunc {
|
||||
return RequirePermission(func(t *repository.Tokens) bool {
|
||||
return t.PermissionManage
|
||||
})
|
||||
}
|
||||
|
||||
// RequireAdmin requires permission_admin.
|
||||
func RequireAdmin() gin.HandlerFunc {
|
||||
return RequirePermission(func(t *repository.Tokens) bool {
|
||||
return t.PermissionAdmin
|
||||
})
|
||||
}
|
||||
Reference in New Issue
Block a user