- go.mod module name
- All 714 import references across 289 Go files
- VERSION: 0.1.0
- CI DB names: switchboard_core_{ci,dev,test}
- Docker image: gobha/switchboard-core
- Test fixtures: JWT issuer, repo names
- .env.example, docker-compose container name
- Compiles clean (go build exit 0)
61 lines
1.7 KiB
Go
61 lines
1.7 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"switchboard-core/auth"
|
|
"switchboard-core/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
|
|
}
|