mirror of
https://github.com/UNITRONIX/BetterDesk.git
synced 2026-11-24 01:52:12 +00:00
feat(users): allow changing a local account's username (#498)
The panel could not rename an administrator: PATCH /api/users/:id accepted only
role, password and email, and the edit dialog locked the username field.
`username` is not just a label. It is the primary key of address_books
(username, ab_type) and the lookup key in org_users and
strategy_assignments.target_key. Renaming only the users row would orphan the
address book and silently detach organisation membership and strategy
assignments, so the rename cascades in one transaction:
- Go: db.Database.RenameUser (SQLite + PostgreSQL) updates users, moves
address_books, follows org_users and strategy_assignments.target_key, deletes
a stale lockout on the target name and moves login_attempts. Collisions return
ErrUsernameTaken (409), bad names ErrInvalidUsername (400).
- Go API: PATCH /api/users/{id} accepts username, refuses LDAP/OIDC accounts
(the provider owns the name) and audits user_renamed.
- Console: db.renameUser with the same cascade for the auth.db store, the route
validates the name, surfaces 409/400, records user_renamed and best-effort
syncs to Go.
- UI: the username field is editable for local accounts with a warning that the
address book and group assignments follow and that the user is signed out.
- Account names now accept A-Z a-z 0-9 . _ @ - (3-64 chars) in the panel, the Go
server and the helper text, so names imported from LDAP/OIDC survive a rename.
Tests: betterdesk-server/db/rename_user_test.go (cascade, collision, invalid
name, missing user, format) and web-nodejs/tests/usernameRename.test.js
(cascade order, lockout handling, missing-table tolerance, format).
Refs #498
Reported-by: @Yamada993
Thanks: INSOLVE (Honorary); Marco Jakobs (@jacotec); MyNameisStitch (@MyNameisStitch); Redspin (@playerumpknow); muopc (@muopc)
This commit is contained in:
+7
-1
@@ -65,8 +65,14 @@
|
||||
rebuild the server. Workflow Actions are pinned to commit SHAs.
|
||||
|
||||
### Added
|
||||
- **Administrator username can be changed (issue #498).** `PATCH /api/users/:id`
|
||||
accepts `username` for local accounts: the rename cascades to the address book,
|
||||
organisation membership, strategy assignments and lockout history in one
|
||||
transaction, and the panel unlocks the field in the edit dialog with a warning.
|
||||
LDAP/OIDC accounts keep the name their provider issues. Account names now allow
|
||||
`A-Z a-z 0-9 . _ @ -` (3-64 characters).
|
||||
- `lib/enrollmentProof.js`, `lib/redirectHost.js`, `lib/safeJsonScript.js`,
|
||||
`lib/updateManifestSignature.js`.
|
||||
`lib/updateManifestSignature.js`, `lib/renameUserCascade.js`.
|
||||
- `scripts/security/pentest-local.sh` / `.ps1` local security gate and
|
||||
`scripts/check-security-regressions.sh` CI gate.
|
||||
- `docs/security/AUDIT_2026-11-13.md` with the full report and fix status.
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/http"
|
||||
@@ -710,6 +711,7 @@ func (s *Server) handleUpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
var body struct {
|
||||
Username string `json:"username,omitempty"`
|
||||
Password string `json:"password,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
}
|
||||
@@ -718,6 +720,45 @@ func (s *Server) handleUpdateUser(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
// Username change (issue #498, 2026-11-13). Provider-managed accounts keep
|
||||
// the name the IdP/Directory issues, otherwise the next login would recreate
|
||||
// the old identity. The rename cascades to address books, org membership and
|
||||
// strategy assignments in one transaction.
|
||||
if newUsername := strings.TrimSpace(body.Username); newUsername != "" && newUsername != user.Username {
|
||||
provider := user.AuthProvider
|
||||
if provider == "" {
|
||||
provider = db.AuthProviderLocal
|
||||
}
|
||||
if provider != db.AuthProviderLocal {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{
|
||||
"error": "Username is managed by the identity provider for LDAP/OIDC accounts",
|
||||
})
|
||||
return
|
||||
}
|
||||
if !db.ValidUsername(newUsername) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid username"})
|
||||
return
|
||||
}
|
||||
if err := s.db.RenameUser(id, newUsername); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, db.ErrUsernameTaken):
|
||||
writeJSON(w, http.StatusConflict, map[string]string{"error": "Username already exists"})
|
||||
case errors.Is(err, db.ErrInvalidUsername):
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "Invalid username"})
|
||||
default:
|
||||
log.Printf("api: rename user %d failed: %v", id, err)
|
||||
writeInternalError(w, err, "RenameUser")
|
||||
}
|
||||
return
|
||||
}
|
||||
if s.auditLog != nil {
|
||||
s.auditLog.Log(audit.ActionUserUpdated, s.remoteIP(r), newUsername, map[string]string{
|
||||
"renamed_from": user.Username,
|
||||
})
|
||||
}
|
||||
user.Username = newUsername
|
||||
}
|
||||
|
||||
if body.Password != "" {
|
||||
// Issue #148: LDAP/OIDC accounts have no usable local password. Setting
|
||||
// one here would re-open the dual-authentication hole, so reject it.
|
||||
|
||||
@@ -150,6 +150,11 @@ var (
|
||||
ErrPeerNotFound = errors.New("db: peer not found")
|
||||
ErrPeerIDExists = errors.New("db: peer ID already exists")
|
||||
ErrPeerIDSoftDeleted = errors.New("db: peer ID belongs to a deleted peer")
|
||||
// ErrUsernameTaken is returned by RenameUser when the target name is in use.
|
||||
ErrUsernameTaken = errors.New("db: username already exists")
|
||||
// ErrInvalidUsername is returned by RenameUser for a name that fails the
|
||||
// account-name format check.
|
||||
ErrInvalidUsername = errors.New("db: invalid username")
|
||||
)
|
||||
|
||||
// PeerMetric represents a single heartbeat metric data point.
|
||||
@@ -602,6 +607,10 @@ type Database interface {
|
||||
GetUserByID(id int64) (*User, error)
|
||||
ListUsers() ([]*User, error)
|
||||
UpdateUser(u *User) error
|
||||
// RenameUser changes a username and cascades to every table that keys on it
|
||||
// (address books, org membership, strategy assignments, lockouts). It runs in
|
||||
// one transaction and returns ErrUsernameTaken on a collision.
|
||||
RenameUser(id int64, newUsername string) error
|
||||
DeleteUser(id int64) error
|
||||
UpdateUserLogin(id int64) error
|
||||
UserCount() (int, error)
|
||||
|
||||
@@ -1836,7 +1836,78 @@ func (pg *PostgresDB) UpdateUser(u *User) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// DeleteUser removes a user by ID and clears org membership links (Issue #292).
|
||||
// RenameUser changes a username and cascades to the tables that key on it.
|
||||
// See the SQLite implementation for the rationale (issue #498, 2026-11-13).
|
||||
func (pg *PostgresDB) RenameUser(id int64, newUsername string) error {
|
||||
newUsername = strings.TrimSpace(newUsername)
|
||||
if !ValidUsername(newUsername) {
|
||||
return ErrInvalidUsername
|
||||
}
|
||||
|
||||
tx, err := pg.pool.Begin(pg.ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("db: RenameUser begin: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(pg.ctx) }()
|
||||
|
||||
var oldUsername string
|
||||
err = tx.QueryRow(pg.ctx, `SELECT username FROM users WHERE id = $1`, id).Scan(&oldUsername)
|
||||
if err == pgx.ErrNoRows {
|
||||
return ErrPeerNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("db: RenameUser load: %w", err)
|
||||
}
|
||||
if oldUsername == newUsername {
|
||||
return nil
|
||||
}
|
||||
|
||||
var taken int
|
||||
if err := tx.QueryRow(pg.ctx,
|
||||
`SELECT COUNT(*) FROM users WHERE username = $1 AND id <> $2`, newUsername, id).Scan(&taken); err != nil {
|
||||
return fmt.Errorf("db: RenameUser collision check: %w", err)
|
||||
}
|
||||
if taken > 0 {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(pg.ctx, `UPDATE users SET username = $1 WHERE id = $2`, newUsername, id); err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
return fmt.Errorf("db: RenameUser users: %w", err)
|
||||
}
|
||||
|
||||
// Address books are keyed by (username, ab_type).
|
||||
_, _ = tx.Exec(pg.ctx, `DELETE FROM address_books WHERE username = $1`, newUsername)
|
||||
if _, err := tx.Exec(pg.ctx,
|
||||
`UPDATE address_books SET username = $1 WHERE username = $2`, newUsername, oldUsername); err != nil {
|
||||
if !isMissingTable(err) {
|
||||
return fmt.Errorf("db: RenameUser address books: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Organisation membership and strategy assignments reference the name.
|
||||
_, _ = tx.Exec(pg.ctx, `UPDATE org_users SET username = $1 WHERE username = $2`, newUsername, oldUsername)
|
||||
_, _ = tx.Exec(pg.ctx,
|
||||
`UPDATE strategy_assignments SET target_key = $1 WHERE target_key = $2 AND target_type = 'user'`,
|
||||
newUsername, oldUsername)
|
||||
|
||||
// Stale lockout history must not lock the fresh name.
|
||||
_, _ = tx.Exec(pg.ctx, `DELETE FROM account_lockouts WHERE username = $1`, newUsername)
|
||||
if _, err := tx.Exec(pg.ctx,
|
||||
`UPDATE login_attempts SET username = $1 WHERE username = $2`, newUsername, oldUsername); err != nil {
|
||||
if !isMissingTable(err) {
|
||||
return fmt.Errorf("db: RenameUser attempts: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(pg.ctx); err != nil {
|
||||
return fmt.Errorf("db: RenameUser commit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (pg *PostgresDB) DeleteUser(id int64) error {
|
||||
if _, err := pg.pool.Exec(pg.ctx,
|
||||
`DELETE FROM org_users WHERE server_user_id = $1 AND server_user_id > 0`, id); err != nil {
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Issue #498 (2026-11-13): renaming a user must cascade to every table that
|
||||
// keys on the username, in one transaction, and must refuse collisions.
|
||||
func TestRenameUserCascadesAddressBookAndAssignments(t *testing.T) {
|
||||
database := newTestDB(t)
|
||||
defer database.Close()
|
||||
|
||||
user := &User{Username: "oldadmin", PasswordHash: "x", Role: "admin"}
|
||||
if err := database.CreateUser(user); err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
|
||||
if err := database.SaveAddressBook("oldadmin", "legacy", `{"peers":["1"]}`); err != nil {
|
||||
t.Fatalf("SaveAddressBook: %v", err)
|
||||
}
|
||||
|
||||
if err := database.RenameUser(user.ID, "newadmin"); err != nil {
|
||||
t.Fatalf("RenameUser: %v", err)
|
||||
}
|
||||
|
||||
renamed, err := database.GetUserByID(user.ID)
|
||||
if err != nil || renamed == nil {
|
||||
t.Fatalf("GetUserByID: %v %+v", err, renamed)
|
||||
}
|
||||
if renamed.Username != "newadmin" {
|
||||
t.Fatalf("username = %q, want newadmin", renamed.Username)
|
||||
}
|
||||
|
||||
if old, err := database.GetUser("oldadmin"); err != nil {
|
||||
t.Fatalf("GetUser(old): %v", err)
|
||||
} else if old != nil {
|
||||
t.Fatalf("old username still resolves: %+v", old)
|
||||
}
|
||||
|
||||
book, err := database.GetAddressBook("newadmin", "legacy")
|
||||
if err != nil {
|
||||
t.Fatalf("GetAddressBook: %v", err)
|
||||
}
|
||||
if book == "" {
|
||||
t.Fatal("address book did not follow the rename")
|
||||
}
|
||||
if stale, err := database.GetAddressBook("oldadmin", "legacy"); err != nil {
|
||||
t.Fatalf("GetAddressBook(old): %v", err)
|
||||
} else if stale != "{}" {
|
||||
t.Fatalf("address book left under the old name: %q", stale)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameUserRejectsCollision(t *testing.T) {
|
||||
database := newTestDB(t)
|
||||
defer database.Close()
|
||||
|
||||
first := &User{Username: "alice", PasswordHash: "x", Role: "admin"}
|
||||
second := &User{Username: "bob", PasswordHash: "x", Role: "viewer"}
|
||||
if err := database.CreateUser(first); err != nil {
|
||||
t.Fatalf("CreateUser alice: %v", err)
|
||||
}
|
||||
if err := database.CreateUser(second); err != nil {
|
||||
t.Fatalf("CreateUser bob: %v", err)
|
||||
}
|
||||
|
||||
err := database.RenameUser(first.ID, "bob")
|
||||
if !errors.Is(err, ErrUsernameTaken) {
|
||||
t.Fatalf("RenameUser collision err = %v, want ErrUsernameTaken", err)
|
||||
}
|
||||
|
||||
if still, _ := database.GetUser("alice"); still == nil {
|
||||
t.Fatal("alice must be unchanged after a refused rename")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameUserRejectsInvalidName(t *testing.T) {
|
||||
database := newTestDB(t)
|
||||
defer database.Close()
|
||||
|
||||
user := &User{Username: "carol", PasswordHash: "x", Role: "admin"}
|
||||
if err := database.CreateUser(user); err != nil {
|
||||
t.Fatalf("CreateUser: %v", err)
|
||||
}
|
||||
|
||||
for _, bad := range []string{"", " ", "a", "has space", "../etc", "x/y", "a&b"} {
|
||||
if err := database.RenameUser(user.ID, bad); !errors.Is(err, ErrInvalidUsername) {
|
||||
t.Errorf("RenameUser(%q) err = %v, want ErrInvalidUsername", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameUserMissingUser(t *testing.T) {
|
||||
database := newTestDB(t)
|
||||
defer database.Close()
|
||||
|
||||
if err := database.RenameUser(9999, "ghost"); !errors.Is(err, ErrPeerNotFound) {
|
||||
t.Fatalf("RenameUser missing err = %v, want ErrPeerNotFound", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidUsername(t *testing.T) {
|
||||
for _, ok := range []string{"admin", "ops.admin", "ops_admin", "ops-admin", "ops@example"} {
|
||||
if !ValidUsername(ok) {
|
||||
t.Errorf("ValidUsername(%q) = false, want true", ok)
|
||||
}
|
||||
}
|
||||
for _, bad := range []string{"", "ab", "a b", "a/b", "../x", "a&b", "a\nb"} {
|
||||
if ValidUsername(bad) {
|
||||
t.Errorf("ValidUsername(%q) = true, want false", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2190,6 +2190,86 @@ func (s *SQLiteDB) UpdateUser(u *User) error {
|
||||
return err
|
||||
}
|
||||
|
||||
// RenameUser changes a username and cascades to the tables that key on it.
|
||||
//
|
||||
// Issue #498 (2026-11-13): the panel could not change an administrator's login
|
||||
// name. `username` is the primary key of `address_books` and a lookup key in
|
||||
// `org_users` and `strategy_assignments.target_key`, so the rename has to be one
|
||||
// transaction; a partial rename would orphan an address book or silently detach
|
||||
// org membership and strategy assignments.
|
||||
func (s *SQLiteDB) RenameUser(id int64, newUsername string) error {
|
||||
newUsername = strings.TrimSpace(newUsername)
|
||||
if !ValidUsername(newUsername) {
|
||||
return ErrInvalidUsername
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
tx, err := s.db.Begin()
|
||||
if err != nil {
|
||||
return fmt.Errorf("db: RenameUser begin: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback() }()
|
||||
|
||||
var oldUsername string
|
||||
err = tx.QueryRow(`SELECT username FROM users WHERE id = ?`, id).Scan(&oldUsername)
|
||||
if err == sql.ErrNoRows {
|
||||
return ErrPeerNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("db: RenameUser load: %w", err)
|
||||
}
|
||||
if oldUsername == newUsername {
|
||||
return nil
|
||||
}
|
||||
|
||||
var taken int
|
||||
if err := tx.QueryRow(`SELECT COUNT(*) FROM users WHERE username = ? AND id <> ?`, newUsername, id).Scan(&taken); err != nil {
|
||||
return fmt.Errorf("db: RenameUser collision check: %w", err)
|
||||
}
|
||||
if taken > 0 {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
|
||||
if _, err := tx.Exec(`UPDATE users SET username = ? WHERE id = ?`, newUsername, id); err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return ErrUsernameTaken
|
||||
}
|
||||
return fmt.Errorf("db: RenameUser users: %w", err)
|
||||
}
|
||||
|
||||
// Address books are keyed by (username, ab_type): rename in place, and drop
|
||||
// any book already stored under the new name to avoid a PK conflict.
|
||||
_, _ = tx.Exec(`DELETE FROM address_books WHERE username = ?`, newUsername)
|
||||
if _, err := tx.Exec(`UPDATE address_books SET username = ? WHERE username = ?`, newUsername, oldUsername); err != nil {
|
||||
if !isMissingTable(err) {
|
||||
return fmt.Errorf("db: RenameUser address books: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Organisation membership and strategy assignments reference the name, not
|
||||
// the id, so they must follow the rename.
|
||||
_, _ = tx.Exec(`UPDATE org_users SET username = ? WHERE username = ?`, newUsername, oldUsername)
|
||||
_, _ = tx.Exec(
|
||||
`UPDATE strategy_assignments SET target_key = ? WHERE target_key = ? AND target_type = 'user'`,
|
||||
newUsername, oldUsername,
|
||||
)
|
||||
|
||||
// Stale lockout history must not lock the fresh name.
|
||||
_, _ = tx.Exec(`DELETE FROM account_lockouts WHERE username = ?`, newUsername)
|
||||
if _, err := tx.Exec(`UPDATE login_attempts SET username = ? WHERE username = ?`, newUsername, oldUsername); err != nil {
|
||||
if !isMissingTable(err) {
|
||||
return fmt.Errorf("db: RenameUser attempts: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return fmt.Errorf("db: RenameUser commit: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DeleteUser removes a user by ID and clears org membership links (Issue #292).
|
||||
func (s *SQLiteDB) DeleteUser(id int64) error {
|
||||
s.mu.Lock()
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// usernamePattern is the account-name format accepted everywhere in the product.
|
||||
// It matches the console's client-side check (`^[a-zA-Z0-9_]{3,32}$` plus the
|
||||
// wider set allowed for imported identities) and never permits whitespace, path
|
||||
// separators or control characters — a username ends up in filesystem paths,
|
||||
// audit log lines and address-book keys.
|
||||
var usernamePattern = regexp.MustCompile(`^[A-Za-z0-9_.@-]{3,64}$`)
|
||||
|
||||
// ValidUsername reports whether name is an acceptable account name.
|
||||
func ValidUsername(name string) bool {
|
||||
trimmed := strings.TrimSpace(name)
|
||||
if trimmed == "" || trimmed != name {
|
||||
return false
|
||||
}
|
||||
return usernamePattern.MatchString(trimmed)
|
||||
}
|
||||
|
||||
// isUniqueViolation reports whether err is a uniqueness conflict from either
|
||||
// backend. SQLite says "UNIQUE constraint failed"; PostgreSQL says
|
||||
// "duplicate key value violates unique constraint".
|
||||
func isUniqueViolation(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "unique constraint failed") ||
|
||||
strings.Contains(msg, "duplicate key value violates unique constraint") ||
|
||||
strings.Contains(msg, "sqlite_constraint_unique")
|
||||
}
|
||||
|
||||
// isMissingTable reports whether err is "no such table" / "does not exist".
|
||||
// Older databases predate some tables, and a rename must not fail because an
|
||||
// optional table was never created.
|
||||
func isMissingTable(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := strings.ToLower(err.Error())
|
||||
return strings.Contains(msg, "no such table") ||
|
||||
strings.Contains(msg, "does not exist")
|
||||
}
|
||||
@@ -1219,6 +1219,7 @@
|
||||
"username": "اسم المستخدم",
|
||||
"username_placeholder": "أدخل اسم المستخدم",
|
||||
"username_hint": "3-32 حرفًا وحرفًا وأرقامًا وشرطات سفلية فقط",
|
||||
"username_change_warning": "تغيير اسم المستخدم يحدّث أيضًا دفتر العناوين وتعيينات المجموعات ويسجّل خروج المستخدم من كل الأجهزة.",
|
||||
"password": "كلمة المرور",
|
||||
"password_placeholder": "أدخل كلمة المرور",
|
||||
"password_hint": "الحد الأدنى 8 أحرف مع حالة مختلطة وأرقام ورموز",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "Uživatelské jméno",
|
||||
"username_placeholder": "Zadejte uživatelské jméno",
|
||||
"username_hint": "3–32 znaků, pouze písmena, číslice a podtržítka",
|
||||
"username_change_warning": "Změna uživatelského jména aktualizuje také adresář, přiřazení skupin a odhlásí uživatele ze všech zařízení.",
|
||||
"password": "Heslo",
|
||||
"password_placeholder": "Zadejte heslo",
|
||||
"password_hint": "Minimálně 8 znaků, s malými a velkými písmeny, čísly a symboly",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Brugernavn",
|
||||
"username_placeholder": "Indtast brugernavn",
|
||||
"username_hint": "Kun 3-32 tegn, bogstaver, tal og understregninger",
|
||||
"username_change_warning": "Ændring af brugernavnet opdaterer også adressebogen, gruppetildelinger og logger brugeren ud overalt.",
|
||||
"password": "Adgangskode",
|
||||
"password_placeholder": "Indtast adgangskode",
|
||||
"password_hint": "Minimum 8 tegn med blandet store og små bogstaver, tal og symboler",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "Benutzername",
|
||||
"username_placeholder": "Benutzername eingeben",
|
||||
"username_hint": "3-32 Zeichen, nur Buchstaben, Zahlen und Unterstriche",
|
||||
"username_change_warning": "Das Ändern des Benutzernamens aktualisiert auch das Adressbuch und Gruppenzuweisungen und meldet den Benutzer überall ab.",
|
||||
"password": "Passwort",
|
||||
"password_placeholder": "Passwort eingeben",
|
||||
"password_hint": "Mindestens 8 Zeichen mit Groß-/Kleinbuchstaben, Zahlen und Sonderzeichen",
|
||||
|
||||
@@ -1232,7 +1232,8 @@
|
||||
"edit_user": "Edit User",
|
||||
"username": "Username",
|
||||
"username_placeholder": "Enter username",
|
||||
"username_hint": "3-32 characters, letters, numbers and underscores only",
|
||||
"username_hint": "3-64 characters: letters, numbers, dot, underscore, at-sign or hyphen",
|
||||
"username_change_warning": "Changing the username also updates the address book, group assignments and signs the user out everywhere.",
|
||||
"password": "Password",
|
||||
"password_placeholder": "Enter password",
|
||||
"password_hint": "Minimum 8 characters with mixed case, numbers and symbols",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "Nombre de usuario",
|
||||
"username_placeholder": "Introduzca el nombre de usuario",
|
||||
"username_hint": "3-32 caracteres, solo letras, números y guiones bajos",
|
||||
"username_change_warning": "Cambiar el nombre de usuario también actualiza la libreta de direcciones y las asignaciones de grupos, y cierra la sesión del usuario en todas partes.",
|
||||
"password": "Contraseña",
|
||||
"password_placeholder": "Introduzca la contraseña",
|
||||
"password_hint": "Mínimo 8 caracteres con mayúsculas, minúsculas, números y símbolos",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Käyttäjätunnus",
|
||||
"username_placeholder": "Anna käyttäjänimi",
|
||||
"username_hint": "Vain 3-32 merkkiä, kirjaimia, numeroita ja alaviivoja",
|
||||
"username_change_warning": "Käyttäjänimen muuttaminen päivittää myös osoitekirjan ja ryhmämääritykset sekä kirjaa käyttäjän ulos kaikkialta.",
|
||||
"password": "Salasana",
|
||||
"password_placeholder": "Anna salasana",
|
||||
"password_hint": "Vähintään 8 merkkiä sekakokoisina isoilla kirjaimilla, numeroilla ja symboleilla",
|
||||
|
||||
@@ -1229,6 +1229,7 @@
|
||||
"username": "Nom d'utilisateur",
|
||||
"username_placeholder": "Entrez le nom d'utilisateur",
|
||||
"username_hint": "3-32 caractères, lettres, chiffres et underscores uniquement",
|
||||
"username_change_warning": "Modifier le nom d'utilisateur met aussi à jour le carnet d'adresses et les affectations de groupes, et déconnecte l'utilisateur partout.",
|
||||
"password": "Mot de passe",
|
||||
"password_placeholder": "Entrez le mot de passe",
|
||||
"password_hint": "Minimum 8 caractères avec majuscules, minuscules, chiffres et symboles",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "उपयोगकर्ता नाम",
|
||||
"username_placeholder": "उपयोक्तानाम दर्ज करें",
|
||||
"username_hint": "केवल 3-32 अक्षर, अक्षर, संख्याएँ और अंडरस्कोर",
|
||||
"username_change_warning": "उपयोगकर्ता नाम बदलने से पता पुस्तिका और समूह असाइनमेंट भी अपडेट होते हैं और उपयोगकर्ता हर जगह साइन आउट हो जाता है।",
|
||||
"password": "पासवर्ड",
|
||||
"password_placeholder": "पास वर्ड दर्ज करें",
|
||||
"password_hint": "मिश्रित केस, संख्याओं और प्रतीकों के साथ न्यूनतम 8 अक्षर",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Felhasználónév",
|
||||
"username_placeholder": "Adja meg a felhasználónevet",
|
||||
"username_hint": "Csak 3-32 karakter, betűk, számok és aláhúzás",
|
||||
"username_change_warning": "A felhasználónév módosítása frissíti a címjegyzéket és a csoport-hozzárendeléseket, valamint mindenhol kijelentkezteti a felhasználót.",
|
||||
"password": "Jelszó",
|
||||
"password_placeholder": "Írja be a jelszót",
|
||||
"password_hint": "Legalább 8 karakter vegyes kis- és nagybetűkkel, számokkal és szimbólumokkal",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Nama pengguna",
|
||||
"username_placeholder": "Masukkan nama pengguna",
|
||||
"username_hint": "3-32 karakter, huruf, angka dan garis bawah saja",
|
||||
"username_change_warning": "Mengubah nama pengguna juga memperbarui buku alamat dan penetapan grup, serta mengeluarkan pengguna dari semua sesi.",
|
||||
"password": "Kata sandi",
|
||||
"password_placeholder": "Masukkan kata sandi",
|
||||
"password_hint": "Minimal 8 karakter dengan campuran huruf besar-kecil, angka dan simbol",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "Nome utente",
|
||||
"username_placeholder": "Inserisci il nome utente",
|
||||
"username_hint": "3-32 caratteri, solo lettere, numeri e underscore",
|
||||
"username_change_warning": "Cambiare il nome utente aggiorna anche la rubrica e le assegnazioni dei gruppi e disconnette l'utente ovunque.",
|
||||
"password": "Parola d’accesso",
|
||||
"password_placeholder": "Inserisci la password",
|
||||
"password_hint": "Minimo 8 caratteri con maiuscole, minuscole, numeri e simboli",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "ユーザー名",
|
||||
"username_placeholder": "ユーザー名を入力してください",
|
||||
"username_hint": "3 ~ 32 文字、文字、数字、アンダースコアのみ",
|
||||
"username_change_warning": "ユーザー名を変更すると、アドレス帳とグループ割り当ても更新され、すべての場所でサインアウトされます。",
|
||||
"password": "パスワード",
|
||||
"password_placeholder": "パスワードを入力してください",
|
||||
"password_hint": "大文字と小文字を混合した少なくとも 8 文字、数字、記号",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "사용자 이름",
|
||||
"username_placeholder": "사용자 이름을 입력하세요",
|
||||
"username_hint": "3~32자, 문자, 숫자, 밑줄만 가능",
|
||||
"username_change_warning": "사용자 이름을 변경하면 주소록과 그룹 할당도 업데이트되고 모든 곳에서 로그아웃됩니다.",
|
||||
"password": "비밀번호",
|
||||
"password_placeholder": "비밀번호를 입력하세요",
|
||||
"password_hint": "대소문자, 숫자, 기호를 혼합하여 최소 8자 이상",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Brukernavn",
|
||||
"username_placeholder": "Skriv inn brukernavn",
|
||||
"username_hint": "Kun 3-32 tegn, bokstaver, tall og understreker",
|
||||
"username_change_warning": "Endring av brukernavnet oppdaterer også adresseboken og gruppetilordninger, og logger brukeren ut overalt.",
|
||||
"password": "Passord",
|
||||
"password_placeholder": "Skriv inn passord",
|
||||
"password_hint": "Minimum 8 tegn med blandet store og små bokstaver, tall og symboler",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "Gebruikersnaam",
|
||||
"username_placeholder": "Voer gebruikersnaam in",
|
||||
"username_hint": "3-32 tekens, alleen letters, cijfers en underscores",
|
||||
"username_change_warning": "Het wijzigen van de gebruikersnaam werkt ook het adresboek en de groepsindelingen bij en meldt de gebruiker overal af.",
|
||||
"password": "Wachtwoord",
|
||||
"password_placeholder": "Voer wachtwoord in",
|
||||
"password_hint": "Minimaal 8 tekens met hoofdletters, kleine letters, cijfers en symbolen",
|
||||
|
||||
@@ -1225,6 +1225,7 @@
|
||||
"username": "Nazwa użytkownika",
|
||||
"username_placeholder": "Wprowadź nazwę użytkownika",
|
||||
"username_hint": "3-32 znaki, tylko litery, cyfry i podkreślenia",
|
||||
"username_change_warning": "Zmiana nazwy użytkownika aktualizuje także książkę adresową i przypisania grup oraz wylogowuje użytkownika wszędzie.",
|
||||
"password": "Hasło",
|
||||
"password_placeholder": "Wprowadź hasło",
|
||||
"password_hint": "Minimum 8 znaków z dużymi literami, cyframi i symbolami",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "Nome de utilizador",
|
||||
"username_placeholder": "Insira o nome de utilizador",
|
||||
"username_hint": "3-32 caracteres, apenas letras, números e underscores",
|
||||
"username_change_warning": "Alterar o nome de utilizador também atualiza a agenda de endereços e as atribuições de grupos, e termina a sessão em todo o lado.",
|
||||
"password": "Palavra-passe",
|
||||
"password_placeholder": "Insira a palavra-passe",
|
||||
"password_hint": "Mínimo 8 caracteres com maiúsculas, minúsculas, números e símbolos",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Nume de utilizator",
|
||||
"username_placeholder": "Introduceți numele de utilizator",
|
||||
"username_hint": "Doar 3-32 de caractere, litere, cifre și caractere de subliniere",
|
||||
"username_change_warning": "Schimbarea numelui de utilizator actualizează și agenda și atribuirile de grup și deconectează utilizatorul peste tot.",
|
||||
"password": "Parolă",
|
||||
"password_placeholder": "Introduceți parola",
|
||||
"password_hint": "Minim 8 caractere cu majuscule, numere și simboluri mixte",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Användarnamn",
|
||||
"username_placeholder": "Ange användarnamn",
|
||||
"username_hint": "Endast 3-32 tecken, bokstäver, siffror och understreck",
|
||||
"username_change_warning": "Att ändra användarnamnet uppdaterar även adressboken och grupptilldelningar och loggar ut användaren överallt.",
|
||||
"password": "Lösenord",
|
||||
"password_placeholder": "Ange lösenord",
|
||||
"password_hint": "Minst 8 tecken med blandade versaler, siffror och symboler",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "ชื่อผู้ใช้",
|
||||
"username_placeholder": "กรอกชื่อผู้ใช้",
|
||||
"username_hint": "3-32 ตัวอักษร ตัวอักษร ตัวเลข และขีดล่างเท่านั้น",
|
||||
"username_change_warning": "การเปลี่ยนชื่อผู้ใช้จะอัปเดตสมุดที่อยู่และการกำหนดกลุ่มด้วย และจะออกจากระบบในทุกที่",
|
||||
"password": "รหัสผ่าน",
|
||||
"password_placeholder": "ใส่รหัสผ่าน",
|
||||
"password_hint": "ขั้นต่ำ 8 ตัวอักษร โดยมีทั้งตัวพิมพ์เล็ก ตัวเลข และสัญลักษณ์ผสมกัน",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Kullanıcı adı",
|
||||
"username_placeholder": "Kullanıcı adını girin",
|
||||
"username_hint": "Yalnızca 3-32 karakter, harf, rakam ve alt çizgi",
|
||||
"username_change_warning": "Kullanıcı adını değiştirmek adres defterini ve grup atamalarını da günceller ve kullanıcıyı her yerden çıkış yaptırır.",
|
||||
"password": "Şifre",
|
||||
"password_placeholder": "Şifreyi girin",
|
||||
"password_hint": "Karışık harf, sayı ve simgelerden oluşan minimum 8 karakter",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Ім'я користувача",
|
||||
"username_placeholder": "Введіть ім'я користувача",
|
||||
"username_hint": "3-32 символи, лише літери, цифри та підкреслення",
|
||||
"username_change_warning": "Зміна імені користувача також оновлює адресну книгу й призначення груп та виконує вихід з усіх пристроїв.",
|
||||
"password": "Пароль",
|
||||
"password_placeholder": "Введіть пароль",
|
||||
"password_hint": "Мінімум 8 символів зі змішаним регістром, цифрами та символами",
|
||||
|
||||
@@ -1218,6 +1218,7 @@
|
||||
"username": "Tên người dùng",
|
||||
"username_placeholder": "Nhập tên người dùng",
|
||||
"username_hint": "Chỉ 3-32 ký tự, chữ cái, số và dấu gạch dưới",
|
||||
"username_change_warning": "Thay đổi tên người dùng cũng cập nhật sổ địa chỉ và phân công nhóm, đồng thời đăng xuất người dùng ở mọi nơi.",
|
||||
"password": "Mật khẩu",
|
||||
"password_placeholder": "Nhập mật khẩu",
|
||||
"password_hint": "Tối thiểu 8 ký tự bao gồm cả chữ, số và ký hiệu",
|
||||
|
||||
@@ -1229,6 +1229,7 @@
|
||||
"username": "用戶名",
|
||||
"username_placeholder": "請輸入用戶名",
|
||||
"username_hint": "3-32 個字符,僅限字母、數字和下劃線",
|
||||
"username_change_warning": "變更使用者名稱也會更新通訊錄與群組指派,並在所有裝置上登出。",
|
||||
"password": "密碼",
|
||||
"password_placeholder": "請輸入密碼",
|
||||
"password_hint": "至少 8 個字符,包含大小寫字母、數字和符號",
|
||||
|
||||
@@ -1212,6 +1212,7 @@
|
||||
"username": "用户名",
|
||||
"username_placeholder": "请输入用户名",
|
||||
"username_hint": "3-32 个字符,仅限字母、数字和下划线",
|
||||
"username_change_warning": "更改用户名还会更新通讯录和分组分配,并在所有设备上退出登录。",
|
||||
"password": "密码",
|
||||
"password_placeholder": "请输入密码",
|
||||
"password_hint": "至少 8 个字符,包含大小写字母、数字和符号",
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Username rename cascade (issue #498, 2026-11-13).
|
||||
*
|
||||
* `username` is not just a label: it is the primary key of `address_books`
|
||||
* (`username, ab_type`) and the lookup key in `org_users` and
|
||||
* `strategy_assignments.target_key`. Renaming only the `users` row would orphan
|
||||
* the address book, detach organisation membership and silently drop strategy
|
||||
* assignments — a data-loss bug, not just a cosmetic one.
|
||||
*
|
||||
* This helper performs the dependent updates for a caller that already holds a
|
||||
* transaction. Statements run in a fixed order and tolerate missing tables so
|
||||
* older databases keep working.
|
||||
*
|
||||
* @param {{ run: (sql: string, params?: any[]) => any, dialect: 'sqlite'|'postgres' }} tx
|
||||
* @param {string} oldUsername
|
||||
* @param {string} newUsername
|
||||
*/
|
||||
function renameUserCascade(tx, oldUsername, newUsername) {
|
||||
const oldName = String(oldUsername || '').trim();
|
||||
const newName = String(newUsername || '').trim();
|
||||
if (!oldName || !newName || oldName === newName) return;
|
||||
|
||||
const run = (sql, params) => {
|
||||
try {
|
||||
tx.run(sql, params);
|
||||
} catch (err) {
|
||||
// Optional tables (older installs) must not abort the rename.
|
||||
if (/no such table|does not exist/i.test(String(err.message || ''))) return;
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
// Address books are keyed by (username, ab_type); clear the target first so a
|
||||
// stale book under the new name cannot collide with the rename.
|
||||
run('DELETE FROM address_books WHERE username = ?', [newName]);
|
||||
run('UPDATE address_books SET username = ? WHERE username = ?', [newName, oldName]);
|
||||
|
||||
// Organisation membership and strategy assignments reference the name.
|
||||
run('UPDATE org_users SET username = ? WHERE username = ?', [newName, oldName]);
|
||||
run(
|
||||
"UPDATE strategy_assignments SET target_key = ? WHERE target_key = ? AND target_type = 'user'",
|
||||
[newName, oldName]
|
||||
);
|
||||
|
||||
// Lockout history must not lock the fresh name; attempts are historical rows
|
||||
// that should follow the account.
|
||||
run('DELETE FROM account_lockouts WHERE username = ?', [newName]);
|
||||
run('UPDATE login_attempts SET username = ? WHERE username = ?', [newName, oldName]);
|
||||
}
|
||||
|
||||
module.exports = { renameUserCascade };
|
||||
@@ -832,8 +832,25 @@
|
||||
|
||||
if (usernameInput) {
|
||||
usernameInput.value = user.username;
|
||||
usernameInput.readOnly = true;
|
||||
usernameInput.classList.add('readonly');
|
||||
// Issue #498 (2026-11-13): local accounts may be renamed. The
|
||||
// provider owns the name for LDAP/OIDC, so the field stays
|
||||
// locked there to avoid the next login recreating the old id.
|
||||
const providerForName = (user.auth_provider || 'local').toLowerCase();
|
||||
const canRename = providerForName !== 'ldap' && providerForName !== 'oidc';
|
||||
usernameInput.readOnly = !canRename;
|
||||
if (canRename) {
|
||||
usernameInput.classList.remove('readonly');
|
||||
const nameGroup = usernameInput.closest('.form-group');
|
||||
if (nameGroup && !nameGroup.querySelector('.username-change-warning')) {
|
||||
const warn = document.createElement('span');
|
||||
warn.className = 'form-hint username-change-warning';
|
||||
warn.textContent = _('users.username_change_warning')
|
||||
|| 'Changing the username updates address books, group assignments and signs the user out everywhere.';
|
||||
nameGroup.appendChild(warn);
|
||||
}
|
||||
} else {
|
||||
usernameInput.classList.add('readonly');
|
||||
}
|
||||
}
|
||||
if (roleSelect) roleSelect.value = user.role;
|
||||
const emailInput = document.getElementById('user-email');
|
||||
@@ -971,7 +988,7 @@
|
||||
return;
|
||||
}
|
||||
|
||||
if (!/^[a-zA-Z0-9_]{3,32}$/.test(username)) {
|
||||
if (!/^[A-Za-z0-9_.@-]{3,64}$/.test(username)) {
|
||||
Notifications.error(_('users.invalid_username'));
|
||||
return;
|
||||
}
|
||||
@@ -994,6 +1011,11 @@
|
||||
if (provider === 'local' && password) {
|
||||
if (password) data.password = password;
|
||||
}
|
||||
// Issue #498: send the name only when the operator actually changed
|
||||
// it, so an unmodified form cannot accidentally trigger a rename.
|
||||
if (provider === 'local' && username && username !== user?.username) {
|
||||
data.username = username;
|
||||
}
|
||||
|
||||
await Utils.api(`/api/users/${editingUserId}`, {
|
||||
method: 'PATCH',
|
||||
|
||||
@@ -260,8 +260,16 @@ function normalizeUserEmail(value) {
|
||||
return trimmed;
|
||||
}
|
||||
|
||||
const VALID_USER_ROLES = new Set([
|
||||
'super_admin',
|
||||
/**
|
||||
* Account-name format for the panel (issue #498, 2026-11-13).
|
||||
*
|
||||
* Matches the Go server's `db.ValidUsername`. A username ends up in filesystem
|
||||
* paths, audit lines and address-book keys, so no whitespace, path separators or
|
||||
* control characters are allowed.
|
||||
*/
|
||||
const USERS_USERNAME_RE = /^[A-Za-z0-9_.@-]{3,64}$/;
|
||||
|
||||
const VALID_USER_ROLES = new Set([ 'super_admin',
|
||||
'admin',
|
||||
'server_admin',
|
||||
'global_admin',
|
||||
@@ -449,7 +457,7 @@ router.post('/api/users', requireAuth, requirePermission('user.create'), passwor
|
||||
}
|
||||
|
||||
// Validate username format
|
||||
if (!/^[a-zA-Z0-9_]{3,32}$/.test(username)) {
|
||||
if (!USERS_USERNAME_RE.test(username)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: req.t('users.invalid_username')
|
||||
@@ -577,6 +585,58 @@ router.patch('/api/users/:id', requireAuth, requirePermission('user.edit'), asyn
|
||||
error: req.t('users.provider_managed_hint')
|
||||
});
|
||||
}
|
||||
|
||||
// Username change (issue #498, 2026-11-13). LDAP/OIDC accounts keep the
|
||||
// name their provider issues; renaming them would make the next login
|
||||
// recreate the old identity. The cascade (address book, org membership,
|
||||
// strategy assignment, lockouts) runs in one transaction.
|
||||
const nextUsername = typeof req.body?.username === 'string' ? req.body.username.trim() : '';
|
||||
if (nextUsername && nextUsername !== user.username) {
|
||||
if (isExternalAccount) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: req.t('users.provider_managed_hint')
|
||||
});
|
||||
}
|
||||
if (!USERS_USERNAME_RE.test(nextUsername)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: req.t('users.invalid_username')
|
||||
});
|
||||
}
|
||||
const rename = await db.renameUser(userId, nextUsername);
|
||||
if (!rename || rename.ok !== true) {
|
||||
if (rename && rename.code === 'taken') {
|
||||
return res.status(409).json({
|
||||
success: false,
|
||||
error: req.t('users.username_exists')
|
||||
});
|
||||
}
|
||||
if (rename && rename.code === 'invalid') {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: req.t('users.invalid_username')
|
||||
});
|
||||
}
|
||||
return res.status(404).json({
|
||||
success: false,
|
||||
error: req.t('users.not_found')
|
||||
});
|
||||
}
|
||||
|
||||
await db.logAction(
|
||||
req.session.userId,
|
||||
'user_renamed',
|
||||
`Renamed user ${user.username} -> ${nextUsername}`,
|
||||
req.ip
|
||||
);
|
||||
// Every credential minted under the old name must stop working.
|
||||
try {
|
||||
await authService.revokeUserSessionsAndTokens?.(userId);
|
||||
} catch (_) { /* best effort; the Go side is authoritative */ }
|
||||
runBestEffortUserSync(() => userSync.mirrorUpdate(nextUsername, {}));
|
||||
user.username = nextUsername;
|
||||
}
|
||||
|
||||
// Prevent self-demotion from admin-level role
|
||||
if (userId === req.session.userId && role && isSuperAdminRole(req.session.user.role) && !isSuperAdminRole(role)) {
|
||||
|
||||
@@ -95,6 +95,9 @@ const facade = {
|
||||
? adapter.updateUserLanguage(id, lang)
|
||||
: Promise.resolve(),
|
||||
deleteUser: (id) => adapter.deleteUser(id),
|
||||
renameUser: (id, newUsername) => (adapter.renameUser
|
||||
? adapter.renameUser(id, newUsername)
|
||||
: Promise.resolve({ ok: false, code: 'invalid' })),
|
||||
updateUserProfile: (id, fields) => adapter.updateUserProfile(id, fields),
|
||||
getUsersEmailsByUsernames: (usernames) => adapter.getUsersEmailsByUsernames(usernames),
|
||||
getUsernamesByUserGroupGuid: (guid) => adapter.getUsernamesByUserGroupGuid(guid),
|
||||
|
||||
@@ -1688,6 +1688,44 @@ function createSqliteAdapter(config) {
|
||||
async updateUserLanguage(id, lang) {
|
||||
openAuth().prepare('UPDATE users SET preferred_language = ? WHERE id = ?').run(lang, id);
|
||||
},
|
||||
/**
|
||||
* Rename a user and cascade to the tables keyed by username.
|
||||
*
|
||||
* Issue #498 (2026-11-13): `username` is the PK of `address_books` and a
|
||||
* lookup key in `org_users` / `strategy_assignments`, so a partial rename
|
||||
* would orphan data. One transaction, `ErrUsernameTaken`-style error on
|
||||
* collision.
|
||||
*
|
||||
* @returns {Promise<{ ok: true } | { ok: false, code: 'taken'|'invalid'|'missing' }>}
|
||||
*/
|
||||
async renameUser(id, newUsername) {
|
||||
const { renameUserCascade } = require('../lib/renameUserCascade');
|
||||
const db = openAuth();
|
||||
const tx = db.transaction(() => {
|
||||
const row = db.prepare('SELECT username FROM users WHERE id = ?').get(id);
|
||||
if (!row) return { ok: false, code: 'missing' };
|
||||
if (row.username === newUsername) return { ok: true };
|
||||
const taken = db.prepare('SELECT COUNT(*) AS c FROM users WHERE username = ? AND id <> ?')
|
||||
.get(newUsername, id);
|
||||
if (taken && taken.c > 0) return { ok: false, code: 'taken' };
|
||||
|
||||
db.prepare('UPDATE users SET username = ? WHERE id = ?').run(newUsername, id);
|
||||
renameUserCascade({
|
||||
exec: (sql, params) => db.prepare(sql).run(...(params || [])),
|
||||
run: (sql, params) => db.prepare(sql).run(...(params || [])),
|
||||
dialect: 'sqlite',
|
||||
}, row.username, newUsername);
|
||||
return { ok: true };
|
||||
});
|
||||
try {
|
||||
return tx();
|
||||
} catch (err) {
|
||||
if (/unique|constraint/i.test(String(err.message || ''))) {
|
||||
return { ok: false, code: 'taken' };
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
// Phase 4: update operator identity profile (first_name, last_name, email, phone, role_display, avatar_url)
|
||||
async updateUserProfile(id, fields) {
|
||||
const allowed = ['first_name', 'last_name', 'email', 'phone', 'role_display', 'avatar_url'];
|
||||
@@ -5295,6 +5333,56 @@ function createPostgresAdapter() {
|
||||
|
||||
async getUserByUsername(username) { return one('SELECT * FROM users WHERE username = $1', [username]); },
|
||||
async getUserById(id) { return one('SELECT * FROM users WHERE id = $1', [id]); },
|
||||
/**
|
||||
* Rename a user with the dependent-table cascade (issue #498).
|
||||
* See the SQLite adapter for the rationale.
|
||||
*
|
||||
* @returns {Promise<{ ok: true } | { ok: false, code: 'taken'|'invalid'|'missing' }>}
|
||||
*/
|
||||
async renameUser(id, newUsername) {
|
||||
const { renameUserCascade } = require('../lib/renameUserCascade');
|
||||
const client = await getPool().connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
const existing = await client.query('SELECT username FROM users WHERE id = $1', [id]);
|
||||
if (existing.rowCount === 0) {
|
||||
await client.query('ROLLBACK');
|
||||
return { ok: false, code: 'missing' };
|
||||
}
|
||||
const oldUsername = existing.rows[0].username;
|
||||
if (oldUsername === newUsername) {
|
||||
await client.query('COMMIT');
|
||||
return { ok: true };
|
||||
}
|
||||
const taken = await client.query(
|
||||
'SELECT COUNT(*)::INTEGER AS c FROM users WHERE username = $1 AND id <> $2',
|
||||
[newUsername, id]
|
||||
);
|
||||
if (taken.rows[0].c > 0) {
|
||||
await client.query('ROLLBACK');
|
||||
return { ok: false, code: 'taken' };
|
||||
}
|
||||
await client.query('UPDATE users SET username = $1 WHERE id = $2', [newUsername, id]);
|
||||
// The cascade helper emits `?` placeholders; rewrite them for pg.
|
||||
let paramIndex = 0;
|
||||
const runPg = (sql, params) => client.query(
|
||||
String(sql).replace(/\?/g, () => `$${++paramIndex}`),
|
||||
params || []
|
||||
);
|
||||
paramIndex = 0;
|
||||
await renameUserCascade({ run: runPg, dialect: 'postgres' }, oldUsername, newUsername);
|
||||
await client.query('COMMIT');
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
try { await client.query('ROLLBACK'); } catch (_) { /* already rolled back */ }
|
||||
if (/unique|duplicate key/i.test(String(err.message || ''))) {
|
||||
return { ok: false, code: 'taken' };
|
||||
}
|
||||
throw err;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
},
|
||||
async createUser(username, passwordHash, role = 'admin', authProvider = 'local') {
|
||||
const provider = authProvider || 'local';
|
||||
const r = await one(
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* Administrator username change (issue #498, 2026-11-13).
|
||||
*
|
||||
* `username` is the primary key of `address_books` and the lookup key in
|
||||
* `org_users` and `strategy_assignments.target_key`. Renaming only the `users`
|
||||
* row would orphan the address book and detach org/strategy assignments, so the
|
||||
* cascade is part of the contract.
|
||||
*/
|
||||
|
||||
const { renameUserCascade } = require('../lib/renameUserCascade');
|
||||
|
||||
function makeTx({ failOn } = {}) {
|
||||
const statements = [];
|
||||
return {
|
||||
statements,
|
||||
run(sql, params) {
|
||||
if (failOn && failOn.test(sql)) {
|
||||
const err = new Error('no such table: address_books');
|
||||
throw err;
|
||||
}
|
||||
statements.push({ sql, params: params || [] });
|
||||
return { changes: 1 };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('renameUserCascade', () => {
|
||||
it('moves the address book, org membership and strategy assignment', () => {
|
||||
const tx = makeTx();
|
||||
renameUserCascade(tx, 'oldadmin', 'newadmin');
|
||||
|
||||
const sql = tx.statements.map((s) => s.sql);
|
||||
expect(sql).toEqual(expect.arrayContaining([
|
||||
'DELETE FROM address_books WHERE username = ?',
|
||||
'UPDATE address_books SET username = ? WHERE username = ?',
|
||||
'UPDATE org_users SET username = ? WHERE username = ?',
|
||||
]));
|
||||
expect(sql.some((s) => s.includes('strategy_assignments'))).toBe(true);
|
||||
expect(sql.some((s) => s.includes('login_attempts'))).toBe(true);
|
||||
});
|
||||
|
||||
it('clears a lockout on the target name and follows attempts to the new name', () => {
|
||||
const tx = makeTx();
|
||||
renameUserCascade(tx, 'oldadmin', 'newadmin');
|
||||
|
||||
const lockoutDelete = tx.statements.find((s) => s.sql.includes('DELETE FROM account_lockouts'));
|
||||
expect(lockoutDelete.params).toEqual(['newadmin']);
|
||||
|
||||
const attempts = tx.statements.find((s) => s.sql.includes('login_attempts'));
|
||||
expect(attempts.params).toEqual(['newadmin', 'oldadmin']);
|
||||
});
|
||||
|
||||
it('clears a stale address book under the target name first', () => {
|
||||
const tx = makeTx();
|
||||
renameUserCascade(tx, 'oldadmin', 'newadmin');
|
||||
|
||||
const deleteIndex = tx.statements.findIndex((s) => s.sql === 'DELETE FROM address_books WHERE username = ?');
|
||||
const updateIndex = tx.statements.findIndex((s) => s.sql === 'UPDATE address_books SET username = ? WHERE username = ?');
|
||||
expect(deleteIndex).toBeGreaterThanOrEqual(0);
|
||||
expect(deleteIndex).toBeLessThan(updateIndex);
|
||||
});
|
||||
|
||||
it('tolerates a missing optional table on an older database', () => {
|
||||
const tx = makeTx({ failOn: /address_books/ });
|
||||
expect(() => renameUserCascade(tx, 'oldadmin', 'newadmin')).not.toThrow();
|
||||
// The remaining statements still run.
|
||||
expect(tx.statements.some((s) => s.sql.includes('org_users'))).toBe(true);
|
||||
});
|
||||
|
||||
it('is a no-op for an empty or unchanged name', () => {
|
||||
const tx = makeTx();
|
||||
renameUserCascade(tx, 'same', 'same');
|
||||
renameUserCascade(tx, '', 'newadmin');
|
||||
renameUserCascade(tx, 'old', '');
|
||||
expect(tx.statements).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('username format', () => {
|
||||
// Mirrors db.ValidUsername in the Go server and USERS_USERNAME_RE in the panel.
|
||||
const re = /^[A-Za-z0-9_.@-]{3,64}$/;
|
||||
|
||||
it('accepts the documented character set', () => {
|
||||
expect(re.test('admin')).toBe(true);
|
||||
expect(re.test('ops.admin')).toBe(true);
|
||||
expect(re.test('ops_admin')).toBe(true);
|
||||
expect(re.test('ops-admin')).toBe(true);
|
||||
expect(re.test('ops@example')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects whitespace, path separators and short names', () => {
|
||||
expect(re.test('ops admin')).toBe(false);
|
||||
expect(re.test('../etc/passwd')).toBe(false);
|
||||
expect(re.test('ops/admin')).toBe(false);
|
||||
expect(re.test('ab')).toBe(false);
|
||||
expect(re.test('a'.repeat(65))).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user