feat(system): add platform user management and streamline settings (#4153)

* feat(system): platform user management — list, enable/disable, reset password, role toggle

Adds a SystemAdmin-only user management panel under platform settings
(System global -> Access). The backend already had repository primitives
and promote/revoke endpoints; this wires the missing service/handler/route
for listing and account-status changes and adds the UI.

Backend
- New GET /system/admin/users: paginated, cross-tenant user list
  (offset/limit, limit capped at 200), serialised via ToUserInfo so password
  hashes are never exposed; has_more derived with a limit+1 fetch (no COUNT).
- New POST /system/admin/users/status: enable/disable an account.
  Disabling revokes all of the user's tokens immediately. Service guards
  reject self-disable and disabling the last active system administrator.
- ValidateToken now re-checks is_active on every request, so a disabled
  account cannot keep using a previously issued access token.

Frontend
- UserListDialog: table with status/role tags, pagination, in-page
  username/email filter, enable/disable and reset-password actions, and
  one-click system-admin promote/revoke (reuses existing endpoints) with
  confirmation prompts. Reset-password dialog is a sibling (not nested)
  dialog so close/cancel/overlay all work.
- All new strings are i18n keys under system.globalSettings.userList in
  all six locales (en-US, zh-CN, zh-TW, ja-JP, ko-KR, ru-RU).

Tests: handler unit tests for list pagination/redaction/limit-cap and for
status-change success/guard/404 paths; existing handler/service/router
suites pass.

Co-authored-by: MOSS Agent <noreply@example.com>

* fix(system): make account status changes atomic and validate requests

* refactor(system): streamline settings and add dedicated user management tab

* fix(system): resolve user management CI lint findings

* fix(system): preserve account status during ordinary user updates

---------

Co-authored-by: desksk <26273255+desksk@users.noreply.github.com>
Co-authored-by: MOSS Agent <noreply@example.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
main
JLi 2026-10-11 17:07:00 +08:00 committed by GitHub
parent 17dc7da514
commit 643f64180e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
29 changed files with 1523 additions and 756 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

View File

@ -292,24 +292,11 @@ export interface SystemAdminUser {
updated_at: string
}
export interface PromoteUserRequest {
user_id: string
}
export interface RevokeSystemAdminRequest {
user_id: string
}
export interface ListSystemAdminsResponse {
total: number
admins: SystemAdminUser[]
}
/**
* Promote a user to system administrator.
*
* Identify the target either by user_id (UUID, for API clients) or
* email (the human-friendly path used by the SystemAdmin UI). Backend
* email (supported by the backend for API clients). Backend
* accepts whichever is provided; user_id wins when both are set.
*
* Backend handler (system.go) returns the updated UserInfo directly as
@ -346,22 +333,42 @@ export async function revokeSystemAdmin(userId: string): Promise<SystemAdminUser
return response as unknown as SystemAdminUser
}
export interface SetUserStatusRequest {
user_id: string
is_active: boolean
}
/**
* List all system administrators (paginated).
* Returns {total, admins[]} directly — no {data: ...} wrapping.
* Enable/disable a platform user account (SystemAdmin only).
* Disabling immediately revokes the target's active sessions.
*/
export async function listSystemAdmins(
export async function setUserStatus(
req: SetUserStatusRequest,
): Promise<{ message: string; is_active: boolean }> {
const response = await post('/api/v1/system/admin/users/status', req)
return response as unknown as { message: string; is_active: boolean }
}
export interface ListAllUsersResponse {
users: SystemAdminUser[]
offset: number
limit: number
has_more: boolean
}
/**
* List every platform user across tenants (SystemAdmin only, paginated).
* Returns {users, offset, limit, has_more} directly (no data wrapping).
*/
export async function listAllUsers(
params?: { offset?: number; limit?: number },
): Promise<ListSystemAdminsResponse> {
// The shared `get` helper doesn't accept a config object, so we
// assemble the query string manually. Both params are optional;
// the server applies sane defaults (offset=0, limit=50, max=200).
): Promise<ListAllUsersResponse> {
const qs = new URLSearchParams()
if (params?.offset != null) qs.set('offset', String(params.offset))
if (params?.limit != null) qs.set('limit', String(params.limit))
const suffix = qs.toString() ? `?${qs.toString()}` : ''
const response = await get(`/api/v1/system/admin/list${suffix}`)
return response as unknown as ListSystemAdminsResponse
const response = await get(`/api/v1/system/admin/users${suffix}`)
return response as unknown as ListAllUsersResponse
}
export interface ResetUserPasswordRequest {

View File

@ -0,0 +1,18 @@
// Shared table frame for settings pages. Import as a reference in scoped styles.
.settings-data-table() {
overflow-x: auto;
border-radius: var(--app-radius-lg);
border: 1px solid var(--td-component-stroke);
background-color: var(--td-bg-color-container);
&:deep(thead th) {
font-weight: 600;
font-size: var(--app-text-md);
}
&:deep(.t-table td),
&:deep(.t-table th) {
padding-top: 12px;
padding-bottom: 12px;
}
}

View File

@ -69,7 +69,6 @@ const TM_KEY_PATTERNS = [
const EXTRA_PREFIXES = [
'system.globalSettings.listConfirm.',
'system.globalSettings.admins.confirm.',
'system.globalSettings.keyLabels.',
'system.globalSettings.keyDescriptions.',
'system.globalSettings.enumLabels.',

View File

@ -4403,36 +4403,27 @@ export default {
},
sections: {
access: {
tab: 'Accounts & access {count}',
title: 'Accounts & access',
description: 'Manage system administrators, public registration, and workspace-creation rules.'
title: 'Registration & access',
description: 'Manage registration, password requirements, and workspace-creation rules.'
},
tenant: {
tab: 'Workspace defaults {count}',
title: 'Workspace defaults',
description: 'Set initial quotas and compatibility behavior for new workspaces without rewriting existing workspaces.'
},
runtime: {
tab: 'Runtime & concurrency {count}',
title: 'Runtime & concurrency',
description: 'Configure concurrency capacity for background worker pools and model services.',
restartHint: 'Worker settings require restart'
},
security: {
tab: 'Network security {count}',
title: 'Network security',
description: 'Manage the SSRF allowlist and whether the Docker sandbox is allowed (a local docker.sock is equivalent to root on the host).'
},
other: {
tab: 'Other {count}',
title: 'Other settings',
description: 'Settings in this deployment that are not part of a standard product group.'
}
},
runtimeTable: {
setting: 'Setting and purpose',
value: 'Current value'
},
runtime: {
title: 'Task Queue Runtime',
description: 'Live background-queue load and per-process capacity for each isolated worker pool. Includes task details and safe controls; auto-refreshes every 5s.',
@ -4751,34 +4742,45 @@ export default {
success: 'Reset to default',
failed: 'Reset failed'
},
admins: {
label: 'System administrators',
description: 'Users with platform-level privileges. Type an email and press Enter to promote a user; click × on a tag to revoke. You (yourself) are an administrator and are not shown in the list — you cannot revoke your own access.',
placeholder: 'Type a user email and press Enter',
loadFailed: 'Failed to load system administrators',
saveSuccess: 'System administrators updated',
saveFailed: 'Failed to update system administrators',
confirm: {
promote: {
header: 'Promote to system administrator',
body: 'Promote {email} to system administrator? This user will gain platform-level privileges: access to every workspace, system settings, and the admin roster itself.',
confirmBtn: 'Promote'
},
revoke: {
header: 'Revoke system administrator',
body: 'Revoke system-administrator privileges from {email}? They will lose access to all system-level features.',
confirmBtn: 'Revoke'
}
}
userList: {
title: 'Platform users',
rowLabel: 'User management',
rowDesc: 'View every registered user across workspaces, with pagination and username/email filtering.',
searchPlaceholder: 'Filter by username or email (current page)',
refresh: 'Refresh',
active: 'Active',
inactive: 'Disabled',
colUsername: 'Username',
colStatus: 'Status',
colRole: 'Role',
colCreated: 'Created',
colAction: 'Actions',
prev: 'Previous',
next: 'Next',
pageCount: '{shown} shown / {total} on page',
enable: 'Enable',
disable: 'Disable',
resetPassword: 'Reset password',
confirmDisable: 'Disable account {name}? Their active sessions will be revoked immediately.',
confirmEnable: 'Enable account {name}?',
enabledMsg: 'Enabled {name}',
disabledMsg: 'Disabled {name}',
actionFailed: 'Action failed',
loadFailed: 'Failed to load users',
roleAdmin: 'System admin',
roleUser: 'Regular user',
confirmRevoke: 'Revoke system-admin privileges from {name}?',
confirmPromote: 'Promote {name} to system administrator?',
revokeBtn: 'Revoke',
promoteBtn: 'Promote',
revokedMsg: 'Revoked admin privileges from {name}',
promotedMsg: 'Promoted {name} to system administrator',
roleFailed: 'Failed to change role',
},
passwordReset: {
label: 'Reset user password',
description: 'Set a new password for another user who cannot sign in. A successful reset invalidates all of that user\'s current sessions, so they must sign in again with the new password.',
action: 'Reset password',
dialogTitle: 'Reset another user\'s password',
warning: 'This is a high-risk action. Verify the user email carefully. You cannot reset your own password here.',
emailLabel: 'User email',
emailPlaceholder: 'Enter the email of the user to reset',
newPasswordLabel: 'New password',
newPasswordPlaceholder: 'Enter new password',
confirmPasswordLabel: 'Confirm new password',
@ -4788,8 +4790,6 @@ export default {
failed: 'Failed to reset password',
},
createUser: {
label: 'Create user',
description: 'Provision a new local user account. If the platform\'s default workspace mode is set to "create personal", the user gets a personal workspace just like a self-registered user would.',
action: 'Create user',
dialogTitle: 'Create a new user',
warning: 'This is a high-risk action. Verify the username and email carefully — they are how the new user will sign in.',
@ -4812,10 +4812,6 @@ export default {
usernameLength: 'Username must be 2-50 characters',
emailRequired: 'Enter an email address',
emailInvalid: 'Enter a valid email address',
passwordRequired: 'Enter a new password',
passwordLength: 'Password must be 8-32 characters',
passwordLetter: 'Password must contain a letter',
passwordNumber: 'Password must contain a number',
confirmRequired: 'Enter the new password again',
passwordMismatch: 'The passwords do not match'
},

View File

@ -4403,36 +4403,27 @@ export default {
},
sections: {
access: {
tab: 'アカウントとアクセス{count}',
title: 'アカウントとアクセス',
description: 'システム管理者、公開登録、ワークスペース作成のルールを管理します。'
title: '登録とアクセス',
description: '登録方法、パスワード要件、ワークスペース作成のルールを管理します。'
},
tenant: {
tab: 'ワークスペースのデフォルト値{count}',
title: 'ワークスペースのデフォルト値',
description: '既存のワークスペースを変更せずに、新規ワークスペースの初期クォータと互換動作を設定します。'
},
runtime: {
tab: 'ランタイムと並列実行{count}',
title: 'ランタイムと並列実行',
description: 'バックグラウンドのワーカプールとモデルサービスの並列実行数を設定します。',
restartHint: 'ワーカ設定の変更には再起動が必要です'
},
security: {
tab: 'ネットワークセキュリティ{count}',
title: 'ネットワークセキュリティ',
description: 'SSRF許可リストと、Dockerサンドボックスの利用可否を管理します(ローカルのdocker.sockはホストのroot権限に相当します)。'
},
other: {
tab: 'その他{count}',
title: 'その他の設定',
description: 'このデプロイ環境に存在する、標準の製品グループに属さない設定です。'
}
},
runtimeTable: {
setting: '設定と用途',
value: '現在の値'
},
runtime: {
title: 'タスクキューのランタイム',
description: '各ワーカプールのバックグラウンドキューの負荷とプロセスごとの容量をリアルタイムに表示します。タスクの詳細と安全な操作が可能で、5秒ごとに自動更新されます。',
@ -4751,34 +4742,45 @@ export default {
success: 'デフォルト値にリセットしました',
failed: 'リセットに失敗しました'
},
admins: {
label: 'システム管理者',
description: 'プラットフォームレベルの権限を持つユーザです。メールアドレスを入力してEnterキーを押すと権限を付与でき、タグの×をクリックすると取り消せます。あなた自身も管理者ですが一覧には表示されず、自分の権限を取り消すことはできません。',
placeholder: 'ユーザのメールアドレスを入力してEnterキーを押してください',
loadFailed: 'システム管理者の読み込みに失敗しました',
saveSuccess: 'システム管理者を更新しました',
saveFailed: 'システム管理者の更新に失敗しました',
confirm: {
promote: {
header: 'システム管理者に昇格',
body: '{email}をシステム管理者に昇格しますか?このユーザはプラットフォームレベルの権限(すべてのワークスペース、システム設定、管理者一覧へのアクセス)を得ます。',
confirmBtn: '昇格'
},
revoke: {
header: 'システム管理者権限を解除',
body: '{email}のシステム管理者権限を解除しますか?すべてのシステムレベルの機能にアクセスできなくなります。',
confirmBtn: '解除'
}
}
userList: {
title: 'プラットフォームユーザー一覧',
rowLabel: 'ユーザー管理',
rowDesc: 'ワークスペース横断の登録ユーザーを、ページ送りとユーザー名/メール絞り込み付きで表示します。',
searchPlaceholder: 'ユーザー名またはメールで絞り込み(現在ページ)',
refresh: '更新',
active: '有効',
inactive: '無効',
colUsername: 'ユーザー名',
colStatus: '状態',
colRole: 'ロール',
colCreated: '作成日',
colAction: '操作',
prev: '前へ',
next: '次へ',
pageCount: '{shown} 件表示 / ページ内 {total}',
enable: '有効化',
disable: '無効化',
resetPassword: 'パスワードリセット',
confirmDisable: 'アカウント {name} を無効化しますか?有効なセッションは即時に失効します。',
confirmEnable: 'アカウント {name} を有効化しますか?',
enabledMsg: '{name} を有効化しました',
disabledMsg: '{name} を無効化しました',
actionFailed: '操作に失敗しました',
loadFailed: 'ユーザー一覧の読み込みに失敗しました',
roleAdmin: 'システム管理者',
roleUser: '一般ユーザー',
confirmRevoke: '{name} のシステム管理者権限を取り消しますか?',
confirmPromote: '{name} をシステム管理者に昇格させますか?',
revokeBtn: '取り消す',
promoteBtn: '昇格',
revokedMsg: '{name} の管理者権限を取り消しました',
promotedMsg: '{name} をシステム管理者に昇格しました',
roleFailed: 'ロールの変更に失敗しました',
},
passwordReset: {
label: 'ユーザのパスワードをリセット',
description: 'ログインできない他のユーザに新しいパスワードを設定します。リセットに成功すると、そのユーザの現在のセッションはすべて無効になり、新しいパスワードで再度ログインする必要があります。',
action: 'パスワードをリセット',
dialogTitle: '他のユーザのパスワードをリセット',
warning: 'これは高リスクの操作です。ユーザのメールアドレスをよく確認してください。ここで自分のパスワードをリセットすることはできません。',
emailLabel: 'ユーザのメールアドレス',
emailPlaceholder: 'リセット対象ユーザのメールアドレスを入力してください',
newPasswordLabel: '新しいパスワード',
newPasswordPlaceholder: '新しいパスワードを入力してください',
confirmPasswordLabel: '新しいパスワード(確認)',
@ -4788,8 +4790,6 @@ export default {
failed: 'パスワードのリセットに失敗しました',
},
createUser: {
label: 'ユーザを作成',
description: 'ローカルユーザアカウントを新規に作成します。プラットフォームのデフォルトのワークスペースモードが「個人ワークスペースを作成」の場合、自分で登録したユーザと同様に個人ワークスペースが作成されます。',
action: 'ユーザを作成',
dialogTitle: '新しいユーザを作成',
warning: 'これは高リスクの操作です。ユーザ名とメールアドレスをよく確認してください。これらは新しいユーザのログインに使用されます。',
@ -4812,10 +4812,6 @@ export default {
usernameLength: 'ユーザ名は2〜50文字で入力してください',
emailRequired: 'メールアドレスを入力してください',
emailInvalid: '有効なメールアドレスを入力してください',
passwordRequired: '新しいパスワードを入力してください',
passwordLength: 'パスワードは8〜32文字で入力してください',
passwordLetter: 'パスワードには英字を含めてください',
passwordNumber: 'パスワードには数字を含めてください',
confirmRequired: '新しいパスワードをもう一度入力してください',
passwordMismatch: 'パスワードが一致しません'
},

View File

@ -3321,14 +3321,45 @@ export default {
success: '{count}개 워크스페이스의 저장 용량을 {gb} GB로 갱신했습니다',
failed: '모든 워크스페이스에 적용 실패'
},
userList: {
title: '플랫폼 사용자 목록',
rowLabel: '사용자 관리',
rowDesc: '워크스페이스 전체의 등록 사용자를 페이지네이션 및 사용자 이름/이메일 필터와 함께 표시합니다.',
searchPlaceholder: '사용자 이름 또는 이메일로 필터링(현재 페이지)',
refresh: '새로고침',
active: '활성',
inactive: '비활성',
colUsername: '사용자 이름',
colStatus: '상태',
colRole: '역할',
colCreated: '생성일',
colAction: '작업',
prev: '이전',
next: '다음',
pageCount: '{shown}개 표시 / 페이지 내 {total}',
enable: '활성화',
disable: '비활성화',
resetPassword: '비밀번호 재설정',
confirmDisable: '{name} 계정을 비활성화할까요? 활성 세션이 즉시 취소됩니다.',
confirmEnable: '{name} 계정을 활성화할까요?',
enabledMsg: '{name} 활성화됨',
disabledMsg: '{name} 비활성화됨',
actionFailed: '작업 실패',
loadFailed: '사용자 목록을 불러오지 못했습니다',
roleAdmin: '시스템 관리자',
roleUser: '일반 사용자',
confirmRevoke: '{name}의 시스템 관리자 권한을 취소할까요?',
confirmPromote: '{name}을(를) 시스템 관리자로 승격할까요?',
revokeBtn: '취소',
promoteBtn: '승격',
revokedMsg: '{name}의 관리자 권한을 취소했습니다',
promotedMsg: '{name}을(를) 시스템 관리자로 승격했습니다',
roleFailed: '역할 변경 실패',
},
passwordReset: {
label: '사용자 비밀번호 재설정',
description: '로그인할 수 없는 다른 사용자의 새 비밀번호를 설정합니다. 재설정하면 해당 사용자의 현재 로그인 세션이 모두 만료되며 새 비밀번호로 다시 로그인해야 합니다.',
action: '비밀번호 재설정',
dialogTitle: '다른 사용자의 비밀번호 재설정',
warning: '보안에 민감한 작업입니다. 사용자 이메일을 반드시 확인하세요. 여기서는 자신의 비밀번호를 재설정할 수 없습니다.',
emailLabel: '사용자 이메일',
emailPlaceholder: '비밀번호를 재설정할 사용자의 이메일 입력',
newPasswordLabel: '새 비밀번호',
newPasswordPlaceholder: '새 비밀번호 입력',
confirmPasswordLabel: '새 비밀번호 확인',
@ -3338,8 +3369,6 @@ export default {
failed: '비밀번호 재설정 실패',
},
createUser: {
label: '사용자 생성',
description: '새 로컬 사용자 계정을 개설합니다. 플랫폼의 기본 공간 모드가 "개인 공간 자동 생성"으로 설정된 경우, 스스로 가입한 사용자와 마찬가지로 개인 공간도 함께 만들어집니다.',
action: '사용자 생성',
dialogTitle: '새 사용자 생성',
warning: '보안에 민감한 작업입니다. 새 사용자가 로그인할 때 사용할 사용자 이름과 이메일을 신중히 확인하세요.',
@ -3362,10 +3391,6 @@ export default {
usernameLength: '사용자 이름은 2~50자여야 합니다',
emailRequired: '이메일을 입력하세요',
emailInvalid: '올바른 이메일 주소를 입력하세요',
passwordRequired: '새 비밀번호를 입력하세요',
passwordLength: '비밀번호는 8~32자여야 합니다',
passwordLetter: '비밀번호에 문자가 포함되어야 합니다',
passwordNumber: '비밀번호에 숫자가 포함되어야 합니다',
confirmRequired: '새 비밀번호를 다시 입력하세요',
passwordMismatch: '비밀번호가 일치하지 않습니다'
},
@ -3380,26 +3405,6 @@ export default {
acknowledgeBtn: '비밀번호를 저장했습니다'
}
},
admins: {
label: '시스템 관리자',
description: '플랫폼 수준 권한을 가진 사용자입니다. 오른쪽에 이메일을 입력하고 엔터를 누르면 해당 사용자를 관리자로 승격하고, 태그의 ×를 누르면 권한을 회수합니다. 본인은 관리자이지만 목록에 표시되지 않으며 자신의 권한을 회수할 수 없습니다.',
placeholder: '사용자 이메일을 입력하고 엔터를 누르세요',
loadFailed: '시스템 관리자 정보를 불러오지 못했습니다',
saveSuccess: '시스템 관리자가 업데이트되었습니다',
saveFailed: '시스템 관리자 업데이트 실패',
confirm: {
revoke: {
header: '시스템 관리자 권한 회수',
body: '{email} 사용자의 시스템 관리자 권한을 회수하시겠습니까? 회수 후에는 시스템 수준 기능에 더 이상 접근할 수 없습니다.',
confirmBtn: '회수 확인'
},
promote: {
header: '시스템 관리자로 승격',
body: '{email} 사용자를 시스템 관리자로 승격하시겠습니까? 이 사용자는 모든 워크스페이스 접근, 시스템 설정 변경, 관리자 명단 관리 등 플랫폼 수준의 권한을 갖게 됩니다.',
confirmBtn: '승격 확인'
}
}
},
reset: {
label: '초기화',
tooltip: 'UI 재정의 값을 제거하고 환경 변수 또는 내장 기본값으로 되돌립니다',
@ -3718,36 +3723,27 @@ export default {
generic: '큐 상태를 불러오지 못했습니다'
}
},
runtimeTable: {
setting: '설정 및 용도',
value: '현재 값'
},
sections: {
other: {
tab: '기타 {count}',
title: '기타 설정',
description: '표준 제품 그룹에 포함되지 않은 현재 배포의 설정입니다.'
},
security: {
tab: '네트워크 보안 {count}',
title: '네트워크 보안',
description: 'SSRF 허용 목록과 Docker 샌드박스 허용 여부(로컬 docker.sock은 호스트 root와 같음)를 관리합니다.'
},
runtime: {
tab: '런타임 및 동시성 {count}',
title: '런타임 및 동시성',
description: '백그라운드 워커 풀과 모델 서비스의 동시 처리 용량을 설정합니다.',
restartHint: '워커 설정은 재시작 후 적용'
},
tenant: {
tab: '워크스페이스 기본값 {count}',
title: '워크스페이스 기본값',
description: '기존 워크스페이스를 변경하지 않고 신규 워크스페이스의 초기 할당량과 호환 동작을 설정합니다.'
},
access: {
tab: '계정 및 액세스 {count}',
title: '계정 및 액세스',
description: '시스템 관리자, 공개 가입, 공간 생성 규칙을 관리합니다.'
title: '가입 및 액세스',
description: '가입 방식, 비밀번호 요구 사항, 공간 생성 규칙을 관리합니다.'
}
},
priorityHint: {

View File

@ -3321,14 +3321,45 @@ export default {
success: 'Обновлена квота хранилища у {count} пространств: {gb} ГБ',
failed: 'Ошибка применения ко всем пространствам'
},
userList: {
title: 'Пользователи платформы',
rowLabel: 'Управление пользователями',
rowDesc: 'Все зарегистрированные пользователи во всех пространствах, с постраничным просмотром и фильтром по имени/почте.',
searchPlaceholder: 'Фильтр по имени или почте (на текущей странице)',
refresh: 'Обновить',
active: 'Активен',
inactive: 'Отключён',
colUsername: 'Имя',
colStatus: 'Статус',
colRole: 'Роль',
colCreated: 'Создан',
colAction: 'Действия',
prev: 'Назад',
next: 'Вперёд',
pageCount: 'Показано {shown} / на странице {total}',
enable: 'Включить',
disable: 'Отключить',
resetPassword: 'Сбросить пароль',
confirmDisable: 'Отключить учётную запись {name}? Активные сеансы будут немедленно прекращены.',
confirmEnable: 'Включить учётную запись {name}?',
enabledMsg: '{name} включён',
disabledMsg: '{name} отключён',
actionFailed: 'Не удалось выполнить действие',
loadFailed: 'Не удалось загрузить список пользователей',
roleAdmin: 'Системный администратор',
roleUser: 'Обычный пользователь',
confirmRevoke: 'Отозвать права системного администратора у {name}?',
confirmPromote: 'Назначить {name} системным администратором?',
revokeBtn: 'Отозвать',
promoteBtn: 'Назначить',
revokedMsg: 'Права администратора у {name} отозваны',
promotedMsg: '{name} назначен системным администратором',
roleFailed: 'Не удалось изменить роль',
},
passwordReset: {
label: 'Сброс пароля пользователя',
description: 'Задайте новый пароль другому пользователю, который не может войти. После сброса все его текущие сеансы будут завершены, и потребуется войти с новым паролем.',
action: 'Сбросить пароль',
dialogTitle: 'Сброс пароля другого пользователя',
warning: 'Это операция повышенного риска. Внимательно проверьте email пользователя. Здесь нельзя сбросить собственный пароль.',
emailLabel: 'Email пользователя',
emailPlaceholder: 'Введите email пользователя',
newPasswordLabel: 'Новый пароль',
newPasswordPlaceholder: 'Введите новый пароль',
confirmPasswordLabel: 'Подтвердите новый пароль',
@ -3338,8 +3369,6 @@ export default {
failed: 'Не удалось сбросить пароль',
},
createUser: {
label: 'Создать пользователя',
description: 'Завести новый локальный аккаунт. Если режим пространства по умолчанию — «создавать личное пространство», пользователь получит личное пространство так же, как при самостоятельной регистрации.',
action: 'Создать пользователя',
dialogTitle: 'Создание нового пользователя',
warning: 'Это операция повышенного риска. Внимательно проверьте имя пользователя и email — это его единственные учётные данные для входа.',
@ -3362,10 +3391,6 @@ export default {
usernameLength: 'Имя пользователя должно содержать от 2 до 50 символов',
emailRequired: 'Введите email',
emailInvalid: 'Введите корректный email',
passwordRequired: 'Введите новый пароль',
passwordLength: 'Пароль должен содержать от 8 до 32 символов',
passwordLetter: 'Пароль должен содержать букву',
passwordNumber: 'Пароль должен содержать цифру',
confirmRequired: 'Введите новый пароль ещё раз',
passwordMismatch: 'Пароли не совпадают'
},
@ -3380,26 +3405,6 @@ export default {
acknowledgeBtn: 'Я сохранил пароль'
}
},
admins: {
label: 'Системные администраторы',
description: 'Пользователи с правами уровня платформы. Введите email и нажмите Enter, чтобы повысить пользователя до администратора; нажмите × на теге, чтобы отозвать права. Вы (текущий пользователь) являетесь администратором и не отображаетесь в списке — отозвать собственные права нельзя.',
placeholder: 'Введите email пользователя и нажмите Enter',
loadFailed: 'Не удалось загрузить системных администраторов',
saveSuccess: 'Системные администраторы обновлены',
saveFailed: 'Ошибка обновления системных администраторов',
confirm: {
revoke: {
header: 'Отозвать права администратора',
body: 'Отозвать права системного администратора у {email}? После отзыва пользователь потеряет доступ ко всем системным функциям.',
confirmBtn: 'Отозвать'
},
promote: {
header: 'Повысить до системного администратора',
body: 'Повысить пользователя {email} до системного администратора? Пользователь получит права уровня платформы: доступ ко всем пространствам, изменение системных настроек и управление списком администраторов.',
confirmBtn: 'Повысить'
}
}
},
reset: {
label: 'Сбросить',
tooltip: 'Очистить переопределение из UI и вернуться к переменной окружения или встроенному значению по умолчанию',
@ -3718,36 +3723,27 @@ export default {
generic: 'Не удалось загрузить состояние очередей'
}
},
runtimeTable: {
setting: 'Параметр и назначение',
value: 'Текущее значение'
},
sections: {
other: {
tab: 'Другое {count}',
title: 'Другие настройки',
description: 'Настройки этого развёртывания вне стандартных групп.'
},
security: {
tab: 'Сетевая безопасность {count}',
title: 'Сетевая безопасность',
description: 'Белый список SSRF и разрешение песочницы Docker (локальный docker.sock равносилен root на хосте).'
},
runtime: {
tab: 'Среда и параллелизм {count}',
title: 'Среда и параллелизм',
description: 'Параллелизм фоновых пулов и сервисов моделей.',
restartHint: 'Настройки воркеров требуют перезапуска'
},
tenant: {
tab: 'Значения пространства {count}',
title: 'Значения пространства по умолчанию',
description: 'Начальные квоты и режимы совместимости для новых пространств.'
},
access: {
tab: 'Учётные записи и доступ {count}',
title: 'Учётные записи и доступ',
description: 'Системные администраторы, открытая регистрация и правила создания пространств.'
title: 'Регистрация и доступ',
description: 'Настройка регистрации, требований к паролям и правил создания пространств.'
}
},
priorityHint: {

View File

@ -3323,14 +3323,45 @@ export default {
success: '已将 {count} 个空间的存储配额更新为 {gb} GB',
failed: '应用到所有空间失败'
},
userList: {
title: '平台用户列表',
rowLabel: '用户管理',
rowDesc: '查看平台上的全部注册用户(跨空间),支持分页与按用户名/邮箱筛选。',
searchPlaceholder: '按用户名或邮箱筛选(当前页)',
refresh: '刷新',
active: '正常',
inactive: '已停用',
colUsername: '用户名',
colStatus: '状态',
colRole: '角色',
colCreated: '创建日期',
colAction: '操作',
prev: '上一页',
next: '下一页',
pageCount: '{shown} 条 / 本页 {total}',
enable: '启用',
disable: '停用',
resetPassword: '重置密码',
confirmDisable: '确定停用账号 {name} 吗?将立即吊销其登录状态。',
confirmEnable: '确定启用账号 {name} 吗?',
enabledMsg: '已启用 {name}',
disabledMsg: '已停用 {name}',
actionFailed: '操作失败',
loadFailed: '加载用户列表失败',
roleAdmin: '系统管理员',
roleUser: '普通用户',
confirmRevoke: '确定撤销 {name} 的系统管理员权限吗?',
confirmPromote: '确定将 {name} 提升为系统管理员吗?',
revokeBtn: '撤销',
promoteBtn: '提升',
revokedMsg: '已撤销 {name} 的管理员权限',
promotedMsg: '已将 {name} 提升为系统管理员',
roleFailed: '修改角色失败',
},
passwordReset: {
label: '重置用户密码',
description: '为忘记密码的其他用户设置新密码。重置成功后,该用户当前所有登录会话都会失效,需要使用新密码重新登录。',
action: '重置密码',
dialogTitle: '重置其他用户的密码',
warning: '这是高风险操作。请核对用户邮箱;出于安全考虑,不能在这里重置自己的密码。',
emailLabel: '用户邮箱',
emailPlaceholder: '输入需要重置密码的用户邮箱',
newPasswordLabel: '新密码',
newPasswordPlaceholder: '请输入新密码',
confirmPasswordLabel: '确认新密码',
@ -3340,8 +3371,6 @@ export default {
failed: '重置密码失败',
},
createUser: {
label: '创建用户',
description: '开通一个新的本地用户账号。如果平台的默认空间模式设置为「自动创建个人空间」,该用户会像自助注册的用户一样,同时获得一个个人空间。',
action: '创建用户',
dialogTitle: '创建新用户',
warning: '这是高风险操作。请仔细核对用户名和邮箱——它们将作为该用户登录的唯一凭据。',
@ -3364,10 +3393,6 @@ export default {
usernameLength: '用户名长度必须为 2-50 个字符',
emailRequired: '请输入邮箱',
emailInvalid: '请输入有效的邮箱地址',
passwordRequired: '请输入新密码',
passwordLength: '密码长度必须为 8-32 个字符',
passwordLetter: '密码必须包含字母',
passwordNumber: '密码必须包含数字',
confirmRequired: '请再次输入新密码',
passwordMismatch: '两次输入的密码不一致'
},
@ -3382,26 +3407,6 @@ export default {
acknowledgeBtn: '我已保存密码'
}
},
admins: {
label: '系统管理员',
description: '拥有平台级权限的用户。在右侧输入邮箱并回车即可提升用户为管理员;点击 × 即为撤销其权限。当前你(自己)已是管理员,不在列表中显示,也无法被自己撤销。',
placeholder: '输入用户邮箱并回车',
loadFailed: '加载系统管理员失败',
saveSuccess: '已更新系统管理员',
saveFailed: '更新系统管理员失败',
confirm: {
revoke: {
header: '撤销系统管理员',
body: '确认撤销 {email} 的系统管理员权限?撤销后该用户将无法再访问任何系统级功能。',
confirmBtn: '撤销'
},
promote: {
header: '提升为系统管理员',
body: '确认将 {email} 提升为系统管理员?该用户将获得平台级权限,可访问所有空间、修改系统设置、管理其他管理员。',
confirmBtn: '提升'
}
}
},
reset: {
label: '重置',
tooltip: '清除当前 UI 覆盖,恢复使用环境变量或内置默认值',
@ -3720,36 +3725,27 @@ export default {
generic: '获取队列状态失败'
}
},
runtimeTable: {
setting: '配置项与用途',
value: '当前值'
},
sections: {
other: {
tab: '其他 {count}',
title: '其他配置',
description: '当前部署中未归入标准分组的配置项。'
},
security: {
tab: '网络安全 {count}',
title: '网络安全',
description: '管理 SSRF 白名单,以及是否允许 Docker 沙箱(本机 docker.sock 等同宿主机 root)。'
},
runtime: {
tab: '运行与并发 {count}',
title: '运行与并发',
description: '配置后台任务池与模型服务的并发容量。',
restartHint: 'Worker 配置需重启生效'
},
tenant: {
tab: '空间默认值 {count}',
title: '空间默认值',
description: '设置新空间的初始配额与兼容性行为,不会自动改写已有空间。'
},
access: {
tab: '账户与访问 {count}',
title: '账户与访问',
description: '管理系统管理员、公开注册与用户创建空间的规则。'
title: '注册与访问',
description: '管理注册方式、密码要求和用户创建空间的规则。'
}
},
priorityHint: {

View File

@ -3323,14 +3323,45 @@ export default {
success: '已將 {count} 個空間的存儲配額更新為 {gb} GB',
failed: '應用到所有空間失敗'
},
userList: {
title: '平台使用者列表',
rowLabel: '使用者管理',
rowDesc: '檢視平台上的全部註冊使用者(跨空間),支援分頁與依使用者名稱/郵箱篩選。',
searchPlaceholder: '依使用者名稱或郵箱篩選(目前頁面)',
refresh: '重新整理',
active: '正常',
inactive: '已停用',
colUsername: '使用者名稱',
colStatus: '狀態',
colRole: '角色',
colCreated: '建立日期',
colAction: '操作',
prev: '上一頁',
next: '下一頁',
pageCount: '{shown} 筆 / 本頁 {total}',
enable: '啟用',
disable: '停用',
resetPassword: '重設密碼',
confirmDisable: '確定停用帳號 {name} 嗎?將立即撤銷其登入狀態。',
confirmEnable: '確定啟用帳號 {name} 嗎?',
enabledMsg: '已啟用 {name}',
disabledMsg: '已停用 {name}',
actionFailed: '操作失敗',
loadFailed: '載入使用者列表失敗',
roleAdmin: '系統管理員',
roleUser: '一般使用者',
confirmRevoke: '確定撤銷 {name} 的系統管理員權限嗎?',
confirmPromote: '確定將 {name} 提升為系統管理員嗎?',
revokeBtn: '撤銷',
promoteBtn: '提升',
revokedMsg: '已撤銷 {name} 的管理員權限',
promotedMsg: '已將 {name} 提升為系統管理員',
roleFailed: '修改角色失敗',
},
passwordReset: {
label: '重設使用者密碼',
description: '為忘記密碼的其他使用者設定新密碼。重設成功後,該使用者當前所有登入會話都會失效,需要使用新密碼重新登入。',
action: '重設密碼',
dialogTitle: '重設其他使用者的密碼',
warning: '這是高風險操作。請核對使用者電子信箱;出於安全考慮,不能在這裡重設自己的密碼。',
emailLabel: '使用者電子信箱',
emailPlaceholder: '輸入需要重設密碼的使用者電子信箱',
newPasswordLabel: '新密碼',
newPasswordPlaceholder: '請輸入新密碼',
confirmPasswordLabel: '確認新密碼',
@ -3340,8 +3371,6 @@ export default {
failed: '重設密碼失敗',
},
createUser: {
label: '建立使用者',
description: '開通一個新的本地使用者帳號。如果平台的預設空間模式設定為「自動建立個人空間」,該使用者會像自助註冊的使用者一樣,同時獲得一個個人空間。',
action: '建立使用者',
dialogTitle: '建立新使用者',
warning: '這是高風險操作。請仔細核對使用者名和電子信箱──它們將作為該使用者登入的唯一憑據。',
@ -3364,10 +3393,6 @@ export default {
usernameLength: '使用者名長度必須為 2-50 個字符',
emailRequired: '請輸入電子信箱',
emailInvalid: '請輸入有效的電子信箱地址',
passwordRequired: '請輸入新密碼',
passwordLength: '密碼長度必須為 8-32 個字符',
passwordLetter: '密碼必須包含字母',
passwordNumber: '密碼必須包含數字',
confirmRequired: '請再次輸入新密碼',
passwordMismatch: '兩次輸入的密碼不一致'
},
@ -3382,26 +3407,6 @@ export default {
acknowledgeBtn: '我已儲存密碼'
}
},
admins: {
label: '系統管理員',
description: '擁有平台級權限的使用者。在右側輸入電子信箱並Enter即可提升使用者為管理員;點擊 × 即為撤銷其權限。當前你(自己)已是管理員,不在清單中顯示,也無法被自己撤銷。',
placeholder: '輸入使用者電子信箱並Enter',
loadFailed: '載入系統管理員失敗',
saveSuccess: '已更新系統管理員',
saveFailed: '更新系統管理員失敗',
confirm: {
revoke: {
header: '撤銷系統管理員',
body: '確認撤銷 {email} 的系統管理員權限?撤銷後該使用者將無法再存取任何系統級功能。',
confirmBtn: '撤銷'
},
promote: {
header: '提升為系統管理員',
body: '確認將 {email} 提升為系統管理員?該使用者將獲得平台級權限,可存取所有空間、修改系統設定、管理其他管理員。',
confirmBtn: '提升'
}
}
},
reset: {
label: '重設',
tooltip: '清除當前 UI 覆蓋,復原使用環境變數或內建預設值',
@ -3720,36 +3725,27 @@ export default {
generic: '獲取佇列狀態失敗'
}
},
runtimeTable: {
setting: '設定項與用途',
value: '當前值'
},
sections: {
other: {
tab: '其他 {count}',
title: '其他設定',
description: '當前部署中未歸入標準分組的設定項。'
},
security: {
tab: '網路安全 {count}',
title: '網路安全',
description: '管理 SSRF 白名單,以及是否允許 Docker 沙箱(本機 docker.sock 等同宿主機 root)。'
},
runtime: {
tab: '運行與併發 {count}',
title: '運行與併發',
description: '設定後台任務池與模型服務的併發容量。',
restartHint: 'Worker 設定需重啟生效'
},
tenant: {
tab: '空間預設值 {count}',
title: '空間預設值',
description: '設定新空間的初始配額與相容性行為,不會自動改寫已有空間。'
},
access: {
tab: '帳戶與存取 {count}',
title: '帳戶與存取',
description: '管理系統管理員、公開註冊與使用者建立空間的規則。'
title: '註冊與存取',
description: '管理註冊方式、密碼要求及使用者建立空間的規則。'
}
},
priorityHint: {

View File

@ -1468,6 +1468,7 @@ watch(
<style lang="less" scoped>
@import (reference) '@/components/css/settings-section.less';
@import (reference) '@/components/css/settings-table.less';
.tenant-members {
width: 100%;
@ -1695,21 +1696,7 @@ watch(
}
.data-table-shell {
overflow-x: auto;
border-radius: var(--app-radius-lg);
border: 1px solid var(--td-component-stroke);
background-color: var(--td-bg-color-container);
&:deep(thead th) {
font-weight: 600;
font-size: var(--app-text-md);
}
&:deep(.t-table td),
&:deep(.t-table th) {
padding-top: 12px;
padding-bottom: 12px;
}
.settings-data-table();
/* 角色列:下拉收缩到内容宽度,不再撑满整格。原先 100% 在窄角色
名(如"Owner")下显得空荡且与其他列对不齐。 */

View File

@ -1,7 +1,7 @@
<!--
CreateUserDialog: SystemAdmin "Create user" in-place popup (Access row).
CreateUserDialog: SystemAdmin "Create user" in-place popup.
Anchors to the row action via the default slot, matching TenantMembers
Anchors to the page action via the default slot, matching TenantMembers
invite and UserProfile password popups. Form (username + email +
auto-generate toggle) and, when the server mints a one-time password, a
reveal view that must be acknowledged before the popup can close. Esc is
@ -14,7 +14,7 @@
region can relay it. Shared popup chrome comes from systemAdminDialog.less.
-->
<template>
<t-popup :visible="visible" trigger="click" placement="left-top" :destroy-on-close="!locked"
<t-popup :visible="visible && active" trigger="click" placement="left-top" :destroy-on-close="!locked"
overlay-class-name="wk-popover wk-popover--form system-admin-action-popup-overlay" @visible-change="onVisibleChange">
<span class="system-admin-action-popup-anchor">
<slot />
@ -125,10 +125,11 @@ import {
type CreateUserReveal,
} from './createUserDialogState'
const props = defineProps<{ visible: boolean }>()
const props = defineProps<{ visible: boolean; active: boolean }>()
const emit = defineEmits<{
'update:visible': [boolean]
announced: [string]
created: []
}>()
const { t } = useI18n()
@ -240,6 +241,7 @@ async function submit() {
payload.password = form.newPassword
}
const response = await createSystemUser(payload)
emit('created')
const view = resolveCreateUserView(
response,
{ username: payload.username, email: payload.email },

View File

@ -37,7 +37,7 @@ function compileComponent(source, imports) {
return Object.assign(evaluate(script.content).default, { render: evaluate(template.code).render })
}
function mountResetRow() {
function mountResetRow(email = 'user@example.com') {
const requests = []
const notices = []
const Dialog = compileComponent(read('./ResetPasswordDialog.vue'), {
@ -51,9 +51,9 @@ function mountResetRow() {
})
// Compile the real parent row so reverting its lifetime/visibility binding
// also fails this test, instead of testing a hand-written approximation.
const { descriptor } = parse(read('./SystemSettings.vue'))
const { descriptor } = parse(read('./UserManagement.vue'))
function findRow(node) {
if (node.props?.some((prop) => prop.name === 'class' && prop.value?.content.includes('setting-row--password-reset'))) {
if (node.tag === 'ResetPasswordDialog') {
return node.loc.source
}
return node.children?.map(findRow).find(Boolean)
@ -64,8 +64,15 @@ function mountResetRow() {
<script setup>
import { ref } from 'vue'
import ResetPasswordDialog from './ResetPasswordDialog.vue'
const activeSettingsSection = ref('access')
const passwordResetVisible = ref(false)
const active = ref(true)
const resetVisibleId = ref(null)
const resetBusy = ref(false)
const loading = false
const busyId = null
const createVisible = false
const authStore = { currentUserId: 'self' }
const row = { id: 'target', email: ${JSON.stringify(email)}, is_active: true }
const announce = (message) => { saveAnnouncement.value = message }
const saveAnnouncement = ref('')
const dialogRef = ref()
const t = (key) => key
@ -113,22 +120,22 @@ for (const outcome of ['success', 'failure']) {
test(`pending reset survives tab changes and reports ${outcome}`, async (t) => {
const { app, parent, requests, dialog } = mountResetRow()
t.after(() => app.unmount())
parent.passwordResetVisible = true
parent.resetVisibleId = 'target'
await flush()
const initial = dialog()
Object.assign(initial.form, { email: ' user@example.com ', newPassword: 'FirstSecret1!', confirmPassword: 'FirstSecret1!' })
Object.assign(initial.form, { newPassword: 'FirstSecret1!', confirmPassword: 'FirstSecret1!' })
const pending = initial.submit()
await flush()
assert.equal(requests.length, 1)
assert.equal(requests[0].body.email, 'user@example.com')
initial.onVisibleChange(false)
assert.equal(parent.passwordResetVisible, true)
assert.equal(parent.resetVisibleId, 'target')
parent.activeSettingsSection = 'runtime'
parent.active = false
await flush()
assert.equal(dialog(), initial, 'tab changes must preserve the pending request owner')
assert.equal(parent.dialogRef.$.subTree.component.props.visible, false, 'teleported popup must be hidden')
parent.activeSettingsSection = 'access'
parent.active = true
await flush()
assert.equal(dialog(), initial)
assert.equal(parent.dialogRef.$.subTree.component.props.visible, true)
@ -138,7 +145,7 @@ for (const outcome of ['success', 'failure']) {
await initial.submit()
assert.equal(requests.length, 1, 'returning to the tab must not allow a concurrent reset')
parent.activeSettingsSection = 'runtime'
parent.active = false
await flush()
if (outcome === 'success') requests[0].resolve({})
else requests[0].reject(new Error('Reset failed'))
@ -146,10 +153,34 @@ for (const outcome of ['success', 'failure']) {
await flush()
assert.equal(initial.submitting, false)
assert.equal(parent.saveAnnouncement, outcome === 'success' ? 'system.globalSettings.passwordReset.success' : 'Reset failed')
assert.equal(parent.passwordResetVisible, outcome !== 'success')
parent.activeSettingsSection = 'access'
assert.equal(parent.resetVisibleId, outcome === 'success' ? null : 'target')
parent.active = true
await flush()
assert.equal(parent.dialogRef.$.subTree.component.props.visible, outcome !== 'success')
assert.equal(initial.form.newPassword, outcome === 'success' ? '' : 'FirstSecret1!')
})
}
test('row reset keeps the selected email and reports its pending state', async (t) => {
const { app, parent, requests, dialog } = mountResetRow('bob@example.com')
t.after(() => app.unmount())
parent.resetVisibleId = 'target'
await flush()
const state = dialog()
assert.equal(state.form.email, 'bob@example.com')
Object.assign(state.form, { newPassword: 'FirstSecret1!', confirmPassword: 'FirstSecret1!' })
const pending = state.submit()
await flush()
assert.equal(parent.resetBusy, true)
assert.equal(requests[0].body.email, 'bob@example.com')
requests[0].resolve({})
await pending
await flush()
assert.equal(parent.resetBusy, false)
assert.equal(parent.resetVisibleId, null)
assert.equal(state.form.newPassword, '')
parent.resetVisibleId = 'target'
await flush()
assert.equal(state.form.email, 'bob@example.com')
})

View File

@ -1,6 +1,6 @@
<!--
ResetPasswordDialog: SystemAdmin "reset user password" in-place popup
for the Access row.
for a user row.
The trigger button goes in the default slot. The parent owns visibility
via v-model:visible and relays the `announced` event into its sr-only
@ -22,8 +22,7 @@
</p>
<t-form ref="formRef" :data="form" :rules="rules" label-align="top" class="system-admin-action-popup-form">
<t-form-item :label="t('system.globalSettings.passwordReset.emailLabel')" name="email">
<t-input v-model="form.email" type="text" clearable autocomplete="off" :disabled="submitting"
:placeholder="t('system.globalSettings.passwordReset.emailPlaceholder')" />
<div class="system-admin-action-popup-target">{{ email }}</div>
</t-form-item>
<t-form-item :label="t('system.globalSettings.passwordReset.newPasswordLabel')" name="newPassword">
<t-input v-model="form.newPassword" type="password" autocomplete="new-password" :disabled="submitting"
@ -61,15 +60,17 @@ import { getAuthConfig } from '@/api/auth'
import { newPasswordRules } from '@/utils/passwordPolicy'
// Hide the teleported popup on other tabs without discarding a pending reset.
const props = defineProps<{ visible: boolean; active: boolean }>()
const props = defineProps<{ visible: boolean; active: boolean; email: string }>()
const emit = defineEmits<{
'update:visible': [boolean]
announced: [string]
'busy-change': [boolean]
}>()
const { t } = useI18n()
const submitting = ref(false)
watch(submitting, value => emit('busy-change', value), { flush: 'sync' })
const formRef = ref<FormInstanceFunctions>()
const form = reactive({
email: '',
@ -106,16 +107,14 @@ const rules = computed<Record<string, FormRule[]>>(() => ({
}))
function resetFormFields() {
form.email = ''
form.email = props.email
form.newPassword = ''
form.confirmPassword = ''
formRef.value?.clearValidate?.()
}
// destroy-on-close remounts the form DOM on every open, so the fields
// start empty regardless; the explicit reset + clearValidate here just
// guarantees the reactive state and any stale inline errors are gone too
// (mirrors the pre-refactor behaviour in SystemSettings).
// clear passwords and stale inline errors while preserving the selected user.
watch(() => props.visible, async (visible) => {
if (!visible) {
resetFormFields()

View File

@ -5,11 +5,9 @@
the route also has meta.requiresSystemAdmin so non-admins never
reach this component (see frontend/src/router/index.ts).
Visual contract: matches the canonical Settings-modal pane skeleton
(`.section-header` + `.settings-group` + `.setting-row` /
`.setting-info` / `.setting-control`) used by GeneralSettings,
OllamaSettings, etc. Avoid bespoke layout here; the modal already
constrains width and padding via `.content-wrapper--full`.
Layout follows the outer Toolbox page: header action, contextual
description, and an icon tabbar with the user search alongside it.
The settings modal supplies the outer width and padding.
UI principle: every control auto-persists, no Save button. The
commit signal differs by control type so the user isn't surprised
@ -24,8 +22,6 @@
@change on every digit).
- SSRF whitelist (string_list) → controlled tag-input +
per-tag inline popconfirm.
- System admins → tag-input @change with
inline popconfirm per delta.
auth.registration_mode triggers an
inline t-popconfirm (same as Reset / bulk-apply) before persisting;
@ -35,12 +31,17 @@
<div class="section-header">
<div class="section-header__titlewrap">
<h2>{{ t('system.globalSettings.title') }}</h2>
<div id="system-users-actions" />
</div>
<div class="section-description">
<p>{{ activeSectionDescription }}</p>
<t-popup placement="bottom-start" trigger="hover" :overlay-inner-style="{ maxWidth: '420px' }">
<button type="button" class="hint-trigger" :aria-label="t('system.globalSettings.priorityHint.disclosure')">
<t-icon name="info-circle" size="16px" />
</button>
<template #content>
<div class="hint-popover">
<p class="hint-popover__scope">{{ t('system.globalSettings.description') }}</p>
<p class="hint-popover__title">{{ t('system.globalSettings.priorityHint.disclosure') }}</p>
<ul class="hint-popover__list">
<li>{{ t('system.globalSettings.priorityHint.tier1') }}</li>
@ -50,10 +51,10 @@
</div>
</template>
</t-popup>
<span v-if="activeSettingsSection === 'runtime'" class="section-description__note">
{{ t('system.globalSettings.sections.runtime.restartHint') }}
</span>
</div>
<p class="section-description">
{{ t('system.globalSettings.description') }}
</p>
</div>
<div v-if="loading && settings.length === 0" class="loading-state">
@ -66,112 +67,27 @@
</div>
<template v-else>
<t-tabs v-model="activeSettingsSection" class="settings-section-tabs">
<t-tab-panel value="access" :label="sectionTabLabel('access')" />
<t-tab-panel value="tenant" :label="sectionTabLabel('tenant')" />
<t-tab-panel value="runtime" :label="sectionTabLabel('runtime')" />
<t-tab-panel value="security" :label="sectionTabLabel('security')" />
<t-tab-panel v-if="hasUnknownSettings" value="other" :label="sectionTabLabel('other')" />
</t-tabs>
<section class="settings-section-panel" :aria-label="activeSectionTitle">
<div class="settings-section-intro"
:class="{ 'settings-section-intro--runtime': activeSettingsSection === 'runtime' }">
<p>{{ activeSectionDescription }}</p>
<t-tag v-if="activeSettingsSection === 'runtime'" theme="warning" variant="light" size="small">
{{ t('system.globalSettings.sections.runtime.restartHint') }}
</t-tag>
<div class="settings-tabbar">
<div class="settings-tabs" role="tablist" :aria-label="t('system.globalSettings.title')">
<button v-for="tab in sectionTabs" :id="`system-settings-tab-${tab.key}`" :key="tab.key"
type="button" role="tab" class="settings-tab" :data-section="tab.key"
:aria-selected="activeSettingsSection === tab.key" :tabindex="activeSettingsSection === tab.key ? 0 : -1"
:aria-controls="tab.key === 'users' ? 'system-settings-users' : 'system-settings-values'"
@click="activeSettingsSection = tab.key" @keydown="onTabKeydown($event, tab.key)">
<t-icon :name="tab.icon" size="16px" />
<span>{{ tab.label }}</span>
</button>
</div>
<div id="system-users-toolbar" class="settings-toolbar" v-show="activeSettingsSection === 'users'" />
</div>
<div v-if="activeSettingsSection === 'runtime'" class="runtime-table-header" aria-hidden="true">
<span>{{ t('system.globalSettings.runtimeTable.setting') }}</span>
<span>{{ t('system.globalSettings.runtimeTable.value') }}</span>
</div>
<div class="settings-group" :class="{ 'settings-group--runtime': activeSettingsSection === 'runtime' }">
<!--
System-admins management. Visually identical to SSRF whitelist
(a tag-input with one entry per email). NOT a system_setting
row — it's backed by the user table via promote/revoke APIs.
We sit it at the top because changing who can edit this page
is structurally more important than tweaking any value below.
Self-edit safety: the current user is excluded from the visible
tags (they can't revoke themselves anyway, and showing a tag
that can't be removed is worse than not showing it).
-->
<div v-if="activeSettingsSection === 'access'" class="setting-row setting-row--admin">
<div class="setting-info">
<div class="setting-label">
<span>{{ t('system.globalSettings.admins.label') }}</span>
<t-tag theme="danger" variant="light" size="small" class="setting-badge">
{{ t('system.globalSettings.badgeHighRisk') }}
</t-tag>
</div>
<p class="desc">{{ t('system.globalSettings.admins.description') }}</p>
</div>
<div class="setting-control">
<div class="setting-control-row">
<t-popconfirm v-model:visible="adminPopconfirm.visible" :content="adminPopconfirm.content"
:theme="adminPopconfirm.theme" :confirm-btn="adminPopconfirm.confirmBtn"
:cancel-btn="t('system.globalSettings.confirm.cancelBtn')"
:popup-props="PROGRAMMATIC_POPCONFIRM_PROPS" placement="left" @confirm="adminPopconfirm.finish(true)"
@cancel="adminPopconfirm.finish(false)" @visible-change="adminPopconfirm.onVisibleChange">
<div class="setting-control-anchor">
<t-tag-input v-model="adminEmails" :placeholder="t('system.globalSettings.admins.placeholder')"
:aria-label="t('system.globalSettings.admins.label')" :disabled="adminBusy"
class="setting-input setting-input--wide" clearable @change="onAdminsChange" />
</div>
</t-popconfirm>
<div v-if="adminBusy" class="setting-save-state" role="status">
<t-loading size="small" />
<span>{{ t('system.globalSettings.saving') }}</span>
</div>
</div>
</div>
</div>
<!-- Keep the reset request and its submit lock alive across tab changes. -->
<div v-show="activeSettingsSection === 'access'" class="setting-row setting-row--password-reset">
<div class="setting-info">
<div class="setting-label">
<span>{{ t('system.globalSettings.passwordReset.label') }}</span>
<t-tag theme="danger" variant="light" size="small" class="setting-badge">
{{ t('system.globalSettings.badgeHighRisk') }}
</t-tag>
</div>
<p class="desc">{{ t('system.globalSettings.passwordReset.description') }}</p>
</div>
<div class="setting-control">
<ResetPasswordDialog v-model:visible="passwordResetVisible" :active="activeSettingsSection === 'access'"
@announced="saveAnnouncement = $event">
<t-button theme="danger" variant="text" class="password-reset-trigger">
<template #icon><t-icon name="lock-on" /></template>
{{ t('system.globalSettings.passwordReset.action') }}
</t-button>
</ResetPasswordDialog>
</div>
</div>
<div v-if="activeSettingsSection === 'access'" class="setting-row setting-row--create-user">
<div class="setting-info">
<div class="setting-label">
<span>{{ t('system.globalSettings.createUser.label') }}</span>
<t-tag theme="danger" variant="light" size="small" class="setting-badge">
{{ t('system.globalSettings.badgeHighRisk') }}
</t-tag>
</div>
<p class="desc">{{ t('system.globalSettings.createUser.description') }}</p>
</div>
<div class="setting-control">
<CreateUserDialog v-model:visible="createUserVisible" @announced="saveAnnouncement = $event">
<t-button theme="primary" variant="text" class="create-user-trigger">
<template #icon><t-icon name="user-add" /></template>
{{ t('system.globalSettings.createUser.action') }}
</t-button>
</CreateUserDialog>
</div>
</div>
<UserManagement id="system-settings-users" role="tabpanel" aria-labelledby="system-settings-tab-users"
v-show="activeSettingsSection === 'users'" :active="activeSettingsSection === 'users'"
@announced="saveAnnouncement = $event" />
<section id="system-settings-values" v-show="activeSettingsSection !== 'users'" role="tabpanel"
class="settings-section-panel" :aria-labelledby="`system-settings-tab-${activeSettingsSection}`">
<div class="settings-group">
<div v-for="item in activeSectionSettings" :key="item.key" class="setting-row">
<div class="setting-info">
<div class="setting-label">
@ -333,21 +249,14 @@ import {
updateSystemSetting,
resetSystemSetting,
applyDefaultStorageQuotaToAllTenants,
listSystemAdmins,
promoteUserToSystemAdmin,
revokeSystemAdmin,
type SystemSettingItem,
} from '@/api/system'
import CreateUserDialog from './CreateUserDialog.vue'
import ResetPasswordDialog from './ResetPasswordDialog.vue'
import { useAuthStore } from '@/stores/auth'
import UserManagement from './UserManagement.vue'
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
import { PASSWORD_SPECIAL_CHARS } from '@/utils/passwordPolicy'
import { isSettingValueDirty, resolveCurrentSetting } from './systemSettingsEdit'
const authStore = useAuthStore()
const deploymentCapabilities = useDeploymentCapabilitiesStore()
const currentUserId = computed(() => authStore.currentUserId)
const { t, tm, te, locale } = useI18n()
@ -447,7 +356,6 @@ function createInlinePopconfirm() {
}
const ssrfPopconfirm = createInlinePopconfirm()
const adminPopconfirm = createInlinePopconfirm()
const highRiskPopconfirm = createInlinePopconfirm()
// Friendly labels for enum options live in i18n
@ -467,13 +375,13 @@ const savedKey = ref<string | null>(null)
const saveAnnouncement = ref('')
let savedKeyTimer: ReturnType<typeof setTimeout> | null = null
type SettingsSection = 'access' | 'tenant' | 'runtime' | 'security' | 'other'
type SettingsSection = 'users' | 'access' | 'tenant' | 'runtime' | 'security' | 'other'
// Product-oriented order, rather than the registry's alphabetical key order.
// Unknown/out-of-band rows remain visible in a conditional "Other" tab so the
// backend's diagnostic contract is preserved when a deployment contains an
// unexpected key.
const SETTINGS_SECTION_KEYS: Record<Exclude<SettingsSection, 'other'>, readonly string[]> = {
const SETTINGS_SECTION_KEYS: Record<Exclude<SettingsSection, 'other' | 'users'>, readonly string[]> = {
access: [
'auth.registration_mode',
'auth.complex_password_enabled',
@ -504,6 +412,36 @@ const settingsByKey = computed<Map<string, SystemSettingItem>>(() => new Map(set
const unknownSettings = computed(() => settings.value.filter((item) => !knownSettingKeys.has(item.key)))
const hasUnknownSettings = computed(() => unknownSettings.value.length > 0)
const sectionTabs = computed(() => {
const tabs: { key: SettingsSection; icon: string; label: string }[] = [
{ key: 'access', icon: 'lock-on', label: t('system.globalSettings.sections.access.title') },
{ key: 'users', icon: 'usergroup', label: t('system.globalSettings.userList.rowLabel') },
{ key: 'tenant', icon: 'folder', label: t('system.globalSettings.sections.tenant.title') },
{ key: 'runtime', icon: 'server', label: t('system.globalSettings.sections.runtime.title') },
{ key: 'security', icon: 'secured', label: t('system.globalSettings.sections.security.title') },
]
if (hasUnknownSettings.value) tabs.push({ key: 'other', icon: 'ellipsis', label: t('system.globalSettings.sections.other.title') })
return tabs
})
function onTabKeydown(event: KeyboardEvent, key: SettingsSection) {
const tabs = sectionTabs.value
const index = tabs.findIndex(tab => tab.key === key)
let next: number
switch (event.key) {
case 'ArrowRight': next = (index + 1) % tabs.length; break
case 'ArrowLeft': next = (index - 1 + tabs.length) % tabs.length; break
case 'Home': next = 0; break
case 'End': next = tabs.length - 1; break
default: return
}
event.preventDefault()
activeSettingsSection.value = tabs[next]!.key
const tablist = (event.currentTarget as HTMLElement).parentElement
tablist?.querySelector<HTMLButtonElement>(`[data-section="${activeSettingsSection.value}"]`)?.focus()
}
watch(hasUnknownSettings, (hasUnknown) => {
if (!hasUnknown && activeSettingsSection.value === 'other') {
activeSettingsSection.value = 'access'
@ -511,27 +449,19 @@ watch(hasUnknownSettings, (hasUnknown) => {
})
const activeSectionSettings = computed(() => {
if (activeSettingsSection.value === 'users') return []
if (activeSettingsSection.value === 'other') return unknownSettings.value
return SETTINGS_SECTION_KEYS[activeSettingsSection.value]
.map((key) => settingsByKey.value.get(key))
.filter((item): item is SystemSettingItem => Boolean(item))
})
const activeSectionTitle = computed(() =>
t(`system.globalSettings.sections.${activeSettingsSection.value}.title`),
)
const activeSectionDescription = computed(() =>
t(`system.globalSettings.sections.${activeSettingsSection.value}.description`),
activeSettingsSection.value === 'users' ? t('system.globalSettings.userList.rowDesc')
: t(`system.globalSettings.sections.${activeSettingsSection.value}.description`),
)
function sectionTabLabel(section: SettingsSection): string {
const count = section === 'other'
? unknownSettings.value.length
: SETTINGS_SECTION_KEYS[section].filter((key) => settingsByKey.value.has(key)).length + (section === 'access' ? 2 : 0)
return t(`system.globalSettings.sections.${section}.tab`, { count })
}
function markSettingSaved(item: SystemSettingItem) {
savedKey.value = item.key
saveAnnouncement.value = t('system.globalSettings.saveAnnouncement', {
@ -544,25 +474,6 @@ function markSettingSaved(item: SystemSettingItem) {
}, 2000)
}
// Admin management state. We keep two parallel structures:
// - adminEmails: the v-model bound to the t-tag-input (excludes
// current user; that's the visible source of truth).
// - adminEmailToId: email → user UUID, populated from the list
// endpoint. Needed because revoke takes a UUID, not an email.
// Both reset on every reload to avoid stale entries persisting after
// a peer SystemAdmin makes a change. adminBusy disables the input and
// shows the row spinner only while promote/revoke API calls are in
// flight — not while the inline popconfirm is waiting for a click.
const adminEmails = ref<string[]>([])
const adminEmailToId = ref<Record<string, string>>({})
const adminBusy = ref(false)
// Access-row popups each live in their own dialog component
// (CreateUserDialog.vue / ResetPasswordDialog.vue, same Access row);
// only their visibility is owned here.
const passwordResetVisible = ref(false)
const createUserVisible = ref(false)
// Guards ssrf.whitelist while an async confirm roundtrip is in flight.
const listConfirmBusyKey = ref<string | null>(null)
@ -985,129 +896,8 @@ async function persistSetting(item: SystemSettingItem) {
}
}
// loadAdmins refreshes the admin tag list + the email→id lookup
// table. We exclude the current user from the visible list so the
// "you can't revoke yourself" rule has nothing to enforce in the UI
// (the backend rejects it too, but hiding the tag is friendlier).
async function loadAdmins() {
try {
const resp = await listSystemAdmins({ limit: 200 })
const map: Record<string, string> = {}
const emails: string[] = []
for (const u of resp.admins ?? []) {
// Empty emails would collapse to a single tag "" that can't be
// round-tripped to a user_id; skip them. Same defensive stance
// as resolveMaxOwnedTenantsPerUser on the backend.
if (!u.email) continue
map[u.email] = u.id
if (u.id !== currentUserId.value) {
emails.push(u.email)
}
}
adminEmailToId.value = map
adminEmails.value = emails
} catch (err: any) {
const msg = err?.message || t('system.globalSettings.admins.loadFailed')
MessagePlugin.error(msg)
}
}
function confirmAdminChange(action: 'promote' | 'revoke', email: string): Promise<boolean> {
const base = `system.globalSettings.admins.confirm.${action}`
return adminPopconfirm.ask({
content: globalSettingsText(`${base}.body`, { email }),
theme: action === 'revoke' ? 'danger' : 'warning',
confirmBtn: {
content: globalSettingsText(`${base}.confirmBtn`),
theme: action === 'revoke' ? 'danger' : 'primary',
},
})
}
// onAdminsChange diffs the new tag list against the canonical state
// and dispatches one promote / revoke per delta. Failures roll back
// the whole tag list to the server-side truth — this is simpler than
// trying to undo individual ops, and the network/error case for batch
// edits is rare enough that a full reload doesn't surprise anyone.
async function onAdminsChange(next: string[]) {
if (adminBusy.value) return
// Snapshot of what's currently authoritative — the email→id map's
// keys, minus the current user. Anything in `next` that's not here
// is an addition; anything here that's not in `next` is a removal.
const authoritative = new Set<string>()
for (const email of Object.keys(adminEmailToId.value)) {
if (adminEmailToId.value[email] !== currentUserId.value) {
authoritative.add(email)
}
}
const nextSet = new Set(next.map((e) => e.trim()).filter(Boolean))
// Drop the user-typed entry to canonical lowercase/trim before we
// diff. We don't lowercase server-returned emails because the
// backend stores the original case; matching against the map's keys
// happens with the as-typed value, which is what the user sees.
const added: string[] = []
for (const email of nextSet) {
if (!authoritative.has(email)) added.push(email)
}
const removed: string[] = []
for (const email of authoritative) {
if (!nextSet.has(email)) removed.push(email)
}
if (added.length === 0 && removed.length === 0) return
// Confirm before any privilege change (no loading spinner yet — the
// popconfirm is the only UI; adminBusy is reserved for API roundtrips).
for (const email of added) {
const ok = await confirmAdminChange('promote', email)
if (!ok) {
await loadAdmins()
return
}
}
for (const email of removed) {
const userId = adminEmailToId.value[email]
if (!userId) continue
const ok = await confirmAdminChange('revoke', email)
if (!ok) {
await loadAdmins()
return
}
}
adminBusy.value = true
let applied = 0
try {
for (const email of added) {
await promoteUserToSystemAdmin({ email })
applied++
}
for (const email of removed) {
const userId = adminEmailToId.value[email]
if (!userId) continue
await revokeSystemAdmin(userId)
applied++
}
await loadAdmins()
if (applied > 0) {
saveAnnouncement.value = t('system.globalSettings.admins.saveSuccess')
MessagePlugin.success(t('system.globalSettings.admins.saveSuccess'))
}
} catch (err: any) {
const msg = err?.message || t('system.globalSettings.admins.saveFailed')
saveAnnouncement.value = msg
MessagePlugin.error(msg)
await loadAdmins()
} finally {
adminBusy.value = false
}
}
onMounted(() => {
loadSettings()
loadAdmins()
})
onUnmounted(() => {
@ -1120,8 +910,10 @@ onUnmounted(() => {
.system-settings {
width: 100%;
container-type: inline-size;
}
// Use the same title styling as the other settings pages.
.section-header {
.settings-section-header();
}
@ -1129,7 +921,28 @@ onUnmounted(() => {
.section-header__titlewrap {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--app-space-4);
padding-right: 28px;
}
.section-description {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
margin: 0;
color: var(--td-text-color-secondary);
font-size: var(--app-text-base);
line-height: 20px;
p { margin: 0; }
}
.section-description__note {
color: var(--td-text-color-placeholder);
font-size: var(--app-text-sm);
margin-left: 8px;
}
.hint-trigger {
@ -1156,6 +969,13 @@ onUnmounted(() => {
gap: 8px;
}
.hint-popover__scope {
margin: 0 0 4px;
font-size: var(--app-text-sm);
line-height: 1.6;
color: var(--td-text-color-secondary);
}
.hint-popover__title {
margin: 0;
color: var(--td-text-color-primary);
@ -1176,94 +996,72 @@ onUnmounted(() => {
}
}
.settings-section-tabs {
position: sticky;
top: 0;
z-index: 3;
margin: 0 0 18px;
background: var(--td-bg-color-container);
box-shadow: 0 1px 0 var(--td-component-stroke);
&:deep(.t-tabs__nav-item) {
font-weight: 500;
}
}
.settings-section-panel {
min-width: 0;
}
.settings-section-intro {
// Search sits in the tabbar, while the primary action belongs to the header.
.settings-tabbar {
display: flex;
align-items: flex-start;
justify-content: space-between;
align-items: center;
gap: 16px;
padding: 0 0 12px;
border-bottom: 1px solid var(--td-component-stroke);
p {
margin: 0;
font-size: var(--app-text-md);
line-height: 1.5;
color: var(--td-text-color-secondary);
}
margin-bottom: var(--app-space-4);
}
.settings-section-intro--runtime {
border-bottom: none;
}
.runtime-table-header {
display: grid;
grid-template-columns: minmax(0, 1fr) 280px;
.settings-tabs {
flex: 1;
min-width: 0;
display: flex;
gap: 24px;
padding: 10px 16px;
font-size: var(--app-text-sm);
font-weight: 500;
color: var(--td-text-color-secondary);
background: var(--td-bg-color-secondarycontainer);
border: 1px solid var(--td-component-stroke);
border-bottom: none;
border-radius: 8px 8px 0 0;
overflow-x: auto;
scrollbar-width: none;
}
span:last-child {
text-align: right;
.settings-toolbar { flex-shrink: 0; }
.settings-tab {
position: relative;
flex-shrink: 0;
display: inline-flex;
align-items: center;
gap: 6px;
height: 44px;
padding: 0 2px;
border: 0;
background: transparent;
color: var(--td-text-color-secondary);
font: inherit;
font-size: var(--app-text-base);
font-weight: 500;
cursor: pointer;
transition: color var(--app-motion-fast) ease;
&::after {
content: '';
position: absolute;
left: 0;
right: 0;
bottom: 0;
height: 2px;
border-radius: var(--app-radius-pill);
background: transparent;
}
&:hover { color: var(--td-text-color-primary); }
&[aria-selected='true'] {
color: var(--td-text-color-primary);
> .t-icon { color: var(--td-brand-color); }
&::after { background: var(--td-brand-color); }
}
&:focus-visible {
outline: 2px solid var(--td-brand-color);
outline-offset: -2px;
border-radius: var(--app-radius-sm);
}
}
.settings-group--runtime {
border: 1px solid var(--td-component-stroke);
border-radius: 0 0 8px 8px;
overflow: hidden;
.settings-section-panel { min-width: 0; }
.setting-row {
display: grid;
grid-template-columns: minmax(0, 1fr) 280px;
gap: 24px;
padding: 14px 16px;
}
.setting-info {
max-width: none;
padding-right: 0;
}
.setting-label {
font-size: var(--app-text-base);
}
.desc {
max-width: 620px;
font-size: var(--app-text-sm);
}
.setting-control {
min-width: 0;
}
.setting-input {
width: 210px;
}
@container (max-width: 900px) {
.settings-tabbar { flex-wrap: wrap; gap: 0; }
.settings-tabs { flex-basis: 100%; }
.settings-toolbar { width: 100%; padding: 8px 0; }
}
.sr-only {
@ -1299,7 +1097,7 @@ onUnmounted(() => {
flex-shrink: 0;
}
// Anchor wrapper for inline t-popconfirm on inputs (SSRF / admins /
// Anchor wrapper for inline t-popconfirm on inputs (SSRF /
// high-risk select). Popconfirm attaches to this box so the bubble
// appears beside the control, not a full-screen modal.
.setting-control-anchor {
@ -1318,13 +1116,7 @@ onUnmounted(() => {
font-size: var(--app-text-md);
}
// Skeleton mirrors GeneralSettings.vue 1:1 so the two panes feel like
// they came from the same hand. Values that diverge intentionally:
// - .setting-label is a flex container (vs General's plain <label>)
// because we render badges inline with the title; identical font /
// spacing otherwise.
// - .desc has a max-width so long backend descriptions don't push
// the control off the canvas in narrow viewports.
// All settings tabs share one description/control grid.
.settings-group {
display: flex;
flex-direction: column;
@ -1333,10 +1125,18 @@ onUnmounted(() => {
.setting-row {
.setting-row();
display: grid;
grid-template-columns: minmax(0, 1fr) 320px;
gap: 32px;
padding: 24px 0;
&:first-child { padding-top: 0; }
}
.setting-info {
.setting-info();
max-width: none;
padding-right: 0;
}
.setting-label {
@ -1359,8 +1159,8 @@ onUnmounted(() => {
font-size: var(--app-text-md);
color: var(--td-text-color-secondary);
margin: 0;
line-height: 1.5;
max-width: 480px;
line-height: 1.65;
max-width: 600px;
}
.setting-meta {
@ -1371,6 +1171,7 @@ onUnmounted(() => {
.setting-control {
.setting-control();
min-width: 0;
flex-direction: column;
align-items: flex-end;
gap: 6px;
@ -1388,14 +1189,6 @@ onUnmounted(() => {
justify-content: flex-end;
}
.setting-saving {
// Pin width so the row layout doesn't reflow when the spinner
// appears / disappears mid-save.
width: 16px;
height: 16px;
flex-shrink: 0;
}
.setting-input {
width: 240px;
}
@ -1404,57 +1197,9 @@ onUnmounted(() => {
width: 320px;
}
.password-reset-trigger,
.create-user-trigger {
min-width: 112px;
height: 32px;
padding: 0 12px;
border: 1px solid transparent;
border-radius: var(--app-radius-sm);
}
.password-reset-trigger {
color: var(--td-error-color);
background: var(--td-error-color-light);
&:hover {
color: var(--td-error-color-hover);
background: var(--td-error-color-light-hover);
border-color: var(--td-error-color-focus);
}
&:active {
color: var(--td-error-color-active);
background: var(--td-error-color-focus);
}
}
@media (max-width: 860px) {
.settings-section-intro {
align-items: flex-start;
flex-direction: column;
}
.runtime-table-header {
display: none;
}
.settings-group--runtime {
border-radius: var(--app-radius-md);
.setting-row {
display: flex;
flex-direction: column;
gap: 12px;
}
.setting-input {
width: 100%;
}
}
.setting-row {
flex-direction: column;
grid-template-columns: minmax(0, 1fr);
gap: 12px;
}

View File

@ -0,0 +1,208 @@
<template>
<section class="user-management" :aria-label="t('system.globalSettings.userList.rowLabel')">
<Teleport to="#system-users-actions">
<div v-show="active">
<CreateUserDialog v-model:visible="createVisible" :active="active" @created="fetchPage(0)" @announced="announce">
<t-button variant="text" size="small" class="user-management__create"
:disabled="loading || busyId !== null || resetVisibleId !== null">
<template #icon><t-icon name="add" size="16px" /></template>
{{ t('system.globalSettings.createUser.action') }}
</t-button>
</CreateUserDialog>
</div>
</Teleport>
<Teleport to="#system-users-toolbar">
<div v-show="active" class="user-management__tools">
<t-input v-model="search" :disabled="locked" class="user-management__search" clearable
:placeholder="t('system.globalSettings.userList.searchPlaceholder')"
:aria-label="t('system.globalSettings.userList.searchPlaceholder')">
<template #prefix-icon><t-icon name="search" size="16px" /></template>
</t-input>
<t-button variant="text" shape="square" :loading="loading" :disabled="locked"
:title="t('system.globalSettings.userList.refresh')" :aria-label="t('system.globalSettings.userList.refresh')"
@click="fetchPage(offset)">
<template #icon><t-icon name="refresh" size="16px" /></template>
</t-button>
</div>
</Teleport>
<t-alert v-if="loadError" theme="error" :message="loadError" />
<div class="user-management__table">
<div class="user-management__scroll">
<t-table :aria-label="t('system.globalSettings.userList.title')" row-key="id" :data="filteredUsers" :columns="columns" :loading="loading" size="medium" hover>
<template #user="{ row }">
<div class="user-management__identity">
<span class="user-management__name">{{ row.username }}
<span v-if="row.id === authStore.currentUserId" class="user-management__self">{{ t('common.me') }}</span>
</span>
<span class="user-management__email">{{ row.email }}</span>
</div>
</template>
<template #status="{ row }">
<span class="user-management__status" :class="{ 'is-active': row.is_active }">
<span class="user-management__status-dot" aria-hidden="true" />
{{ row.is_active ? t('system.globalSettings.userList.active') : t('system.globalSettings.userList.inactive') }}
</span>
</template>
<template #role="{ row }">
<span v-if="row.id === authStore.currentUserId" class="user-management__own-role">
{{ t('system.globalSettings.userList.roleAdmin') }}
</span>
<t-popconfirm v-else :visible="active && pendingRole?.id === row.id"
:content="row.is_system_admin
? t('system.globalSettings.userList.confirmRevoke', { name: row.username })
: t('system.globalSettings.userList.confirmPromote', { name: row.username })"
:popup-props="{ trigger: 'context-menu', overlayClassName: 'wk-popover user-management-confirm-popup' }" placement="left" theme="warning"
:confirm-btn="{ content: t(row.is_system_admin ? 'system.globalSettings.userList.revokeBtn' : 'system.globalSettings.userList.promoteBtn'), theme: row.is_system_admin ? 'danger' : 'primary', loading: busyId === row.id }"
:cancel-btn="t('common.cancel')" @confirm="changeRole(row)" @cancel="pendingRole = null"
@visible-change="(v: boolean) => { if (!v && !busyId) pendingRole = null }">
<t-select :model-value="row.is_system_admin ? 'admin' : 'user'" :options="roleOptions"
:aria-label="`${row.username} · ${t('system.globalSettings.userList.colRole')}`" :borderless="true"
class="user-management__role" :disabled="loading || locked"
:popup-props="{ overlayClassName: 'wk-popover user-management-role-popup' }"
@change="(value: unknown) => { if (value !== (row.is_system_admin ? 'admin' : 'user')) pendingRole = row }" />
</t-popconfirm>
</template>
<template #created="{ row }"><span class="user-management__date">{{ formatDate(row.created_at) }}</span></template>
<template #actions="{ row }">
<div class="user-management__actions">
<ResetPasswordDialog :visible="resetVisibleId === row.id" :active="active" :email="row.email"
@update:visible="value => { resetVisibleId = value ? row.id : null }"
@busy-change="resetBusy = $event" @announced="announce">
<t-button variant="text" class="user-management__action"
:disabled="loading || busyId !== null || resetBusy || (resetVisibleId !== null && resetVisibleId !== row.id) || createVisible || row.id === authStore.currentUserId || !row.is_active"
:title="t('system.globalSettings.userList.resetPassword')" :aria-label="t('system.globalSettings.userList.resetPassword')">
{{ t('system.globalSettings.userList.resetPassword') }}
</t-button>
</ResetPasswordDialog>
<t-popconfirm :visible="active && statusVisibleId === row.id" placement="left" theme="warning"
:popup-props="{ overlayClassName: 'wk-popover user-management-confirm-popup' }"
:content="t(row.is_active ? 'system.globalSettings.userList.confirmDisable' : 'system.globalSettings.userList.confirmEnable', { name: row.username })"
:confirm-btn="{ content: t(row.is_active ? 'system.globalSettings.userList.disable' : 'system.globalSettings.userList.enable'), theme: row.is_active ? 'danger' : 'primary', loading: busyId === row.id }"
:cancel-btn="t('common.cancel')" @visible-change="(value: boolean) => { statusVisibleId = value ? row.id : null }"
@confirm="changeStatus(row)">
<t-button variant="text" class="user-management__action"
:disabled="loading || locked || row.id === authStore.currentUserId"
:title="t(row.is_active ? 'system.globalSettings.userList.disable' : 'system.globalSettings.userList.enable')"
:aria-label="t(row.is_active ? 'system.globalSettings.userList.disable' : 'system.globalSettings.userList.enable')">
{{ t(row.is_active ? 'system.globalSettings.userList.disable' : 'system.globalSettings.userList.enable') }}
</t-button>
</t-popconfirm>
</div>
</template>
</t-table>
</div>
<div class="user-management__pager">
<span class="user-management__count">{{ t('system.globalSettings.userList.pageCount', { shown: filteredUsers.length, total: users.length }) }}</span>
<t-button variant="text" shape="square" size="small" :disabled="offset === 0 || loading || locked"
:aria-label="t('system.globalSettings.userList.prev')" :title="t('system.globalSettings.userList.prev')" @click="fetchPage(offset - limit)">
<template #icon><t-icon name="chevron-left" /></template>
</t-button>
<span class="user-management__page">{{ Math.floor(offset / limit) + 1 }}</span>
<t-button variant="text" shape="square" size="small" :disabled="!hasMore || loading || locked"
:aria-label="t('system.globalSettings.userList.next')" :title="t('system.globalSettings.userList.next')" @click="fetchPage(offset + limit)">
<template #icon><t-icon name="chevron-right" /></template>
</t-button>
</div>
</div>
</section>
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { MessagePlugin } from 'tdesign-vue-next'
import { listAllUsers, setUserStatus, promoteUserToSystemAdmin, revokeSystemAdmin, type SystemAdminUser } from '@/api/system'
import { useAuthStore } from '@/stores/auth'
import CreateUserDialog from './CreateUserDialog.vue'
import ResetPasswordDialog from './ResetPasswordDialog.vue'
const props = defineProps<{ active: boolean }>()
const emit = defineEmits<{ announced: [string] }>()
const { t, locale } = useI18n()
const authStore = useAuthStore()
const users = ref<SystemAdminUser[]>([])
const loading = ref(false)
const loadError = ref('')
const offset = ref(0)
const limit = 20
const hasMore = ref(false)
const search = ref('')
const busyId = ref<string | null>(null)
const pendingRole = ref<SystemAdminUser | null>(null)
const statusVisibleId = ref<string | null>(null)
const resetVisibleId = ref<string | null>(null)
const resetBusy = ref(false)
const createVisible = ref(false)
const locked = computed(() => busyId.value !== null || resetVisibleId.value !== null || createVisible.value)
const roleOptions = computed(() => [
{ value: 'user', label: t('system.globalSettings.userList.roleUser') },
{ value: 'admin', label: t('system.globalSettings.userList.roleAdmin') },
])
const columns = computed(() => [
{ colKey: 'user', title: t('system.globalSettings.userList.colUsername'), minWidth: 230 },
{ colKey: 'role', title: t('system.globalSettings.userList.colRole'), width: 160 },
{ colKey: 'status', title: t('system.globalSettings.userList.colStatus'), width: 100 },
{ colKey: 'created', title: t('system.globalSettings.userList.colCreated'), width: 130 },
{ colKey: 'actions', title: t('system.globalSettings.userList.colAction'), width: 170 },
])
const filteredUsers = computed(() => {
const query = search.value.trim().toLowerCase()
return users.value.filter(user => !query || `${user.username} ${user.email}`.toLowerCase().includes(query))
})
function formatDate(value: string) {
const date = new Date(value)
return Number.isNaN(date.getTime()) ? value : date.toLocaleDateString(locale.value)
}
function errorMessage(error: any, key: string): string {
return error?.response?.data?.error || error?.message || t(key)
}
function announce(message: string) { emit('announced', message) }
async function fetchPage(nextOffset: number) {
if (loading.value || resetBusy.value) return
loading.value = true
loadError.value = ''
pendingRole.value = null
statusVisibleId.value = null
try {
const response = await listAllUsers({ offset: nextOffset, limit })
users.value = response.users
hasMore.value = response.has_more
offset.value = response.offset
} catch (error) {
loadError.value = errorMessage(error, 'system.globalSettings.userList.loadFailed')
} finally { loading.value = false }
}
async function changeStatus(row: SystemAdminUser) {
if (busyId.value || row.id === authStore.currentUserId) return
busyId.value = row.id
try {
const response = await setUserStatus({ user_id: row.id, is_active: !row.is_active })
row.is_active = response.is_active
const message = t(row.is_active ? 'system.globalSettings.userList.enabledMsg' : 'system.globalSettings.userList.disabledMsg', { name: row.username })
MessagePlugin.success(message)
announce(message)
} catch (error) { MessagePlugin.error(errorMessage(error, 'system.globalSettings.userList.actionFailed')) }
finally { busyId.value = null; statusVisibleId.value = null }
}
async function changeRole(row: SystemAdminUser) {
if (busyId.value || row.id === authStore.currentUserId) return
busyId.value = row.id
try {
const updated = row.is_system_admin ? await revokeSystemAdmin(row.id) : await promoteUserToSystemAdmin({ user_id: row.id })
row.is_system_admin = updated.is_system_admin
const message = t(row.is_system_admin ? 'system.globalSettings.userList.promotedMsg' : 'system.globalSettings.userList.revokedMsg', { name: row.username })
MessagePlugin.success(message)
announce(message)
} catch (error) { MessagePlugin.error(errorMessage(error, 'system.globalSettings.userList.roleFailed')) }
finally { busyId.value = null; pendingRole.value = null }
}
watch(() => props.active, active => {
if (active && !locked.value) fetchPage(offset.value)
if (!active) { pendingRole.value = null; statusVisibleId.value = null }
}, { immediate: true })
</script>
<style scoped lang="less" src="./userManagement.less"></style>
<style lang="less">
.user-management-role-popup, .user-management-confirm-popup { z-index: 3050 !important; }
</style>

View File

@ -40,6 +40,12 @@
color: var(--td-text-color-secondary);
}
.system-admin-action-popup-target {
color: var(--td-text-color-primary);
font-size: var(--app-text-base);
line-height: 24px;
}
.system-admin-action-popup-form {
.t-form__item {
margin-bottom: 14px;

View File

@ -0,0 +1,63 @@
@import (reference) '@/components/css/settings-table.less';
.user-management {
width: 100%;
min-width: 0;
&__tools, &__actions, &__pager {
display: flex;
align-items: center;
gap: 8px;
}
&__tools { gap: 4px; }
&__create.t-button {
flex-shrink: 0;
min-height: 32px;
padding: 0 12px;
gap: 6px;
border: 1px solid var(--td-component-stroke);
border-radius: var(--app-radius-sm);
background: var(--td-bg-color-container);
color: var(--td-text-color-primary);
font-size: var(--app-text-md);
transition: background var(--app-motion-base);
&:hover:not(:disabled) { background: var(--td-bg-color-container-hover); }
&:focus-visible { outline: 2px solid var(--td-brand-color); outline-offset: 2px; }
:deep(.t-icon) { color: var(--td-brand-color); }
}
&__search { width: 240px; max-width: 100%; }
&__search :deep(.t-input) { border-radius: var(--app-radius-sm); }
&__table {
.settings-data-table();
overflow: hidden;
:deep(thead th) {
background: var(--td-bg-color-secondarycontainer);
color: var(--td-text-color-secondary);
font-weight: 500;
}
:deep(.t-table tbody tr:last-child td) { border-bottom: 0; }
}
&__scroll { overflow-x: auto; }
&__identity { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
&__name { font-size: var(--app-text-base); font-weight: 500; color: var(--td-text-color-primary); line-height: 22px; }
&__email { font-size: var(--app-text-sm); line-height: 18px; color: var(--td-text-color-secondary); }
&__name, &__email { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
&__date { font-size: var(--app-text-md); color: var(--td-text-color-secondary); font-variant-numeric: tabular-nums; }
&__self { margin-left: 6px; color: var(--td-text-color-placeholder); font-size: var(--app-text-sm); font-weight: 400; }
&__role { width: 136px; margin-left: -8px; }
&__role :deep(.t-input) { font-size: var(--app-text-md); }
&__own-role { font-size: var(--app-text-md); color: var(--td-text-color-primary); }
&__status { display: inline-flex; align-items: center; gap: 7px; font-size: var(--app-text-md); color: var(--td-text-color-secondary); }
&__status-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--td-text-color-disabled); }
&__status.is-active &__status-dot { background: var(--td-success-color); }
&__actions { gap: 8px; margin-left: -8px; }
&__action { padding: 0 8px; font-size: var(--app-text-md); }
&__pager { justify-content: flex-end; padding: 10px 16px; border-top: 1px solid var(--td-component-stroke); }
&__count { margin-right: auto; font-size: var(--app-text-sm); color: var(--td-text-color-secondary); }
&__page { min-width: 24px; text-align: center; font-size: var(--app-text-sm); color: var(--td-text-color-primary); }
}
@media (max-width: 860px) {
.user-management__search { flex: 1; min-width: 180px; }
}

View File

@ -3,6 +3,7 @@ package repository
import (
"context"
"errors"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
@ -11,11 +12,21 @@ import (
)
var (
ErrUserNotFound = errors.New("user not found")
ErrUserAlreadyExists = errors.New("user already exists")
ErrTokenNotFound = errors.New("token not found")
ErrCannotRevokeSelf = errors.New("cannot revoke your own system admin privileges")
ErrLastSystemAdmin = errors.New("cannot revoke the last remaining system administrator")
// ErrCannotDisableSelf prevents administrators from disabling their own account.
ErrCannotDisableSelf = errors.New("cannot disable your own account")
// ErrCannotDisableLastAdmin preserves at least one active system administrator.
ErrCannotDisableLastAdmin = errors.New("cannot disable the last system administrator")
// ErrUserNotFound indicates that the requested user does not exist.
ErrUserNotFound = errors.New("user not found")
// ErrUserAlreadyExists indicates a duplicate user account.
ErrUserAlreadyExists = errors.New("user already exists")
// ErrTokenNotFound indicates that the requested token does not exist.
ErrTokenNotFound = errors.New("token not found")
// ErrCannotRevokeSelf prevents administrators from revoking their own role.
ErrCannotRevokeSelf = errors.New("cannot revoke your own system admin privileges")
// ErrLastSystemAdmin prevents revoking the last active system administrator's role.
ErrLastSystemAdmin = errors.New("cannot revoke the last remaining system administrator")
// ErrUserNotSystemAdmin indicates that the user has no system-admin role to revoke.
ErrUserNotSystemAdmin = errors.New("user is not a system administrator")
)
@ -110,14 +121,16 @@ func (r *userRepository) GetUserByTenantID(ctx context.Context, tenantID uint64)
return &user, nil
}
// UpdateUser updates a user
// UpdateUser updates user data while preserving account status. Status changes
// must go through SetUserActive so stale profile/password writes cannot undo
// an administrator's enable/disable action.
func (r *userRepository) UpdateUser(ctx context.Context, user *types.User) error {
if user != nil && user.TenantID == 0 {
return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
// Preserve Save's all-fields behaviour while keeping the nullable
// tenant column out of the struct write, then explicitly store NULL.
// Keep status and the nullable tenant column out of the struct
// write, then explicitly store NULL for the tenant.
// Writing uint64(0) would violate the PostgreSQL tenant FK.
if err := tx.Omit("tenant_id").Save(user).Error; err != nil {
if err := tx.Omit("tenant_id", "is_active").Save(user).Error; err != nil {
return err
}
return tx.Model(&types.User{}).
@ -125,7 +138,7 @@ func (r *userRepository) UpdateUser(ctx context.Context, user *types.User) error
UpdateColumn("tenant_id", nil).Error
})
}
return r.db.WithContext(ctx).Save(user).Error
return r.db.WithContext(ctx).Omit("is_active").Save(user).Error
}
// DeleteUser deletes a user
@ -185,6 +198,85 @@ func (r *userRepository) ListSystemAdmins(ctx context.Context, offset, limit int
return users, total, nil
}
// lockSystemAdmins uses the same lock order for status changes and role
// revocation: all admin rows by ID, then the target user. SQLite has no row
// locks, so acquire its writer lock before reading the administrator set.
func lockSystemAdmins(tx *gorm.DB) ([]types.User, error) {
if tx.Name() == "sqlite" {
if err := tx.Model(&types.User{}).Where("is_system_admin = ?", true).
UpdateColumn("is_system_admin", true).Error; err != nil {
return nil, err
}
}
var admins []types.User
err := lockUserRows(tx).Where("is_system_admin = ?", true).Order("id ASC").Find(&admins).Error
return admins, err
}
func lockUserRows(tx *gorm.DB) *gorm.DB {
switch tx.Name() {
case "postgres", "mysql":
return tx.Clauses(clause.Locking{Strength: "UPDATE"})
default:
return tx
}
}
func activeSystemAdminCount(admins []types.User) int {
n := 0
for _, admin := range admins {
if admin.IsActive {
n++
}
}
return n
}
// SetUserActive persists status and session revocation in one transaction.
// Locking the admin set also serializes this operation with role revocation.
func (r *userRepository) SetUserActive(ctx context.Context, userID, actorID string, active bool) (*types.User, error) {
var user types.User
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
admins, err := lockSystemAdmins(tx)
if err != nil {
return err
}
if err := lockUserRows(tx).Where("id = ?", userID).First(&user).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return ErrUserNotFound
}
return err
}
if user.IsActive == active {
return nil
}
if !active {
if userID == actorID {
return ErrCannotDisableSelf
}
if user.IsSystemAdmin && activeSystemAdminCount(admins) <= 1 {
return ErrCannotDisableLastAdmin
}
}
user.IsActive = active
user.UpdatedAt = time.Now()
if err := tx.Model(&user).Updates(map[string]any{
"is_active": active, "updated_at": user.UpdatedAt,
}).Error; err != nil {
return err
}
if !active {
return tx.Model(&types.AuthToken{}).Where("user_id = ?", userID).
Update("is_revoked", true).Error
}
return nil
})
if err != nil {
return nil, err
}
return &user, nil
}
// RevokeSystemAdmin revokes system-admin privileges inside a transaction.
// It locks the current admin rows before counting so concurrent revokes
// cannot both observe "two admins" and leave the platform with zero.
@ -204,16 +296,12 @@ func (r *userRepository) RevokeSystemAdmin(ctx context.Context, userID, actorID
var revoked *types.User
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
locking := func(db *gorm.DB) *gorm.DB {
switch tx.Dialector.Name() {
case "postgres", "mysql":
return db.Clauses(clause.Locking{Strength: "UPDATE"})
default:
return db
}
admins, err := lockSystemAdmins(tx)
if err != nil {
return err
}
var user types.User
if err := locking(tx).
if err := lockUserRows(tx).
Where("id = ?", userID).
First(&user).Error; err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
@ -226,18 +314,12 @@ func (r *userRepository) RevokeSystemAdmin(ctx context.Context, userID, actorID
return ErrUserNotSystemAdmin
}
var admins []types.User
if err := locking(tx).
Where("is_system_admin = ?", true).
Find(&admins).Error; err != nil {
return err
}
if len(admins) <= 1 {
if len(admins) <= 1 || (user.IsActive && activeSystemAdminCount(admins) <= 1) {
return ErrLastSystemAdmin
}
user.IsSystemAdmin = false
if err := tx.Save(&user).Error; err != nil {
if err := tx.Model(&user).Update("is_system_admin", false).Error; err != nil {
return err
}
revoked = &user

View File

@ -0,0 +1,235 @@
package repository
import (
"context"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"time"
"github.com/Tencent/WeKnora/internal/types"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
// Each PostgreSQL run owns a schema; never migrate or change existing tables.
func userStatusBackends(t *testing.T, fn func(*testing.T, *gorm.DB)) {
for _, backend := range []string{"sqlite", "postgres"} {
t.Run(backend, func(t *testing.T) {
var db *gorm.DB
var err error
cfg := &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}
if backend == "sqlite" {
db, err = gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "users.db")+"?_busy_timeout=5000"), cfg)
} else {
dsn := os.Getenv("WEKNORA_REPOSITORY_TEST_POSTGRES_DSN")
if dsn == "" {
t.Skip("set WEKNORA_REPOSITORY_TEST_POSTGRES_DSN for PostgreSQL locking tests")
}
adminDB, openErr := gorm.Open(postgres.Open(dsn), cfg)
require.NoError(t, openErr)
adminSQL, openErr := adminDB.DB()
require.NoError(t, openErr)
schema := "user_status_" + strings.ReplaceAll(uuid.NewString(), "-", "")
require.NoError(t, adminDB.Exec("CREATE SCHEMA "+schema).Error)
t.Cleanup(func() {
require.NoError(t, adminDB.Exec("DROP SCHEMA "+schema+" CASCADE").Error)
require.NoError(t, adminSQL.Close())
})
separator := " "
if strings.Contains(dsn, "://") {
separator = "?"
if strings.Contains(dsn, "?") {
separator = "&"
}
}
db, err = gorm.Open(postgres.Open(dsn+separator+"search_path="+schema), cfg)
}
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
sqlDB.SetMaxOpenConns(4)
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
require.NoError(t, db.AutoMigrate(&types.User{}, &types.AuthToken{}))
fn(t, db)
})
}
}
func seedStatusUser(t *testing.T, db *gorm.DB, id string, admin, active bool) {
t.Helper()
user := &types.User{
ID: id, Username: id, Email: id + "@example.com",
PasswordHash: "hash", IsSystemAdmin: admin, IsActive: true,
}
require.NoError(t, NewUserRepository(db).CreateUser(context.Background(), user))
if !active {
require.NoError(t, db.Model(user).Update("is_active", false).Error)
}
}
func TestSetUserActiveGuardsAndSessions(t *testing.T) {
userStatusBackends(t, func(t *testing.T, db *gorm.DB) {
ctx := context.Background()
repo := NewUserRepository(db)
seedStatusUser(t, db, "admin", true, true)
seedStatusUser(t, db, "disabled-admin", true, false)
seedStatusUser(t, db, "user", false, true)
for _, kind := range []string{"access_token", "refresh_token"} {
require.NoError(t, db.Create(&types.AuthToken{
ID: kind, UserID: "user", Token: kind, TokenType: kind,
ExpiresAt: time.Now().Add(time.Hour),
}).Error)
}
_, err := repo.SetUserActive(ctx, "missing", "admin", false)
require.ErrorIs(t, err, ErrUserNotFound)
_, err = repo.SetUserActive(ctx, "admin", "admin", false)
require.ErrorIs(t, err, ErrCannotDisableSelf)
_, err = repo.SetUserActive(ctx, "admin", "another-actor", false)
require.ErrorIs(t, err, ErrCannotDisableLastAdmin)
_, err = repo.RevokeSystemAdmin(ctx, "admin", "another-actor")
require.ErrorIs(t, err, ErrLastSystemAdmin)
_, err = repo.SetUserActive(ctx, "user", "admin", true)
require.NoError(t, err)
var revoked int64
require.NoError(t, db.Model(&types.AuthToken{}).Where("is_revoked = ?", true).Count(&revoked).Error)
require.Zero(t, revoked, "enabling an already active user must preserve sessions")
user, err := repo.SetUserActive(ctx, "user", "admin", false)
require.NoError(t, err)
require.False(t, user.IsActive)
require.NoError(t, db.Model(&types.AuthToken{}).Where("is_revoked = ?", true).Count(&revoked).Error)
require.EqualValues(t, 2, revoked)
user, err = repo.SetUserActive(ctx, "user", "admin", true)
require.NoError(t, err)
require.True(t, user.IsActive)
require.Equal(t, "hash", user.PasswordHash)
require.Zero(t, user.TenantID)
require.NoError(t, db.Model(&types.AuthToken{}).Where("is_revoked = ?", true).Count(&revoked).Error)
require.EqualValues(t, 2, revoked, "re-enabling must not restore old sessions")
})
}
func TestSetUserActiveRollsBackWhenRevocationFails(t *testing.T) {
userStatusBackends(t, func(t *testing.T, db *gorm.DB) {
seedStatusUser(t, db, "user", false, true)
require.NoError(t, db.Migrator().DropTable(&types.AuthToken{}))
repo := NewUserRepository(db)
_, err := repo.SetUserActive(context.Background(), "user", "admin", false)
require.Error(t, err)
user, err := repo.GetUserByID(context.Background(), "user")
require.NoError(t, err)
require.True(t, user.IsActive, "failed revocation must roll back the status change")
})
}
func TestUserUpdatePreservesAccountStatus(t *testing.T) {
for _, scope := range []struct {
name string
tenantID uint64
}{
{name: "tenantless"},
{name: "with-tenant", tenantID: 1},
} {
t.Run(scope.name, func(t *testing.T) {
for _, change := range []struct {
name string
active bool
}{
{name: "disable"},
{name: "enable", active: true},
} {
t.Run(change.name, func(t *testing.T) {
userStatusBackends(t, func(t *testing.T, db *gorm.DB) {
ctx := context.Background()
repo := NewUserRepository(db)
seedStatusUser(t, db, "user", false, !change.active)
if scope.tenantID != 0 {
require.NoError(t, db.Model(&types.User{}).Where("id = ?", "user").
UpdateColumn("tenant_id", scope.tenantID).Error)
}
// Pause an ordinary update after its read, then commit an admin
// status change before the stale user object is written back.
stale, err := repo.GetUserByID(ctx, "user")
require.NoError(t, err)
_, err = repo.SetUserActive(ctx, "user", "admin", change.active)
require.NoError(t, err)
instructions := "updated preference"
stale.Preferences.BrowserSearchInstructions = &instructions
stale.PasswordHash = "updated hash"
require.NoError(t, repo.UpdateUser(ctx, stale))
stored, err := repo.GetUserByID(ctx, "user")
require.NoError(t, err)
require.Equal(t, change.active, stored.IsActive,
"ordinary updates must preserve account status")
require.Equal(t, scope.tenantID, stored.TenantID)
require.Equal(t, "updated hash", stored.PasswordHash)
require.Equal(t, &instructions, stored.Preferences.BrowserSearchInstructions)
})
})
}
})
}
}
func TestConcurrentAdminChangesKeepOneActiveAdmin(t *testing.T) {
for _, mode := range []string{"disable-disable", "disable-revoke", "revoke-revoke"} {
t.Run(mode, func(t *testing.T) {
userStatusBackends(t, func(t *testing.T, db *gorm.DB) {
seedStatusUser(t, db, "a", true, true)
seedStatusUser(t, db, "b", true, true)
for i := 0; i < 20; i++ {
require.NoError(t, db.Model(&types.User{}).
Where("id IN ?", []string{"a", "b"}).
Updates(map[string]any{"is_active": true, "is_system_admin": true}).Error)
start := make(chan struct{})
results := make(chan error, 2)
for n, id := range []string{"a", "b"} {
go func(n int, id string) {
<-start
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
repo := NewUserRepository(db)
actor := "a"
if id == "a" {
actor = "b"
}
var err error
if mode == "revoke-revoke" || (mode == "disable-revoke" && n == 1) {
_, err = repo.RevokeSystemAdmin(ctx, id, actor)
} else {
_, err = repo.SetUserActive(ctx, id, actor, false)
}
results <- err
}(n, id)
}
close(start)
successes := 0
for n := 0; n < 2; n++ {
err := <-results
if err == nil {
successes++
} else {
require.True(t,
errors.Is(err, ErrCannotDisableLastAdmin) || errors.Is(err, ErrLastSystemAdmin),
"unexpected error: %v", err)
}
}
require.Equal(t, 1, successes)
var count int64
require.NoError(t, db.Model(&types.User{}).
Where("is_system_admin = ? AND is_active = ?", true, true).Count(&count).Error)
require.EqualValues(t, 1, count)
}
})
})
}
}

View File

@ -646,3 +646,7 @@ func TestTenantRole_HasPermission(t *testing.T) {
}
}
}
func (r *cleanupUserRepo) SetUserActive(context.Context, string, string, bool) (*types.User, error) {
panic("unexpected SetUserActive call")
}

View File

@ -594,6 +594,36 @@ func (s *userService) UpdateUser(ctx context.Context, user *types.User) error {
return s.userRepo.UpdateUser(ctx, user)
}
// Account-status errors share repository identity for errors.Is at the HTTP boundary.
var (
ErrCannotDisableSelf = apprepo.ErrCannotDisableSelf
ErrCannotDisableLastAdmin = apprepo.ErrCannotDisableLastAdmin
ErrUserNotFound = apprepo.ErrUserNotFound
)
// SetUserActive changes status and revokes sessions atomically with the
// repository's self-disable and last-active-admin guards.
func (s *userService) SetUserActive(ctx context.Context, userID, actorID string, active bool) (*types.User, error) {
return s.userRepo.SetUserActive(ctx, userID, actorID, active)
}
// ListAllUsers lists every platform user newest-first for the system-admin
// user-management UI. It fetches limit+1 rows to derive has_more without a
// separate COUNT. Role gating is the handler's responsibility.
func (s *userService) ListAllUsers(
ctx context.Context, offset, limit int,
) ([]*types.User, bool, error) {
rows, err := s.userRepo.ListUsers(ctx, offset, limit+1)
if err != nil {
return nil, false, err
}
hasMore := len(rows) > limit
if hasMore {
rows = rows[:limit]
}
return rows, hasMore, nil
}
// ListSystemAdmins lists users with IsSystemAdmin=true. Thin pass-through
// to the repository; the handler enforces SystemAdmin gating, so the
// service does not duplicate the role check here.
@ -1300,6 +1330,13 @@ func (s *userService) ValidateToken(ctx context.Context, tokenString string) (*t
return nil, 0, err
}
// Defence in depth: a token minted before the account was disabled must
// stop working even if revocation missed it. Login also rejects disabled
// accounts, but long-lived access tokens are checked here per request.
if !user.IsActive {
return nil, 0, errors.New("account is disabled")
}
// Extract active tenant from the JWT. Anything missing or unparseable
// falls back to the user's home tenant so old tokens (and tokens issued
// by code paths that don't yet set the claim) keep working.

View File

@ -126,7 +126,7 @@ func newAuthTestUserService(tokenRepo *stubAuthTokenRepo) *userService {
return &userService{
userRepo: &stubUserRepoForAuth{
users: map[string]*types.User{
"user-1": {ID: "user-1", TenantID: 1},
"user-1": {ID: "user-1", TenantID: 1, IsActive: true},
},
},
tokenRepo: tokenRepo,
@ -408,3 +408,23 @@ func TestGetAccessTokenLookupsRedactJWT(t *testing.T) {
t.Fatalf("GetAccessTokenByID = %+v, want id tok-1 with redacted token", byID)
}
}
func (s *stubUserRepoForAuth) SetUserActive(context.Context, string, string, bool) (*types.User, error) {
panic("unexpected SetUserActive call")
}
func TestValidateTokenRejectsDisabledAccount(t *testing.T) {
tokenRepo := &stubAuthTokenRepo{tokens: map[string]*types.AuthToken{}}
svc := newAuthTestUserService(tokenRepo)
user := svc.userRepo.(*stubUserRepoForAuth).users["user-1"]
access := signTestJWT(jwt.MapClaims{"user_id": user.ID, "type": "access", "exp": time.Now().Add(time.Hour).Unix()})
tokenRepo.tokens[access] = &types.AuthToken{UserID: user.ID, Token: access, TokenType: "access_token"}
if _, _, err := svc.ValidateToken(context.Background(), access); err != nil {
t.Fatalf("active account rejected: %v", err)
}
user.IsActive = false
_, _, err := svc.ValidateToken(context.Background(), access)
if err == nil || err.Error() != "account is disabled" {
t.Fatalf("disabled account with unrevoked token: got %v", err)
}
}

View File

@ -1523,6 +1523,117 @@ func (h *SystemHandler) ListSystemAdmins(c *gin.Context) {
})
}
// ListAllUsersResponse is the paginated payload for the platform user list.
// Unlike the system-admin list there is no total COUNT; HasMore tells the UI
// whether a next page exists (derived by fetching limit+1 rows).
type ListAllUsersResponse struct {
Users []*types.UserInfo `json:"users"`
Offset int `json:"offset"`
Limit int `json:"limit"`
HasMore bool `json:"has_more"`
}
// ListUsers godoc
// @Summary List all platform users
// @Description Retrieve a paginated list of every user across tenants (SystemAdmin only).
// @Description Supports `offset` (default 0) and `limit` (default 50, max 200).
// @Description Password/hashes are never serialised — only the redacted UserInfo shape.
// @Tags System Admin
// @Produce json
// @Param offset query int false "Page offset" default(0)
// @Param limit query int false "Page size (max 200)" default(50)
// @Success 200 {object} ListAllUsersResponse "Users retrieved successfully"
// @Failure 403 {object} map[string]interface{} "Forbidden: not a system admin"
// @Router /system/admin/users [get]
func (h *SystemHandler) ListUsers(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
offset := 0
limit := 50
if v := c.Query("offset"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n >= 0 {
offset = n
}
}
if v := c.Query("limit"); v != "" {
if n, err := strconv.Atoi(v); err == nil && n > 0 {
limit = n
}
}
if limit > 200 {
limit = 200
}
users, hasMore, err := h.userSvc.ListAllUsers(ctx, offset, limit)
if err != nil {
logger.Errorf(ctx, "Error listing users: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to list users"})
return
}
infos := make([]*types.UserInfo, 0, len(users))
for _, u := range users {
infos = append(infos, u.ToUserInfo())
}
c.JSON(http.StatusOK, ListAllUsersResponse{
Users: infos,
Offset: offset,
Limit: limit,
HasMore: hasMore,
})
}
// SetUserStatusRequest toggles a user account enabled/disabled (SystemAdmin only).
type SetUserStatusRequest struct {
UserID string `json:"user_id" binding:"required"`
IsActive *bool `json:"is_active" binding:"required"`
}
// SetUserStatus godoc
// @Summary Enable or disable a user account
// @Description Disable revokes the target's active sessions immediately.
// @Description Self-disable and disabling the last active system administrator are rejected.
// @Tags System Admin
// @Accept json
// @Produce json
// @Param request body SetUserStatusRequest true "Account status request"
// @Success 200 {object} map[string]interface{} "Status updated"
// @Failure 400 {object} map[string]interface{} "Self-disable / last-admin guard"
// @Failure 404 {object} map[string]interface{} "User not found"
// @Router /system/admin/users/status [post]
func (h *SystemHandler) SetUserStatus(c *gin.Context) {
ctx := logger.CloneContext(c.Request.Context())
var req SetUserStatusRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"})
return
}
callerID, _ := types.UserIDFromContext(ctx)
user, err := h.userSvc.SetUserActive(ctx, strings.TrimSpace(req.UserID), callerID, *req.IsActive)
if err != nil {
switch {
case errors.Is(err, service.ErrUserNotFound):
c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
case errors.Is(err, service.ErrCannotDisableSelf),
errors.Is(err, service.ErrCannotDisableLastAdmin):
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
default:
logger.Errorf(ctx, "Error setting user status: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update user status"})
}
return
}
c.JSON(http.StatusOK, gin.H{
"message": "User status updated",
"user": user.ToUserInfo(),
"is_active": user.IsActive,
})
}
// ResetUserPasswordRequest defines the system-administrator password-reset
// payload. Email is intentionally the only user-facing identifier: the UI is
// an operator tool and emails are easier to verify than UUIDs. The password is

View File

@ -0,0 +1,100 @@
package handler
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
)
// listUsersService is a minimal fake UserService for the ListUsers handler.
type listUsersService struct {
interfaces.UserService
users []*types.User
hasMore bool
err error
gotOff int
gotLim int
}
func (s *listUsersService) ListAllUsers(_ context.Context, offset, limit int) ([]*types.User, bool, error) {
s.gotOff = offset
s.gotLim = limit
return s.users, s.hasMore, s.err
}
func listUsersRouter(h *SystemHandler) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.GET("/system/admin/users", h.ListUsers)
return r
}
func TestListUsers_RedactedAndPaginated(t *testing.T) {
users := []*types.User{
{ID: "u1", Username: "alice", Email: "alice@example.com", IsActive: true, IsSystemAdmin: true},
{ID: "u2", Username: "bob", Email: "bob@example.com", IsActive: true, IsSystemAdmin: false},
}
svc := &listUsersService{users: users, hasMore: true}
h := &SystemHandler{userSvc: svc}
r := listUsersRouter(h)
req := httptest.NewRequest(http.MethodGet, "/system/admin/users?offset=10&limit=50", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d body=%s", w.Code, w.Body.String())
}
var resp struct {
Users []map[string]any `json:"users"`
Offset int `json:"offset"`
Limit int `json:"limit"`
HasMore bool `json:"has_more"`
}
if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
t.Fatal(err)
}
if resp.Offset != 10 || resp.Limit != 50 || !resp.HasMore {
t.Fatalf("unexpected pagination meta: %+v", resp)
}
if len(resp.Users) != 2 {
t.Fatalf("expected 2 users, got %d", len(resp.Users))
}
for _, u := range resp.Users {
if _, ok := u["password"]; ok {
t.Fatalf("password leaked: %v", u)
}
if _, ok := u["Password"]; ok {
t.Fatalf("Password leaked: %v", u)
}
}
if svc.gotOff != 10 || svc.gotLim != 50 {
t.Fatalf("service got wrong args: off=%d lim=%d", svc.gotOff, svc.gotLim)
}
}
func TestListUsers_LimitCapped(t *testing.T) {
svc := &listUsersService{users: nil, hasMore: false}
h := &SystemHandler{userSvc: svc}
r := listUsersRouter(h)
req := httptest.NewRequest(http.MethodGet, "/system/admin/users?limit=9999", nil)
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200, got %d", w.Code)
}
if svc.gotLim != 200 {
t.Fatalf("expected limit capped to 200, got %d", svc.gotLim)
}
}

View File

@ -0,0 +1,123 @@
package handler
import (
"bytes"
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"github.com/Tencent/WeKnora/internal/application/repository"
"github.com/Tencent/WeKnora/internal/application/service"
"github.com/Tencent/WeKnora/internal/types"
"github.com/Tencent/WeKnora/internal/types/interfaces"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type setUserStatusService struct {
interfaces.UserService
returnUser *types.User
err error
gotID string
gotActor string
gotActive bool
}
func (s *setUserStatusService) SetUserActive(
_ context.Context, userID, actorID string, active bool,
) (*types.User, error) {
s.gotID, s.gotActor, s.gotActive = userID, actorID, active
return s.returnUser, s.err
}
func statusRouter(h *SystemHandler, actorID string) *gin.Engine {
gin.SetMode(gin.TestMode)
r := gin.New()
r.Use(func(c *gin.Context) {
ctx := context.WithValue(c.Request.Context(), types.UserIDContextKey, actorID)
c.Request = c.Request.WithContext(ctx)
c.Next()
})
r.POST("/system/admin/users/status", h.SetUserStatus)
return r
}
func TestSetUserStatus_Success(t *testing.T) {
svc := &setUserStatusService{returnUser: &types.User{ID: "u2", Username: "bob", IsActive: false}}
h := &SystemHandler{userSvc: svc}
r := statusRouter(h, "admin-1")
body, _ := json.Marshal(map[string]any{"user_id": "u2", "is_active": false})
req := httptest.NewRequest(http.MethodPost, "/system/admin/users/status", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusOK {
t.Fatalf("expected 200 got %d %s", w.Code, w.Body.String())
}
if svc.gotID != "u2" || svc.gotActor != "admin-1" || svc.gotActive {
t.Fatalf("wrong args: %+v", svc)
}
}
func TestSetUserStatus_GuardErrors400(t *testing.T) {
for _, sentinel := range []error{service.ErrCannotDisableSelf, service.ErrCannotDisableLastAdmin} {
svc := &setUserStatusService{err: sentinel}
h := &SystemHandler{userSvc: svc}
r := statusRouter(h, "admin-1")
body, _ := json.Marshal(map[string]any{"user_id": "x", "is_active": false})
req := httptest.NewRequest(http.MethodPost, "/system/admin/users/status", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusBadRequest {
t.Fatalf("%v: expected 400 got %d", sentinel, w.Code)
}
}
}
func TestSetUserStatus_NotFound404(t *testing.T) {
db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), "users.db")), &gorm.Config{})
require.NoError(t, err)
sqlDB, err := db.DB()
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, sqlDB.Close()) })
require.NoError(t, db.AutoMigrate(&types.User{}))
svc := service.NewUserService(nil, repository.NewUserRepository(db), nil, nil, nil, nil)
h := &SystemHandler{userSvc: svc}
r := statusRouter(h, "admin-1")
body, _ := json.Marshal(map[string]any{"user_id": "ghost", "is_active": true})
req := httptest.NewRequest(http.MethodPost, "/system/admin/users/status", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
if w.Code != http.StatusNotFound {
t.Fatalf("expected 404 got %d", w.Code)
}
}
func TestSetUserStatus_RequiresExplicitStatus(t *testing.T) {
for _, body := range []string{
`{"user_id":"u2"}`,
`{"user_id":"u2","is_active":null}`,
`{"user_id":"u2","is_active":"false"}`,
} {
t.Run(body, func(t *testing.T) {
svc := &setUserStatusService{}
r := statusRouter(&SystemHandler{userSvc: svc}, "admin-1")
req := httptest.NewRequest(http.MethodPost, "/system/admin/users/status", bytes.NewBufferString(body))
req.Header.Set("Content-Type", "application/json")
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
require.Equal(t, http.StatusBadRequest, w.Code)
require.Empty(t, svc.gotID, "invalid requests must not change account status")
})
}
}

View File

@ -298,6 +298,8 @@ func RegisterSystemAdminRoutes(
adminRoutes.POST("/promote", handler.PromoteUserToSystemAdmin)
adminRoutes.POST("/revoke", handler.RevokeSystemAdmin)
adminRoutes.GET("/list", handler.ListSystemAdmins)
adminRoutes.GET("/users", handler.ListUsers)
adminRoutes.POST("/users/status", handler.SetUserStatus)
adminRoutes.POST("/users/reset-password", handler.ResetUserPassword)
adminRoutes.POST("/users/create", handler.CreateSystemUser)
adminRoutes.GET("/api-keys", handler.ListPlatformAPIKeys)

View File

@ -31,7 +31,7 @@ type UserService interface {
GetUserByUsername(ctx context.Context, username string) (*types.User, error)
// GetUserByTenantID gets the first user (owner) of a tenant
GetUserByTenantID(ctx context.Context, tenantID uint64) (*types.User, error)
// UpdateUser updates user information
// UpdateUser updates user data without changing account status; use SetUserActive for that.
UpdateUser(ctx context.Context, user *types.User) error
// DeleteUser deletes a user
DeleteUser(ctx context.Context, id string) error
@ -84,6 +84,15 @@ type UserService interface {
GetCurrentUser(ctx context.Context) (*types.User, error)
// SearchUsers searches users by username or email
SearchUsers(ctx context.Context, query string, limit int) ([]*types.User, error)
// SetUserActive enables or disables a user account (SystemAdmin action).
// Disabling also revokes all of that user's outstanding tokens. The
// repository enforces self-disable and last-system-admin guards.
SetUserActive(ctx context.Context, userID, actorID string, active bool) (*types.User, error)
// ListAllUsers lists every platform user (across tenants) newest-first.
// Returns the page plus a has_more flag so the system-admin user-list UI
// can paginate without a second count query. The handler enforces the
// SystemAdmin gate, so the service does not duplicate it here.
ListAllUsers(ctx context.Context, offset, limit int) ([]*types.User, bool, error)
// ListSystemAdmins lists users with IsSystemAdmin=true.
// Returns the page of admins plus the total count (for pagination UI);
// callers pass offset/limit to page through results. Used by the
@ -120,8 +129,11 @@ type UserRepository interface {
GetUserByUsername(ctx context.Context, username string) (*types.User, error)
// GetUserByTenantID gets the first user (owner) of a tenant
GetUserByTenantID(ctx context.Context, tenantID uint64) (*types.User, error)
// UpdateUser updates a user
// UpdateUser updates user data without changing account status; use SetUserActive for that.
UpdateUser(ctx context.Context, user *types.User) error
// SetUserActive atomically changes status and revokes sessions on disable,
// preserving at least one active system administrator.
SetUserActive(ctx context.Context, userID, actorID string, active bool) (*types.User, error)
// DeleteUser deletes a user
DeleteUser(ctx context.Context, id string) error
// ListUsers lists users with pagination