Skip to content

World's first open-source enterprise world model.

An admin can retire an account without erasing what that person did (#129)

WaylandYangfeaef9b87ba6
diff --git a/crates/utopia-server/src/api/admin_routes.rs b/crates/utopia-server/src/api/admin_routes.rs
index 5979e312..ce5622d3 100644
--- a/crates/utopia-server/src/api/admin_routes.rs
+++ b/crates/utopia-server/src/api/admin_routes.rs
@@ -1,6 +1,6 @@
//! 系统管理 API(仅系统管理员):部署配置 + 代开账号。
-use axum::extract::State;
+use axum::extract::{Path, State};
use axum::Json;
use serde::Deserialize;
use serde_json::json;
@@ -10,6 +10,7 @@ use utopia_core::AppError;
use crate::auth::{self, AuthUser};
use crate::error::ApiResult;
use crate::state::AppState;
+use uuid::Uuid;
fn require_admin(user: &User) -> Result<(), AppError> {
if user.is_admin {
@@ -143,3 +144,57 @@ pub async fn create_user(
.await?;
Ok(Json(json!({ "user": created })))
}
+
+/// 停用一个账号(软删除,见迁移 0056)。
+///
+/// **不是 DELETE。** 审计事件、合并日志、改类账本、口径确认的 `actor_id` 都指着
+/// 这个人,那些是审计材料——人走了仍然要能回答「当时是谁做的」。停用只断访问:
+/// 登录查不到人,已签发的 token 下一次请求也查不到(会话校验走同一个函数),
+/// 成员列表里不再出现,而所有归因照旧。
+///
+/// 两条护栏在 store 层而不是这里:不能停用自己、不能停用最后一个管理员。
+/// 放在下面是因为界面挡得住误点,挡不住直接调接口。
+pub async fn deactivate_user(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(target): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ utopia_store::accounts::deactivate_user(&state.pool, target, user.id).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ None,
+ user.id,
+ "user.deactivated",
+ "user",
+ Some(target),
+ serde_json::json!({}),
+ )
+ .await;
+ Ok(Json(serde_json::json!({ "ok": true })))
+}
+
+/// 把停用的账号放回来。
+///
+/// **可能失败**:停用期间有人用同一个 email 建了新账号,那个部分唯一索引
+/// (`users_email_active_idx`)会挡住恢复。让管理员看见冲突,好过悄悄让两个
+/// 在职账号共用一个 email。
+pub async fn reactivate_user(
+ State(state): State<AppState>,
+ AuthUser(user): AuthUser,
+ Path(target): Path<Uuid>,
+) -> ApiResult<Json<serde_json::Value>> {
+ require_admin(&user)?;
+ utopia_store::accounts::reactivate_user(&state.pool, target).await?;
+ let _ = utopia_store::audit::record(
+ &state.pool,
+ None,
+ user.id,
+ "user.reactivated",
+ "user",
+ Some(target),
+ serde_json::json!({}),
+ )
+ .await;
+ Ok(Json(serde_json::json!({ "ok": true })))
+}
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index 16c3784e..2087f885 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -89,6 +89,13 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
get(admin_routes::get_deployment).put(admin_routes::put_deployment),
)
.route("/admin/users", post(admin_routes::create_user))
+ // 停用 / 恢复账号(0056)。DELETE 的语义是「这个人不再有访问权」,
+ // 而不是「这一行没了」——归因照旧查得到
+ .route(
+ "/admin/users/{id}",
+ axum::routing::delete(admin_routes::deactivate_user)
+ .post(admin_routes::reactivate_user),
+ )
.route(
"/admin/data-sources",
get(datasource_routes::list).post(datasource_routes::create),
diff --git a/crates/utopia-store/src/access.rs b/crates/utopia-store/src/access.rs
index e8bb1de0..5e3af9f1 100644
--- a/crates/utopia-store/src/access.rs
+++ b/crates/utopia-store/src/access.rs
@@ -102,7 +102,8 @@ pub async fn kb_members(pool: &PgPool, kb_id: Uuid) -> AppResult<Vec<KbMemberVie
let rows: Vec<KbMemberView> = sqlx::query_as(
"SELECT m.user_id, u.email, u.display_name, m.role
FROM kb_members m JOIN users u ON u.id = m.user_id
- WHERE m.kb_id = $1 ORDER BY u.display_name",
+ -- 停用的人不出现在成员列表里(0056);成员关系那一行留着
+ WHERE m.kb_id = $1 AND u.deactivated_at IS NULL ORDER BY u.display_name",
)
.bind(kb_id)
.fetch_all(pool)
diff --git a/crates/utopia-store/src/accounts.rs b/crates/utopia-store/src/accounts.rs
index 0eb1bafb..d1629023 100644
--- a/crates/utopia-store/src/accounts.rs
+++ b/crates/utopia-store/src/accounts.rs
@@ -197,16 +197,27 @@ pub async fn admin_create_user(
Ok(user)
}
+/// 按 email 找账号——**只找在职的**。
+///
+/// 这一句 `deactivated_at IS NULL` 同时管两件事:停用的人登不进来,以及
+/// 「一个 email 在停用账号里可能重复」时不会随机返回其中一条(唯一索引
+/// 现在是部分的,只约束在职账号,见迁移 0056)。
pub async fn find_user_by_email(pool: &PgPool, email: &str) -> AppResult<Option<User>> {
- let user = sqlx::query_as("SELECT * FROM users WHERE email = $1")
+ let user = sqlx::query_as("SELECT * FROM users WHERE email = $1 AND deactivated_at IS NULL")
.bind(email)
.fetch_optional(pool)
.await?;
Ok(user)
}
+/// 按 id 找账号——**只找在职的**。
+///
+/// 会话校验走这里,所以停用**立即生效**,不必等 token 过期:已经签发出去的
+/// token 下一次请求就查不到人。这是软删除唯一必须挡住的路径,其余读 users 的
+/// 地方(审计、合并日志、改类账本)**要照旧查得到**——事情是他做的,人停用了
+/// 不等于那件事没发生。
pub async fn find_user_by_id(pool: &PgPool, id: Uuid) -> AppResult<Option<User>> {
- let user = sqlx::query_as("SELECT * FROM users WHERE id = $1")
+ let user = sqlx::query_as("SELECT * FROM users WHERE id = $1 AND deactivated_at IS NULL")
.bind(id)
.fetch_optional(pool)
.await?;
@@ -232,3 +243,76 @@ pub async fn update_password(pool: &PgPool, id: Uuid, password_hash: &str) -> Ap
.await?;
Ok(())
}
+
+/// 停用一个账号(软删除,见迁移 0056)。
+///
+/// **不删行。** 审计事件、合并日志、改类账本、口径确认的 `actor_id` 都指着这个人,
+/// 而那些是审计材料——人走了仍然要能回答「当时是谁做的」。停用只断访问。
+///
+/// **不能停用自己**:管理员把自己停掉之后就没人能把他放回来了(这个系统没有
+/// 「超级管理员」这一层)。挡在这里而不是只挡在界面上——界面挡得住误点,
+/// 挡不住直接调接口。
+///
+/// **最后一个管理员不能停用**:否则这个组织从此没人能管成员。同样的理由。
+pub async fn deactivate_user(pool: &PgPool, target: Uuid, actor: Uuid) -> AppResult<()> {
+ if target == actor {
+ return Err(AppError::Validation("不能停用自己的账号".into()));
+ }
+ let mut tx = pool.begin().await?;
+ let victim: Option<(bool, Uuid, Option<chrono::DateTime<chrono::Utc>>)> =
+ sqlx::query_as("SELECT is_admin, org_id, deactivated_at FROM users WHERE id = $1")
+ .bind(target)
+ .fetch_optional(&mut *tx)
+ .await?;
+ let Some((is_admin, org_id, already)) = victim else {
+ tx.rollback().await?;
+ return Err(AppError::NotFound);
+ };
+ if already.is_some() {
+ // 幂等:重复停用不是错误,也不该把 deactivated_by 改成第二个人
+ tx.rollback().await?;
+ return Ok(());
+ }
+ if is_admin {
+ let (others,): (i64,) = sqlx::query_as(
+ "SELECT count(*) FROM users
+ WHERE org_id = $1 AND is_admin AND deactivated_at IS NULL AND id <> $2",
+ )
+ .bind(org_id)
+ .bind(target)
+ .fetch_one(&mut *tx)
+ .await?;
+ if others == 0 {
+ tx.rollback().await?;
+ return Err(AppError::Validation(
+ "这是组织里最后一个管理员,停用之后没人能管成员".into(),
+ ));
+ }
+ }
+ sqlx::query("UPDATE users SET deactivated_at = now(), deactivated_by = $2 WHERE id = $1")
+ .bind(target)
+ .bind(actor)
+ .execute(&mut *tx)
+ .await?;
+ tx.commit().await?;
+ Ok(())
+}
+
+/// 把停用的账号放回来。
+///
+/// **可能失败,而且失败得有道理**:停用期间有人用同一个 email 建了新账号,
+/// 那个部分唯一索引会挡住这次恢复。这时该做的是让管理员看见冲突,而不是
+/// 悄悄让两个在职账号共用一个 email。
+pub async fn reactivate_user(pool: &PgPool, target: Uuid) -> AppResult<()> {
+ let res = sqlx::query(
+ "UPDATE users SET deactivated_at = NULL, deactivated_by = NULL
+ WHERE id = $1 AND deactivated_at IS NOT NULL",
+ )
+ .bind(target)
+ .execute(pool)
+ .await?;
+ if res.rows_affected() == 0 {
+ return Err(AppError::NotFound);
+ }
+ Ok(())
+}
diff --git a/crates/utopia-store/src/members.rs b/crates/utopia-store/src/members.rs
index 2a821c02..09404160 100644
--- a/crates/utopia-store/src/members.rs
+++ b/crates/utopia-store/src/members.rs
@@ -7,7 +7,9 @@ pub async fn list(pool: &PgPool, workspace_id: Uuid) -> AppResult<Vec<MemberView
let rows = sqlx::query_as(
"SELECT m.user_id, u.email, u.display_name, m.role, u.is_admin
FROM memberships m JOIN users u ON u.id = m.user_id
- WHERE m.workspace_id = $1
+ -- 停用的人不再出现在成员列表里(0056)。成员关系那一行留着——
+ -- 恢复账号时不必重新加回每一个工作区
+ WHERE m.workspace_id = $1 AND u.deactivated_at IS NULL
ORDER BY m.created_at",
)
.bind(workspace_id)
@@ -20,7 +22,7 @@ pub async fn list(pool: &PgPool, workspace_id: Uuid) -> AppResult<Vec<MemberView
pub async fn org_users(pool: &PgPool, org_id: Uuid) -> AppResult<Vec<OrgUser>> {
let rows = sqlx::query_as(
"SELECT id, email, display_name, is_admin FROM users
- WHERE org_id = $1 ORDER BY created_at",
+ WHERE org_id = $1 AND deactivated_at IS NULL ORDER BY created_at",
)
.bind(org_id)
.fetch_all(pool)
@@ -53,11 +55,14 @@ pub async fn set_role(
user_id: Uuid,
role: Role,
) -> AppResult<()> {
- // 目标用户必须存在于本组织
- let exists: Option<(Uuid,)> = sqlx::query_as("SELECT id FROM users WHERE id = $1")
- .bind(user_id)
- .fetch_optional(pool)
- .await?;
+ // 目标用户必须存在于本组织,**而且在职**——否则能把一个已停用的账号
+ // 加进工作区,它在成员列表里又看不见(那条查询过滤了停用的),
+ // 于是成了一条谁也发现不了的授权
+ let exists: Option<(Uuid,)> =
+ sqlx::query_as("SELECT id FROM users WHERE id = $1 AND deactivated_at IS NULL")
+ .bind(user_id)
+ .fetch_optional(pool)
+ .await?;
if exists.is_none() {
return Err(AppError::NotFound);
}
diff --git a/crates/utopia-store/tests/a_retired_account.rs b/crates/utopia-store/tests/a_retired_account.rs
new file mode 100644
index 00000000..7bc2c911
--- /dev/null
+++ b/crates/utopia-store/tests/a_retired_account.rs
@@ -0,0 +1,134 @@
+//! 停用账号的四条硬性质——打在真库上(见迁移 0056)。
+//!
+//! 软删除的风险全在「漏过滤一处」:只要有一条读 `users` 的路径忘了带
+//! `deactivated_at IS NULL`,停用就成了摆设,而且**不会有任何报错**。
+//! 所以这几条守的不是函数,是**路径**。
+//!
+//! 反过来,归因那几处必须**照旧查得到**:审计事件、合并日志、改类账本的
+//! `actor_id` 指着这个人,而那些是审计材料——人走了不等于那件事没发生。
+
+use sqlx::PgPool;
+use uuid::Uuid;
+
+async fn org_with_two_admins(pool: &PgPool) -> anyhow::Result<(Uuid, Uuid, Uuid)> {
+ let (org, a, b) = (Uuid::now_v7(), Uuid::now_v7(), Uuid::now_v7());
+ sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, 'retire-test')")
+ .bind(org)
+ .execute(pool)
+ .await?;
+ for (id, mail) in [(a, "a"), (b, "b")] {
+ sqlx::query(
+ "INSERT INTO users (id, org_id, email, display_name, password_hash, is_admin)
+ VALUES ($1, $2, $3, 'u', 'x', TRUE)",
+ )
+ .bind(id)
+ .bind(org)
+ .bind(format!("{}-{mail}@retire.test", id.simple()))
+ .execute(pool)
+ .await?;
+ }
+ Ok((org, a, b))
+}
+
+#[tokio::test]
+async fn a_retired_account_cannot_get_back_in() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let (org, a, b) = org_with_two_admins(&pool).await?;
+
+ let run = async {
+ let email: String = sqlx::query_scalar("SELECT email FROM users WHERE id = $1")
+ .bind(b)
+ .fetch_one(&pool)
+ .await?;
+ assert!(
+ utopia_store::accounts::find_user_by_email(&pool, &email)
+ .await?
+ .is_some(),
+ "停用前该找得到"
+ );
+
+ utopia_store::accounts::deactivate_user(&pool, b, a).await?;
+
+ // 登录这条路
+ assert!(
+ utopia_store::accounts::find_user_by_email(&pool, &email)
+ .await?
+ .is_none(),
+ "停用的账号还能按 email 找到——登录挡不住"
+ );
+ // **已经签发出去的 token 那条路**。会话校验走 find_user_by_id,
+ // 所以停用立即生效,不必等 token 过期
+ assert!(
+ utopia_store::accounts::find_user_by_id(&pool, b)
+ .await?
+ .is_none(),
+ "停用的账号还能按 id 找到——已签发的 token 仍然有效"
+ );
+
+ // 归因照旧:那一行还在,只是打了时间戳
+ let still_there: i64 = sqlx::query_scalar("SELECT count(*) FROM users WHERE id = $1")
+ .bind(b)
+ .fetch_one(&pool)
+ .await?;
+ assert_eq!(still_there, 1, "软删除不该把行删掉——审计要靠它");
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ run
+}
+
+#[tokio::test]
+async fn the_last_admin_and_oneself_are_protected() -> anyhow::Result<()> {
+ let Ok(url) = std::env::var("UTOPIA_DATABASE_URL") else {
+ eprintln!("跳过:未设 UTOPIA_DATABASE_URL");
+ return Ok(());
+ };
+ let pool = PgPool::connect(&url).await?;
+ let (org, a, b) = org_with_two_admins(&pool).await?;
+
+ let run = async {
+ assert!(
+ utopia_store::accounts::deactivate_user(&pool, a, a)
+ .await
+ .is_err(),
+ "不能停用自己——这个系统没有超级管理员那一层,停完就没人能放回来"
+ );
+
+ utopia_store::accounts::deactivate_user(&pool, b, a).await?;
+ assert!(
+ utopia_store::accounts::deactivate_user(&pool, a, b)
+ .await
+ .is_err(),
+ "最后一个管理员不能停用,否则组织从此没人能管成员"
+ );
+
+ // 幂等:重复停用不是错误
+ utopia_store::accounts::deactivate_user(&pool, b, a).await?;
+
+ // 恢复之后一切照旧
+ utopia_store::accounts::reactivate_user(&pool, b).await?;
+ assert!(
+ utopia_store::accounts::find_user_by_id(&pool, b)
+ .await?
+ .is_some(),
+ "恢复之后该能登录了"
+ );
+ Ok::<_, anyhow::Error>(())
+ }
+ .await;
+
+ sqlx::query("DELETE FROM organizations WHERE id = $1")
+ .bind(org)
+ .execute(&pool)
+ .await?;
+ run
+}
diff --git a/migrations/0056_users_can_be_retired.sql b/migrations/0056_users_can_be_retired.sql
new file mode 100644
index 00000000..46ee6213
--- /dev/null
+++ b/migrations/0056_users_can_be_retired.sql
@@ -0,0 +1,24 @@
+-- 管理员可以停用一个账号。**软删除,不是 DELETE。**
+--
+-- 硬删删不掉:审计事件、合并日志、改类账本、口径确认——它们的 `actor_id`
+-- 指着这个人,而那些记录是审计材料,人走了仍然要能回答「当时是谁做的」。
+-- 真去 DELETE 只有两个结果:要么被外键挡住(那些列是裸外键),要么级联把
+-- 审计一起删掉。两个都不是我们要的。
+--
+-- 所以停用 = 打一个时间戳。**归因保住,访问断掉**。
+ALTER TABLE users ADD COLUMN deactivated_at TIMESTAMPTZ;
+
+-- 谁停的。同样是裸外键——停用者自己也可能被停用,而那条记录还得在
+ALTER TABLE users ADD COLUMN deactivated_by UUID REFERENCES users(id);
+
+-- **唯一的 email 约束要放停用的账号一马。**
+--
+-- 从前 email 是全表唯一。停用之后那个地址还占着位置,于是同一个人回来、
+-- 或者同一个邮箱转给别人,都建不了新账号——而「停用」不该等于「这个邮箱
+-- 永久报废」。改成部分唯一索引:只约束在职的。
+--
+-- 代价写在前面:停用过的账号里可以有重复 email,`find_user_by_email`
+-- 因此必须带 `deactivated_at IS NULL`——它本来就要带(不然停用的人还能登录),
+-- 这里只是让那一句同时也是正确性的保证,而不只是权限的。
+ALTER TABLE users DROP CONSTRAINT IF EXISTS users_email_key;
+CREATE UNIQUE INDEX users_email_active_idx ON users (email) WHERE deactivated_at IS NULL;
diff --git a/web/src/api.ts b/web/src/api.ts
index e4a4391e..f8e7e631 100644
--- a/web/src/api.ts
+++ b/web/src/api.ts
@@ -789,6 +789,11 @@ export const api = {
body: JSON.stringify(body),
}),
+ /** 停用一个账号(软删除)。归因照旧查得到——审计、合并日志、改类账本都靠它 */
+ adminDeactivateUser: (userId: string) =>
+ request<{ ok: boolean }>(`/api/v1/admin/users/${userId}`, {
+ method: "DELETE",
+ }),
adminDataSources: () =>
request<{ data_sources: DataSourceView[] }>("/api/v1/admin/data-sources"),
adminCreateDataSource: (body: { name: string; conn_string: string }) =>
diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts
index 4d0fcf89..523b2859 100644
--- a/web/src/i18n/en.ts
+++ b/web/src/i18n/en.ts
@@ -1068,6 +1068,11 @@ export const en = {
title: "Deployment users",
systemAdmin: "System admin",
remove: "Remove",
+ deactivate: "Deactivate",
+ deactivateHint:
+ "Cuts off access everywhere — sign-in and any token already issued. What they did stays attributed to them.",
+ deactivateConfirm: (name: string) =>
+ `Deactivate ${name}? They lose access everywhere. Their past decisions stay on record.`,
pickUser: "Select a user to add…",
add: "Add",
roles: {
diff --git a/web/src/i18n/zh.ts b/web/src/i18n/zh.ts
index 244dcfc8..8d769f0b 100644
--- a/web/src/i18n/zh.ts
+++ b/web/src/i18n/zh.ts
@@ -957,6 +957,11 @@ export const zh: Strings = {
title: "部署用户",
systemAdmin: "系统管理员",
remove: "移除",
+ deactivate: "停用账号",
+ deactivateHint:
+ "断掉整个系统的访问——登录与已签发的 token 都失效。他做过的事仍然记在他名下。",
+ deactivateConfirm: (name: string) =>
+ `停用 ${name}?他将无法再登录任何地方,但过往的决定仍然留痕。`,
pickUser: "选择要添加的用户…",
add: "添加",
roles: {
diff --git a/web/src/pages/Members.tsx b/web/src/pages/Members.tsx
index 4c855143..42b3a88c 100644
--- a/web/src/pages/Members.tsx
+++ b/web/src/pages/Members.tsx
@@ -40,6 +40,11 @@ export function Members({ workspaceId }: { workspaceId: string }) {
onSuccess: refresh,
onError,
});
+ const deactivate = useMutation({
+ mutationFn: (userId: string) => api.adminDeactivateUser(userId),
+ onSuccess: refresh,
+ onError,
+ });
const memberIds = new Set(members.data?.map((m) => m.user_id));
const addable = orgUsers.data?.filter((u) => !memberIds.has(u.id)) ?? [];
@@ -91,13 +96,28 @@ export function Members({ workspaceId }: { workspaceId: string }) {
options={ROLE_OPTIONS}
/>
</td>
- <td className="py-2 text-right">
+ <td className="py-2 text-right whitespace-nowrap">
<button
onClick={() => remove.mutate(m.user_id)}
className="text-xs text-neutral-500 hover:text-rose-400"
>
{S.members.remove}
</button>
+ {/* 停用账号跟「移出工作区」是两件事:前者断掉整个系统的访问,
+ 后者只是这个工作区不再有他。所以分开两个按钮,而且停用
+ 只给管理员看——它的影响面大得多 */}
+ {me.data?.is_admin && me.data.id !== m.user_id && (
+ <button
+ onClick={() => {
+ if (confirm(S.members.deactivateConfirm(m.display_name)))
+ deactivate.mutate(m.user_id);
+ }}
+ className="ml-3 text-xs text-neutral-600 hover:text-rose-400"
+ title={S.members.deactivateHint}
+ >
+ {S.members.deactivate}
+ </button>
+ )}
</td>
</tr>
))}