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
Jeffrey Smith e4f0bdbd36
All checks were successful
CI/CD / detect-changes (push) Successful in 4s
CI/CD / e2e-smoke (push) Has been skipped
CI/CD / test-frontend (push) Successful in 6s
CI/CD / test-runners (push) Has been skipped
CI/CD / test-go-pg (push) Successful in 2m48s
CI/CD / test-sqlite (push) Successful in 2m49s
CI/CD / build-and-deploy (push) Successful in 28s
Feat v0.7.7 api tokens ext permissions (#61)
Co-authored-by: Jeffrey Smith <jasafpro@gmail.com>
Co-committed-by: Jeffrey Smith <jasafpro@gmail.com>
2026-04-02 19:11:47 +00:00

71 lines
2.2 KiB
Go

package middleware
import (
"net/http"
"github.com/gin-gonic/gin"
"armature/auth"
"armature/store"
)
const permCacheKey = "resolved_permissions"
// RequirePermission returns middleware that enforces a named permission.
// Permission resolution is cached in the request context — computed at most
// once per request regardless of how many RequirePermission middlewares are
// chained. Admins receive permissions through the Admins group.
func RequirePermission(perm string, stores store.Stores) gin.HandlerFunc {
return func(c *gin.Context) {
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.
// For PAT-authenticated requests, uses the token's stored permissions directly
// (git model: token retains permissions even if user later loses them).
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
}
// PAT path: use token's stored permissions directly
if c.GetString("auth_method") == "pat" {
if patPerms, exists := c.Get("pat_permissions"); exists {
perms := make(map[string]bool)
for _, p := range patPerms.([]string) {
perms[p] = true
}
c.Set(permCacheKey, perms)
return perms, nil
}
}
// JWT path: resolve from groups
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
}