65 lines
1.4 KiB
Go
65 lines
1.4 KiB
Go
package contexts
|
|
|
|
import (
|
|
"context"
|
|
|
|
"git.haelnorr.com/h/oslstats/internal/permissions"
|
|
"git.haelnorr.com/h/oslstats/internal/roles"
|
|
)
|
|
|
|
// Permissions retrieves the permission cache from context (type-safe)
|
|
func Permissions(ctx context.Context) *PermissionCache {
|
|
cache, ok := ctx.Value(PermissionCacheKey).(*PermissionCache)
|
|
if !ok {
|
|
return nil
|
|
}
|
|
return cache
|
|
}
|
|
|
|
type PermissionCache struct {
|
|
Permissions map[permissions.Permission]bool
|
|
Roles map[roles.Role]bool
|
|
HasWildcard bool
|
|
}
|
|
|
|
// HasPermission returns true if the cache contains the provided permission
|
|
func (p *PermissionCache) HasPermission(perm permissions.Permission) bool {
|
|
if p.HasWildcard {
|
|
return true
|
|
}
|
|
_, exists := p.Permissions[perm]
|
|
return exists
|
|
}
|
|
|
|
// HasAnyPermission returns true if the cache contains any of the provided permissions
|
|
func (p *PermissionCache) HasAnyPermission(perms []permissions.Permission) bool {
|
|
if p.HasWildcard {
|
|
return true
|
|
}
|
|
for _, perm := range perms {
|
|
_, exists := p.Permissions[perm]
|
|
if exists {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// HasAllPermissions returns true only if more than one permission is provided and the cache
|
|
// contains all the provided permissions
|
|
func (p *PermissionCache) HasAllPermissions(perms []permissions.Permission) bool {
|
|
if p.HasWildcard {
|
|
return true
|
|
}
|
|
if len(perms) == 0 {
|
|
return false
|
|
}
|
|
for _, perm := range perms {
|
|
_, exists := p.Permissions[perm]
|
|
if !exists {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|