feat(19.6.1-01): administrator form with server-side privilege rules

- create and edit administrators: password (min 4, max 72 bytes, bcrypt
  at admin.password.bcrypt_cost), role picker, radio permission overrides,
  superuser switch; no mail on create
- superusers hidden from non-superusers in list, lookups and schemas;
  is_superuser projected to superusers so an untouched save keeps it
- save-path rules: superuser-only switch, role and permission ceilings,
  no outranking, no own role/flag/overrides/password change, last active
  superuser not demoted (advisory lock + count in the write tx)
- password set for another admin bumps tokens_valid_after
- role, superuser, activation and last sign-in list filters
This commit is contained in:
Jakub Zych
2026-10-22 11:08:12 +02:00
parent 7340241f22
commit 88401737c9
12 changed files with 1032 additions and 7 deletions

View File

@@ -3,7 +3,9 @@ package cabana
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
"strings"
"time"
@@ -70,6 +72,13 @@ type BackendUser struct {
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at"`
TokensValidAfter *time.Time `gorm:"column:tokens_valid_after"`
Role BackendUserRole
// priorRoleID is the stored role_id the Administrators screen saw
// before a save assigned the submitted role (priorLoaded set), so the
// save can refuse a change of the editor's own role after the
// assignment. Unexported: GORM and the admin's field binding skip it.
priorRoleID *uint
priorLoaded bool
}
func (BackendUser) TableName() string { return "backend_users" }
@@ -82,6 +91,44 @@ func (BackendUser) Fillable() []string {
return []string{"login", "email", "first_name", "last_name"}
}
// filterByRole is the Administrators list filter scope that keeps the
// holders of one role.
const filterByRole = "filterByRole"
// FilterScopes lists the scope names the Administrators list filters call.
func (BackendUser) FilterScopes() []string { return []string{filterByRole} }
// FilterScope narrows db for the scope name: filterByRole keeps the holders
// of the role whose id is value. Any other name, and a value that is not a
// role id, match nothing; a nil db is returned as it is.
func (BackendUser) FilterScope(name string, db *gorm.DB, value any) *gorm.DB {
if db == nil {
return db
}
if name != filterByRole {
return db.Where("1 = 0")
}
id, ok := filterID(value)
if !ok {
return db.Where("1 = 0")
}
return db.Where("backend_users.role_id = ?", id)
}
// filterID reads a filter value as a positive whole number, given as a
// number or as its decimal text.
func filterID(value any) (uint64, bool) {
if value == nil {
return 0, false
}
text := strings.TrimSpace(fmt.Sprint(value))
id, err := strconv.ParseUint(text, 10, 32)
if err != nil || id == 0 {
return 0, false
}
return id, true
}
// Rules are the administrator's admin save rules. The uniqueness of login
// and email, deleted administrators included and ignoring case, is checked
// by the Administrators screen itself.