// SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini package main import "slices" const ( accessNone = "none" accessSession = "session" accessZone = "zone" accessAdmin = "admin" ) type accessDecision int const ( accessAllowed accessDecision = iota accessUnauthenticated accessForbidden accessNotFound ) func authorize(access string, p *principal, delegated bool) accessDecision { if access == accessNone { return accessAllowed } if p == nil { return accessUnauthenticated } switch access { case accessAdmin: if !p.isAdmin() { return accessForbidden } case accessZone: if !p.isAdmin() && !delegated { return accessNotFound } } return accessAllowed } func needsDelegation(access string, p principal) bool { return access == accessZone && !p.isAdmin() } func canAccessZone(p principal, zone string, delegated map[string]bool) bool { return p.isAdmin() || (p.User.Role == roleUser && delegated[zone]) } func visibleZones(p principal, zones []string, delegated map[string]bool) []string { out := make([]string, 0, len(zones)) for _, z := range zones { if canAccessZone(p, z, delegated) { out = append(out, z) } } return out } func isOwnAccount(p principal, username string) bool { return p.User.Username == username } func delegationTargetError(target userRow) *apiError { if target.DeletedAt.Valid { return errUserNotFound() } if target.Role != roleUser { return &apiError{Status: 422, Message: "zones cannot be delegated to admins", Fields: map[string]string{"username": "user is an admin and needs no delegation"}} } return nil } func leavesNoActiveAdmin(target userRow, activeAdmins []userRow) bool { if target.Role != roleAdmin || target.DeletedAt.Valid { return false } return !slices.ContainsFunc(activeAdmins, func(u userRow) bool { return u.ID != target.ID }) }