This repository has been archived on 2026-04-03. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
core/server/middleware/permissions.go
2026-03-07 19:58:43 +00:00

61 lines
1.8 KiB
Go

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"git.gobha.me/xcaliber/chat-switchboard/auth"
"git.gobha.me/xcaliber/chat-switchboard/store"
)
const permCacheKey = "resolved_permissions"
// RequirePermission returns middleware that enforces a named permission.
// Admin users bypass the check entirely. Permission resolution is cached in
// the request context — computed at most once per request regardless of how
// many RequirePermission middlewares are chained.
func RequirePermission(perm string, stores store.Stores) gin.HandlerFunc {
return func(c *gin.Context) {
role, _ := c.Get("role")
if role == "admin" {
c.Next()
return
}
userID := c.GetString("user_id")
perms, err := resolveAndCachePerms(c, stores, userID)
if err != nil || !perms[perm] {
c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
"error": "permission required: " + perm,
})
return
}
c.Next()
}
}
// resolveAndCachePerms loads the user's effective permissions once per request.
func resolveAndCachePerms(c *gin.Context, stores store.Stores, userID string) (map[string]bool, error) {
if cached, exists := c.Get(permCacheKey); exists {
return cached.(map[string]bool), nil
}
perms, err := auth.ResolvePermissions(c.Request.Context(), stores, userID)
if err != nil {
return nil, err
}
c.Set(permCacheKey, perms)
return perms, nil
}
// GetResolvedPermissions returns the cached permission set for the current
// request. Returns nil if not yet resolved (i.e. RequirePermission was not
// earlier in the chain). Callers in handlers can use this for conditional
// logic without triggering an extra DB round-trip.
func GetResolvedPermissions(c *gin.Context) map[string]bool {
if cached, exists := c.Get(permCacheKey); exists {
return cached.(map[string]bool)
}
return nil
}