feat(19.6.1-01): administrator lifecycle and last-superuser protection
- activate, deactivate and restore as record and bulk actions; delete is the soft delete through deleted_at, never a hard delete - deleted admins listed and opened (unscoped), deleted/deactivated row states, Deleted filter (hide / only), preview status hint - deactivate and delete bump tokens_valid_after; activate and restore do not - self delete and self deactivate refused; outranking and last active superuser guarded on delete, deactivate and bulk rows (whole selection rolls back)
This commit is contained in:
@@ -25,23 +25,29 @@ type usersAdmin struct {
|
||||
}
|
||||
|
||||
var (
|
||||
_ pact.AdminController = usersAdmin{}
|
||||
_ pact.AdminPermissioned = usersAdmin{}
|
||||
_ pact.AdminRecordSource = usersAdmin{}
|
||||
_ pact.FormRecordTitle = usersAdmin{}
|
||||
_ FieldRelationProvider = usersAdmin{}
|
||||
_ pact.ListExtendQuery = usersAdmin{}
|
||||
_ pact.FormExtendQuery = usersAdmin{}
|
||||
_ pact.FormVirtualFields = usersAdmin{}
|
||||
_ pact.FormRules = usersAdmin{}
|
||||
_ pact.FilterOptions = usersAdmin{}
|
||||
_ pact.FormBeforeCreate = usersAdmin{}
|
||||
_ pact.FormBeforeUpdate = usersAdmin{}
|
||||
_ pact.FormAfterUpdate = usersAdmin{}
|
||||
_ RelationLockProvider = usersAdmin{}
|
||||
_ PermissionEditorProvider = usersAdmin{}
|
||||
_ recordDataExtender = usersAdmin{}
|
||||
_ schemaFieldHider = usersAdmin{}
|
||||
_ pact.AdminController = usersAdmin{}
|
||||
_ pact.AdminPermissioned = usersAdmin{}
|
||||
_ pact.AdminRecordSource = usersAdmin{}
|
||||
_ pact.FormRecordTitle = usersAdmin{}
|
||||
_ FieldRelationProvider = usersAdmin{}
|
||||
_ pact.ListExtendQuery = usersAdmin{}
|
||||
_ pact.FormExtendQuery = usersAdmin{}
|
||||
_ pact.FormVirtualFields = usersAdmin{}
|
||||
_ pact.FormRules = usersAdmin{}
|
||||
_ pact.FilterOptions = usersAdmin{}
|
||||
_ pact.FormBeforeCreate = usersAdmin{}
|
||||
_ pact.FormBeforeUpdate = usersAdmin{}
|
||||
_ pact.FormAfterUpdate = usersAdmin{}
|
||||
_ RelationLockProvider = usersAdmin{}
|
||||
_ PermissionEditorProvider = usersAdmin{}
|
||||
_ recordDataExtender = usersAdmin{}
|
||||
_ schemaFieldHider = usersAdmin{}
|
||||
_ pact.ListRowStates = usersAdmin{}
|
||||
_ pact.FormBeforeDelete = usersAdmin{}
|
||||
_ pact.FormAfterDelete = usersAdmin{}
|
||||
_ pact.HasAdminRecordActions = usersAdmin{}
|
||||
_ pact.HasAdminBulkActions = usersAdmin{}
|
||||
_ pact.AdminPartialData = usersAdmin{}
|
||||
)
|
||||
|
||||
func (usersAdmin) ID() string { return AdministratorsControllerID }
|
||||
@@ -137,24 +143,27 @@ func asBackendUser(model any) (*BackendUser, error) {
|
||||
return user, nil
|
||||
}
|
||||
|
||||
// ListExtendQuery hides superusers from an administrator who does not act
|
||||
// as a superuser (D-03): they are never listed, and a bulk selection never
|
||||
// ListExtendQuery includes deleted administrators (WinterCMS's
|
||||
// withTrashed), so they are listed with their row state and can be
|
||||
// restored, and hides superusers from an administrator who does not act as
|
||||
// a superuser (D-03): they are never listed, and a bulk selection never
|
||||
// resolves to one.
|
||||
func (usersAdmin) ListExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
return scopeSuperusers(ctx, db)
|
||||
return scopeAdministrators(ctx, db)
|
||||
}
|
||||
|
||||
// FormExtendQuery applies the same scope to every record lookup, so a
|
||||
// superuser's id is not found (404) for anyone else: show, the preview
|
||||
// partial, update, delete and record actions.
|
||||
// deleted administrator opens and a superuser's id is not found (404) for
|
||||
// anyone else: show, the preview partial, update, delete and record actions.
|
||||
func (usersAdmin) FormExtendQuery(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
return scopeSuperusers(ctx, db)
|
||||
return scopeAdministrators(ctx, db)
|
||||
}
|
||||
|
||||
func scopeSuperusers(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
func scopeAdministrators(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
if db == nil {
|
||||
return db
|
||||
}
|
||||
db = db.Unscoped()
|
||||
principal, _ := bouncer.User(ctx)
|
||||
if actsAsSuperuser(principal) {
|
||||
return db
|
||||
@@ -162,6 +171,259 @@ func scopeSuperusers(ctx context.Context, db *gorm.DB) *gorm.DB {
|
||||
return db.Where("backend_users.is_superuser = ?", false)
|
||||
}
|
||||
|
||||
// ListRowStates marks a deleted administrator deleted and a deactivated one
|
||||
// disabled; a row may carry both.
|
||||
func (usersAdmin) ListRowStates(_ context.Context, _ *gorm.DB, records []any) ([][]pact.RowState, error) {
|
||||
out := make([][]pact.RowState, len(records))
|
||||
for i, record := range records {
|
||||
user, err := asBackendUser(record)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if user.DeletedAt.Valid {
|
||||
out[i] = append(out[i], pact.RowStateDeleted)
|
||||
}
|
||||
if !user.IsActivated {
|
||||
out[i] = append(out[i], pact.RowStateDisabled)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// FormBeforeDelete refuses deleting yourself (D-08), an administrator who
|
||||
// outranks the editor (D-19) and the last active superuser (D-09). The
|
||||
// framework calls it for the form's delete and once per row inside the bulk
|
||||
// delete's transaction, so one refused row rolls the whole selection back.
|
||||
func (c usersAdmin) FormBeforeDelete(ctx context.Context, model any) error {
|
||||
user, err := asBackendUser(model)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
principal, _ := bouncer.User(ctx)
|
||||
if principal != nil && principal.ID == user.ID {
|
||||
return &ForbiddenError{Message: usersLang + "self_delete"}
|
||||
}
|
||||
if err := guardOutranked(ctx, c.registry(), principal, user); err != nil {
|
||||
return err
|
||||
}
|
||||
return guardLastSuperuser(ctx, user)
|
||||
}
|
||||
|
||||
// FormAfterDelete ends the deleted administrator's sessions (D-12). The
|
||||
// delete itself stays the framework's soft delete through deleted_at: a
|
||||
// backend user is never hard-deleted, so tokens, linked_by references and
|
||||
// attachments keep valid foreign keys (D-10). Personal API tokens stop
|
||||
// because the guard refuses a deleted administrator.
|
||||
func (usersAdmin) FormAfterDelete(ctx context.Context, model any) error {
|
||||
user, err := asBackendUser(model)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tx, ok := TxFromContext(ctx)
|
||||
if !ok {
|
||||
return errors.New("cabana: administrators: a delete needs its transaction")
|
||||
}
|
||||
cutoff := revocationCutoff()
|
||||
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped().
|
||||
Model(&BackendUser{}).Where("id = ?", user.ID).
|
||||
Update("tokens_valid_after", cutoff).Error
|
||||
}
|
||||
|
||||
// usersLifecycle is one lifecycle action of the Administrators screen,
|
||||
// shared by its record and bulk forms.
|
||||
type usersLifecycle struct {
|
||||
name string
|
||||
// applies is the action's Applies for a record; self is true on the
|
||||
// editor's own record.
|
||||
applies func(user *BackendUser, self bool) bool
|
||||
// run checks and writes one administrator through the action's
|
||||
// transaction.
|
||||
run func(ctx context.Context, c usersAdmin, db *gorm.DB, editor *bouncer.Principal, user *BackendUser) error
|
||||
}
|
||||
|
||||
func (c usersAdmin) lifecycles() []usersLifecycle {
|
||||
return []usersLifecycle{
|
||||
{
|
||||
name: "activate",
|
||||
applies: func(user *BackendUser, _ bool) bool {
|
||||
return !user.DeletedAt.Valid && !user.IsActivated
|
||||
},
|
||||
run: func(ctx context.Context, c usersAdmin, db *gorm.DB, editor *bouncer.Principal, user *BackendUser) error {
|
||||
if err := guardOutranked(ctx, c.registry(), editor, user); err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
return db.Model(&BackendUser{}).Where("id = ?", user.ID).
|
||||
Updates(map[string]any{"is_activated": true, "activated_at": now}).Error
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "deactivate",
|
||||
// Deactivate is not offered on your own record; the run still
|
||||
// refuses it (a bulk selection may hold it).
|
||||
applies: func(user *BackendUser, self bool) bool {
|
||||
return !user.DeletedAt.Valid && user.IsActivated && !self
|
||||
},
|
||||
run: func(ctx context.Context, c usersAdmin, db *gorm.DB, editor *bouncer.Principal, user *BackendUser) error {
|
||||
if editor != nil && editor.ID == user.ID {
|
||||
return &ForbiddenError{Message: usersLang + "self_deactivate"}
|
||||
}
|
||||
if err := guardOutranked(ctx, c.registry(), editor, user); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := guardLastSuperuser(ctx, user); err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Model(&BackendUser{}).Where("id = ?", user.ID).
|
||||
Updates(map[string]any{"is_activated": false, "tokens_valid_after": revocationCutoff()}).Error
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "restore",
|
||||
applies: func(user *BackendUser, _ bool) bool {
|
||||
return user.DeletedAt.Valid
|
||||
},
|
||||
run: func(ctx context.Context, c usersAdmin, db *gorm.DB, editor *bouncer.Principal, user *BackendUser) error {
|
||||
if err := guardOutranked(ctx, c.registry(), editor, user); err != nil {
|
||||
return err
|
||||
}
|
||||
return db.Model(&BackendUser{}).Where("id = ?", user.ID).
|
||||
Update("deleted_at", nil).Error
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// actionDB is the action's write transaction as a fresh, unscoped session.
|
||||
func actionDB(ctx context.Context) (*gorm.DB, error) {
|
||||
tx, ok := TxFromContext(ctx)
|
||||
if !ok {
|
||||
return nil, errors.New("cabana: administrators: an action needs its transaction")
|
||||
}
|
||||
return tx.Session(&gorm.Session{NewDB: true}).WithContext(ctx).Unscoped(), nil
|
||||
}
|
||||
|
||||
// AdminRecordActions are Activate, Deactivate and Restore on the preview
|
||||
// (D-10), each offered only while it applies; at most one applies at a time.
|
||||
// Every refusal is a ForbiddenError with a message (the admin's toast shows
|
||||
// only the message).
|
||||
func (c usersAdmin) AdminRecordActions() []pact.AdminRecordAction {
|
||||
lifecycles := c.lifecycles()
|
||||
out := make([]pact.AdminRecordAction, 0, len(lifecycles))
|
||||
for _, lifecycle := range lifecycles {
|
||||
lifecycle := lifecycle
|
||||
out = append(out, pact.AdminRecordAction{
|
||||
Name: lifecycle.name,
|
||||
Label: usersLang + lifecycle.name,
|
||||
Confirm: usersLang + lifecycle.name + "_confirm",
|
||||
Permissions: []string{PermissionManageUsers},
|
||||
Applies: func(ctx context.Context, record any) (bool, error) {
|
||||
user, err := asBackendUser(record)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
principal, _ := bouncer.User(ctx)
|
||||
return lifecycle.applies(user, principal != nil && principal.ID == user.ID), nil
|
||||
},
|
||||
Run: func(ctx context.Context, in pact.AdminRecordActionInput) (pact.AdminRecordActionResult, error) {
|
||||
user, err := asBackendUser(in.Record)
|
||||
if err != nil {
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
db, err := actionDB(ctx)
|
||||
if err != nil {
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
principal, _ := bouncer.User(ctx)
|
||||
if err := lifecycle.run(ctx, c, db, principal, user); err != nil {
|
||||
return pact.AdminRecordActionResult{}, err
|
||||
}
|
||||
return pact.AdminRecordActionResult{Message: usersLang + lifecycle.name + "d"}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AdminBulkActions are Activate, Deactivate and Restore on the selected
|
||||
// rows. A row the action does not apply to is skipped and not counted, the
|
||||
// editor's own row refuses a deactivate, and one refused row rolls the
|
||||
// whole selection back.
|
||||
func (c usersAdmin) AdminBulkActions() []pact.AdminBulkAction {
|
||||
lifecycles := c.lifecycles()
|
||||
out := make([]pact.AdminBulkAction, 0, len(lifecycles))
|
||||
for _, lifecycle := range lifecycles {
|
||||
lifecycle := lifecycle
|
||||
out = append(out, pact.AdminBulkAction{
|
||||
Name: lifecycle.name,
|
||||
Label: usersLang + lifecycle.name,
|
||||
Confirm: usersLang + lifecycle.name + "_selected_confirm",
|
||||
Permissions: []string{PermissionManageUsers},
|
||||
Run: func(ctx context.Context, in pact.AdminBulkActionInput) (pact.AdminBulkActionResult, error) {
|
||||
db, err := actionDB(ctx)
|
||||
if err != nil {
|
||||
return pact.AdminBulkActionResult{}, err
|
||||
}
|
||||
principal, _ := bouncer.User(ctx)
|
||||
affected := 0
|
||||
for _, record := range in.Records {
|
||||
user, err := asBackendUser(record)
|
||||
if err != nil {
|
||||
return pact.AdminBulkActionResult{}, err
|
||||
}
|
||||
// The editor's own row is checked by run, not skipped,
|
||||
// so a deactivate that selects it is refused.
|
||||
if !lifecycle.applies(user, false) {
|
||||
continue
|
||||
}
|
||||
if err := lifecycle.run(ctx, c, db, principal, user); err != nil {
|
||||
return pact.AdminBulkActionResult{}, err
|
||||
}
|
||||
affected++
|
||||
}
|
||||
result := pact.AdminBulkActionResult{Affected: affected}
|
||||
if affected == len(in.Records) {
|
||||
result.Message = usersLang + lifecycle.name + "d_selected"
|
||||
}
|
||||
return result, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// usersHintView is the view model of controllers/users/_hint.htm, the status
|
||||
// callout above the preview: the callout kind (danger or warning) and the
|
||||
// phrase keys of its title and text. It is empty when no state applies, and
|
||||
// the template then renders nothing.
|
||||
type usersHintView struct {
|
||||
Kind string
|
||||
Title string
|
||||
Text string
|
||||
}
|
||||
|
||||
// PartialData serves the preview header partial hint: one callout by
|
||||
// precedence deleted, deactivated, the editor's own account.
|
||||
func (usersAdmin) PartialData(ctx context.Context, name string, record any) (any, error) {
|
||||
if name != "hint" {
|
||||
return nil, fmt.Errorf("cabana: administrators: unknown partial %q", name)
|
||||
}
|
||||
user, ok := record.(*BackendUser)
|
||||
if !ok || user == nil {
|
||||
return usersHintView{}, nil
|
||||
}
|
||||
principal, _ := bouncer.User(ctx)
|
||||
switch {
|
||||
case user.DeletedAt.Valid:
|
||||
return usersHintView{Kind: "danger", Title: usersLang + "trashed_hint_title", Text: usersLang + "trashed_hint_desc"}, nil
|
||||
case !user.IsActivated:
|
||||
return usersHintView{Kind: "warning", Title: usersLang + "deactivated_hint_title", Text: usersLang + "deactivated_hint_desc"}, nil
|
||||
case principal != nil && principal.ID == user.ID:
|
||||
return usersHintView{Kind: "warning", Title: usersLang + "self_hint_title", Text: usersLang + "self_hint_desc"}, nil
|
||||
}
|
||||
return usersHintView{}, nil
|
||||
}
|
||||
|
||||
// extendRecordData sends the stored superuser flag to a superuser. The
|
||||
// is_superuser switch is a virtual field (the column is protected), and the
|
||||
// admin sends every field on save: without its stored value an untouched
|
||||
@@ -207,8 +469,15 @@ func (usersAdmin) FormRules(_ context.Context, op string) map[string]string {
|
||||
}
|
||||
}
|
||||
|
||||
// FilterOptions serves the role filter's choices: every role by name.
|
||||
// FilterOptions serves the role filter's choices, every role by name, and
|
||||
// the deleted filter's two choices.
|
||||
func (c usersAdmin) FilterOptions(scope string) []pact.Option {
|
||||
if scope == filterTrashed {
|
||||
return []pact.Option{
|
||||
{Value: trashedHide, Label: usersLang + "filter_deleted_hide"},
|
||||
{Value: trashedOnly, Label: usersLang + "filter_deleted_only"},
|
||||
}
|
||||
}
|
||||
if scope != filterByRole {
|
||||
return nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user