diff --git a/docs/images/system-settings/registration-access.jpg b/docs/images/system-settings/registration-access.jpg new file mode 100644 index 00000000..24933520 Binary files /dev/null and b/docs/images/system-settings/registration-access.jpg differ diff --git a/docs/images/system-settings/user-management.jpg b/docs/images/system-settings/user-management.jpg new file mode 100644 index 00000000..9c061217 Binary files /dev/null and b/docs/images/system-settings/user-management.jpg differ diff --git a/frontend/src/api/system/index.ts b/frontend/src/api/system/index.ts index fa717354..4770652b 100644 --- a/frontend/src/api/system/index.ts +++ b/frontend/src/api/system/index.ts @@ -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 { + 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 { - // 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 { 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 { diff --git a/frontend/src/components/css/settings-table.less b/frontend/src/components/css/settings-table.less new file mode 100644 index 00000000..40cb8647 --- /dev/null +++ b/frontend/src/components/css/settings-table.less @@ -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; + } +} diff --git a/frontend/src/i18n/localeKeyAudit.ts b/frontend/src/i18n/localeKeyAudit.ts index ad6460cd..5e8a3a72 100644 --- a/frontend/src/i18n/localeKeyAudit.ts +++ b/frontend/src/i18n/localeKeyAudit.ts @@ -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.', diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index 3fbd8702..c40fc87f 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -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' }, diff --git a/frontend/src/i18n/locales/ja-JP.ts b/frontend/src/i18n/locales/ja-JP.ts index da5a17a9..c4842a7c 100644 --- a/frontend/src/i18n/locales/ja-JP.ts +++ b/frontend/src/i18n/locales/ja-JP.ts @@ -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: 'パスワードが一致しません' }, diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index fdb8a84c..ccccf24f 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -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: { diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index c00d7bbe..dc11022b 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -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: { diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 1056e9e2..6db8910b 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -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: { diff --git a/frontend/src/i18n/locales/zh-TW.ts b/frontend/src/i18n/locales/zh-TW.ts index 08b6b814..1f357776 100644 --- a/frontend/src/i18n/locales/zh-TW.ts +++ b/frontend/src/i18n/locales/zh-TW.ts @@ -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: { diff --git a/frontend/src/views/settings/TenantMembers.vue b/frontend/src/views/settings/TenantMembers.vue index fb106d06..21097dd9 100644 --- a/frontend/src/views/settings/TenantMembers.vue +++ b/frontend/src/views/settings/TenantMembers.vue @@ -1468,6 +1468,7 @@ watch( + diff --git a/frontend/src/views/system/systemAdminDialog.less b/frontend/src/views/system/systemAdminDialog.less index 11a9dd91..aa8d911f 100644 --- a/frontend/src/views/system/systemAdminDialog.less +++ b/frontend/src/views/system/systemAdminDialog.less @@ -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; diff --git a/frontend/src/views/system/userManagement.less b/frontend/src/views/system/userManagement.less new file mode 100644 index 00000000..ee591187 --- /dev/null +++ b/frontend/src/views/system/userManagement.less @@ -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; } +} diff --git a/internal/application/repository/user.go b/internal/application/repository/user.go index ba8081e2..f5ddc487 100644 --- a/internal/application/repository/user.go +++ b/internal/application/repository/user.go @@ -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 diff --git a/internal/application/repository/user_status_test.go b/internal/application/repository/user_status_test.go new file mode 100644 index 00000000..27e9d803 --- /dev/null +++ b/internal/application/repository/user_status_test.go @@ -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) + } + }) + }) + } +} diff --git a/internal/application/service/tenant_member_test.go b/internal/application/service/tenant_member_test.go index fafd285e..2c725ecd 100644 --- a/internal/application/service/tenant_member_test.go +++ b/internal/application/service/tenant_member_test.go @@ -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") +} diff --git a/internal/application/service/user.go b/internal/application/service/user.go index 1fd6e2be..e60d803c 100644 --- a/internal/application/service/user.go +++ b/internal/application/service/user.go @@ -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. diff --git a/internal/application/service/user_auth_token_test.go b/internal/application/service/user_auth_token_test.go index bcba68b2..10042fbe 100644 --- a/internal/application/service/user_auth_token_test.go +++ b/internal/application/service/user_auth_token_test.go @@ -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) + } +} diff --git a/internal/handler/system.go b/internal/handler/system.go index 40cabdc5..36340f51 100644 --- a/internal/handler/system.go +++ b/internal/handler/system.go @@ -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 diff --git a/internal/handler/system_user_list_test.go b/internal/handler/system_user_list_test.go new file mode 100644 index 00000000..0e98e3f6 --- /dev/null +++ b/internal/handler/system_user_list_test.go @@ -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) + } +} diff --git a/internal/handler/system_user_status_test.go b/internal/handler/system_user_status_test.go new file mode 100644 index 00000000..a14fd643 --- /dev/null +++ b/internal/handler/system_user_status_test.go @@ -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") + }) + } +} diff --git a/internal/router/routes_auth_tenant.go b/internal/router/routes_auth_tenant.go index d4b6ddc1..0af18671 100644 --- a/internal/router/routes_auth_tenant.go +++ b/internal/router/routes_auth_tenant.go @@ -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) diff --git a/internal/types/interfaces/user.go b/internal/types/interfaces/user.go index 263b82dc..bc6617f2 100644 --- a/internal/types/interfaces/user.go +++ b/internal/types/interfaces/user.go @@ -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