| 1 | use sqlx::PgPool; |
| 2 | use utopia_core::models::{Role, User, Workspace}; |
| 3 | use utopia_core::{AppError, AppResult}; |
| 4 | use uuid::Uuid; |
| 5 | |
| 6 | /// 注册(单租户模型): |
| 7 | /// - 部署内还没有组织 → 首个用户:创建组织 + 默认工作区,成为 owner + 系统管理员; |
| 8 | /// - 已有组织 → 加入该组织,并以 viewer 进入默认(最早的)工作区; |
| 9 | /// `open_registration = false` 时拒绝(仅引导首用户例外)。 |
| 10 | pub async fn register( |
| 11 | pool: &PgPool, |
| 12 | email: &str, |
| 13 | password_hash: &str, |
| 14 | display_name: &str, |
| 15 | org_name: Option<&str>, |
| 16 | open_registration: bool, |
| 17 | ) -> AppResult<(User, Workspace)> { |
| 18 | let mut tx = pool.begin().await?; |
| 19 | |
| 20 | let existing_org: Option<(Uuid,)> = |
| 21 | sqlx::query_as("SELECT id FROM organizations ORDER BY created_at LIMIT 1") |
| 22 | .fetch_optional(&mut *tx) |
| 23 | .await?; |
| 24 | |
| 25 | let result = match existing_org { |
| 26 | None => { |
| 27 | // 首个用户:引导整个部署 |
| 28 | let org_id = Uuid::now_v7(); |
| 29 | sqlx::query("INSERT INTO organizations (id, name) VALUES ($1, $2)") |
| 30 | .bind(org_id) |
| 31 | .bind(org_name.unwrap_or("Default Organization")) |
| 32 | .execute(&mut *tx) |
| 33 | .await?; |
| 34 | |
| 35 | let user = |
| 36 | insert_user(&mut tx, org_id, email, password_hash, display_name, true).await?; |
| 37 | |
| 38 | let workspace: Workspace = sqlx::query_as( |
| 39 | "INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, $3) RETURNING *", |
| 40 | ) |
| 41 | .bind(Uuid::now_v7()) |
| 42 | .bind(org_id) |
| 43 | .bind("Default Workspace") |
| 44 | .fetch_one(&mut *tx) |
| 45 | .await?; |
| 46 | |
| 47 | insert_membership(&mut tx, user.id, workspace.id, Role::Owner).await?; |
| 48 | insert_general_kb(&mut tx, workspace.id, user.id).await?; |
| 49 | (user, workspace) |
| 50 | } |
| 51 | Some((org_id,)) => { |
| 52 | if !open_registration { |
| 53 | return Err(AppError::invalid( |
| 54 | "registration_closed", |
| 55 | "Registration is closed for this deployment. Contact your administrator.", |
| 56 | )); |
| 57 | } |
| 58 | let user = |
| 59 | insert_user(&mut tx, org_id, email, password_hash, display_name, false).await?; |
| 60 | |
| 61 | // 加入默认(最早的)工作区;异常情况下组织没有工作区则补建一个 |
| 62 | let default_ws: Option<Workspace> = sqlx::query_as( |
| 63 | "SELECT * FROM workspaces WHERE org_id = $1 ORDER BY created_at LIMIT 1", |
| 64 | ) |
| 65 | .bind(org_id) |
| 66 | .fetch_optional(&mut *tx) |
| 67 | .await?; |
| 68 | |
| 69 | match default_ws { |
| 70 | Some(ws) => { |
| 71 | insert_membership(&mut tx, user.id, ws.id, Role::Viewer).await?; |
| 72 | (user, ws) |
| 73 | } |
| 74 | None => { |
| 75 | let ws: Workspace = sqlx::query_as( |
| 76 | "INSERT INTO workspaces (id, org_id, name) VALUES ($1, $2, $3) RETURNING *", |
| 77 | ) |
| 78 | .bind(Uuid::now_v7()) |
| 79 | .bind(org_id) |
| 80 | .bind("Default Workspace") |
| 81 | .fetch_one(&mut *tx) |
| 82 | .await?; |
| 83 | insert_membership(&mut tx, user.id, ws.id, Role::Owner).await?; |
| 84 | (user, ws) |
| 85 | } |
| 86 | } |
| 87 | } |
| 88 | }; |
| 89 | |
| 90 | tx.commit().await?; |
| 91 | Ok(result) |
| 92 | } |
| 93 | |
| 94 | async fn insert_user( |
| 95 | tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, |
| 96 | org_id: Uuid, |
| 97 | email: &str, |
| 98 | password_hash: &str, |
| 99 | display_name: &str, |
| 100 | is_admin: bool, |
| 101 | ) -> AppResult<User> { |
| 102 | sqlx::query_as( |
| 103 | "INSERT INTO users (id, org_id, email, password_hash, display_name, is_admin) |
| 104 | VALUES ($1, $2, $3, $4, $5, $6) RETURNING *", |
| 105 | ) |
| 106 | .bind(Uuid::now_v7()) |
| 107 | .bind(org_id) |
| 108 | .bind(email) |
| 109 | .bind(password_hash) |
| 110 | .bind(display_name) |
| 111 | .bind(is_admin) |
| 112 | .fetch_one(&mut **tx) |
| 113 | .await |
| 114 | .map_err(|e| match &e { |
| 115 | sqlx::Error::Database(db) if db.is_unique_violation() => { |
| 116 | AppError::Conflict("This email is already registered".into()) |
| 117 | } |
| 118 | _ => AppError::Db(e), |
| 119 | }) |
| 120 | } |
| 121 | |
| 122 | async fn insert_membership( |
| 123 | tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, |
| 124 | user_id: Uuid, |
| 125 | workspace_id: Uuid, |
| 126 | role: Role, |
| 127 | ) -> AppResult<()> { |
| 128 | sqlx::query("INSERT INTO memberships (user_id, workspace_id, role) VALUES ($1, $2, $3)") |
| 129 | .bind(user_id) |
| 130 | .bind(workspace_id) |
| 131 | .bind(role.as_str()) |
| 132 | .execute(&mut **tx) |
| 133 | .await?; |
| 134 | Ok(()) |
| 135 | } |
| 136 | |
| 137 | /// 部署的公共空间。首个用户注册即建,与组织和工作区同一个事务——不然新部署的 |
| 138 | /// 第一屏是个空壳:Graph 停在 Loading,切换器里无库可选,而"建第一个库"这件事 |
| 139 | /// 从没有人告诉过用户。 |
| 140 | /// |
| 141 | /// 名字是 General 而非 Public:可见性由 visibility 字段表达,名字再说一遍既冗余, |
| 142 | /// 又会让自部署用户误读成"公开到互联网"。is_default 让它永远 open、不可删 |
| 143 | /// (0012 的 CHECK 是 DB 级双保险)。 |
| 144 | async fn insert_general_kb( |
| 145 | tx: &mut sqlx::Transaction<'_, sqlx::Postgres>, |
| 146 | workspace_id: Uuid, |
| 147 | owner_id: Uuid, |
| 148 | ) -> AppResult<()> { |
| 149 | let kb_id = Uuid::now_v7(); |
| 150 | sqlx::query( |
| 151 | "INSERT INTO knowledge_bases |
| 152 | (id, workspace_id, name, kind, description, is_default, visibility) |
| 153 | VALUES ($1, $2, 'General', 'knowledge', $3, TRUE, 'open')", |
| 154 | ) |
| 155 | .bind(kb_id) |
| 156 | .bind(workspace_id) |
| 157 | .bind("Shared space for the whole deployment. Everyone can read it.") |
| 158 | .execute(&mut **tx) |
| 159 | .await?; |
| 160 | // 建库者记为本库 admin,与手动建库路径一致。首个用户本就是系统管理员、 |
| 161 | // 无需此行也进得来,但系统管理员身份日后可以撤销,本库权限不该随之蒸发。 |
| 162 | sqlx::query( |
| 163 | "INSERT INTO kb_members (kb_id, user_id, role, added_by) |
| 164 | VALUES ($1, $2, 'admin', $2)", |
| 165 | ) |
| 166 | .bind(kb_id) |
| 167 | .bind(owner_id) |
| 168 | .execute(&mut **tx) |
| 169 | .await?; |
| 170 | Ok(()) |
| 171 | } |
| 172 | |
| 173 | /// 管理员代开账号:加入既有组织 + 默认工作区,部署角色由管理员指定。 |
| 174 | pub async fn admin_create_user( |
| 175 | pool: &PgPool, |
| 176 | email: &str, |
| 177 | password_hash: &str, |
| 178 | display_name: &str, |
| 179 | role: Role, |
| 180 | ) -> AppResult<User> { |
| 181 | let mut tx = pool.begin().await?; |
| 182 | let (org_id,): (Uuid,) = |
| 183 | sqlx::query_as("SELECT id FROM organizations ORDER BY created_at LIMIT 1") |
| 184 | .fetch_optional(&mut *tx) |
| 185 | .await? |
| 186 | .ok_or_else(|| AppError::Validation("Deployment not bootstrapped yet".into()))?; |
| 187 | let user = insert_user(&mut tx, org_id, email, password_hash, display_name, false).await?; |
| 188 | let ws: Option<(Uuid,)> = |
| 189 | sqlx::query_as("SELECT id FROM workspaces WHERE org_id = $1 ORDER BY created_at LIMIT 1") |
| 190 | .bind(org_id) |
| 191 | .fetch_optional(&mut *tx) |
| 192 | .await?; |
| 193 | if let Some((ws_id,)) = ws { |
| 194 | insert_membership(&mut tx, user.id, ws_id, role).await?; |
| 195 | } |
| 196 | tx.commit().await?; |
| 197 | Ok(user) |
| 198 | } |
| 199 | |
| 200 | /// 按 email 找账号——**只找在职的**。 |
| 201 | /// |
| 202 | /// 这一句 `deactivated_at IS NULL` 同时管两件事:停用的人登不进来,以及 |
| 203 | /// 「一个 email 在停用账号里可能重复」时不会随机返回其中一条(唯一索引 |
| 204 | /// 现在是部分的,只约束在职账号,见 `users.deactivated_at`)。 |
| 205 | pub async fn find_user_by_email(pool: &PgPool, email: &str) -> AppResult<Option<User>> { |
| 206 | let user = sqlx::query_as("SELECT * FROM users WHERE email = $1 AND deactivated_at IS NULL") |
| 207 | .bind(email) |
| 208 | .fetch_optional(pool) |
| 209 | .await?; |
| 210 | Ok(user) |
| 211 | } |
| 212 | |
| 213 | /// 按 id 找账号——**只找在职的**。 |
| 214 | /// |
| 215 | /// 会话校验走这里,所以停用**立即生效**,不必等 token 过期:已经签发出去的 |
| 216 | /// token 下一次请求就查不到人。这是软删除唯一必须挡住的路径,其余读 users 的 |
| 217 | /// 地方(审计、合并日志、改类账本)**要照旧查得到**——事情是他做的,人停用了 |
| 218 | /// 不等于那件事没发生。 |
| 219 | pub async fn find_user_by_id(pool: &PgPool, id: Uuid) -> AppResult<Option<User>> { |
| 220 | let user = sqlx::query_as("SELECT * FROM users WHERE id = $1 AND deactivated_at IS NULL") |
| 221 | .bind(id) |
| 222 | .fetch_optional(pool) |
| 223 | .await?; |
| 224 | Ok(user) |
| 225 | } |
| 226 | |
| 227 | /// 改显示名(个人资料页)。 |
| 228 | pub async fn update_display_name(pool: &PgPool, id: Uuid, display_name: &str) -> AppResult<User> { |
| 229 | sqlx::query_as("UPDATE users SET display_name = $2 WHERE id = $1 RETURNING *") |
| 230 | .bind(id) |
| 231 | .bind(display_name) |
| 232 | .fetch_optional(pool) |
| 233 | .await? |
| 234 | .ok_or(AppError::NotFound) |
| 235 | } |
| 236 | |
| 237 | /// 改密码(server 层已验旧密并完成哈希)。 |
| 238 | pub async fn update_password(pool: &PgPool, id: Uuid, password_hash: &str) -> AppResult<()> { |
| 239 | sqlx::query("UPDATE users SET password_hash = $2 WHERE id = $1") |
| 240 | .bind(id) |
| 241 | .bind(password_hash) |
| 242 | .execute(pool) |
| 243 | .await?; |
| 244 | Ok(()) |
| 245 | } |
| 246 | |
| 247 | /// 停用一个账号(软删除,见 `users.deactivated_at`)。 |
| 248 | /// |
| 249 | /// **不删行。** 审计事件、合并日志、改类账本、口径确认的 `actor_id` 都指着这个人, |
| 250 | /// 而那些是审计材料——人走了仍然要能回答「当时是谁做的」。停用只断访问。 |
| 251 | /// |
| 252 | /// **不能停用自己**:管理员把自己停掉之后就没人能把他放回来了(这个系统没有 |
| 253 | /// 「超级管理员」这一层)。挡在这里而不是只挡在界面上——界面挡得住误点, |
| 254 | /// 挡不住直接调接口。 |
| 255 | /// |
| 256 | /// **最后一个管理员不能停用**:否则这个组织从此没人能管成员。同样的理由。 |
| 257 | pub async fn deactivate_user(pool: &PgPool, target: Uuid, actor: Uuid) -> AppResult<()> { |
| 258 | if target == actor { |
| 259 | return Err(AppError::Validation("不能停用自己的账号".into())); |
| 260 | } |
| 261 | let mut tx = pool.begin().await?; |
| 262 | let victim: Option<(bool, Uuid, Option<chrono::DateTime<chrono::Utc>>)> = |
| 263 | sqlx::query_as("SELECT is_admin, org_id, deactivated_at FROM users WHERE id = $1") |
| 264 | .bind(target) |
| 265 | .fetch_optional(&mut *tx) |
| 266 | .await?; |
| 267 | let Some((is_admin, org_id, already)) = victim else { |
| 268 | tx.rollback().await?; |
| 269 | return Err(AppError::NotFound); |
| 270 | }; |
| 271 | if already.is_some() { |
| 272 | // 幂等:重复停用不是错误,也不该把 deactivated_by 改成第二个人 |
| 273 | tx.rollback().await?; |
| 274 | return Ok(()); |
| 275 | } |
| 276 | if is_admin { |
| 277 | let (others,): (i64,) = sqlx::query_as( |
| 278 | "SELECT count(*) FROM users |
| 279 | WHERE org_id = $1 AND is_admin AND deactivated_at IS NULL AND id <> $2", |
| 280 | ) |
| 281 | .bind(org_id) |
| 282 | .bind(target) |
| 283 | .fetch_one(&mut *tx) |
| 284 | .await?; |
| 285 | if others == 0 { |
| 286 | tx.rollback().await?; |
| 287 | return Err(AppError::Validation( |
| 288 | "这是组织里最后一个管理员,停用之后没人能管成员".into(), |
| 289 | )); |
| 290 | } |
| 291 | } |
| 292 | sqlx::query("UPDATE users SET deactivated_at = now(), deactivated_by = $2 WHERE id = $1") |
| 293 | .bind(target) |
| 294 | .bind(actor) |
| 295 | .execute(&mut *tx) |
| 296 | .await?; |
| 297 | tx.commit().await?; |
| 298 | Ok(()) |
| 299 | } |
| 300 | |
| 301 | /// 把停用的账号放回来。 |
| 302 | /// |
| 303 | /// **可能失败,而且失败得有道理**:停用期间有人用同一个 email 建了新账号, |
| 304 | /// 那个部分唯一索引会挡住这次恢复。这时该做的是让管理员看见冲突,而不是 |
| 305 | /// 悄悄让两个在职账号共用一个 email。 |
| 306 | pub async fn reactivate_user(pool: &PgPool, target: Uuid) -> AppResult<()> { |
| 307 | let res = sqlx::query( |
| 308 | "UPDATE users SET deactivated_at = NULL, deactivated_by = NULL |
| 309 | WHERE id = $1 AND deactivated_at IS NOT NULL", |
| 310 | ) |
| 311 | .bind(target) |
| 312 | .execute(pool) |
| 313 | .await?; |
| 314 | if res.rows_affected() == 0 { |
| 315 | return Err(AppError::NotFound); |
| 316 | } |
| 317 | Ok(()) |
| 318 | } |