| 1 | use axum::extract::State; |
| 2 | use axum::http::HeaderMap; |
| 3 | use axum::Json; |
| 4 | use axum_extra::extract::cookie::CookieJar; |
| 5 | use serde::Deserialize; |
| 6 | use serde_json::json; |
| 7 | use utopia_core::models::{User, Workspace}; |
| 8 | use utopia_core::AppError; |
| 9 | |
| 10 | use crate::auth::{self, AuthUser}; |
| 11 | use crate::error::ApiResult; |
| 12 | use crate::state::AppState; |
| 13 | |
| 14 | #[derive(Deserialize)] |
| 15 | pub struct RegisterReq { |
| 16 | pub email: String, |
| 17 | pub password: String, |
| 18 | pub display_name: String, |
| 19 | pub org_name: Option<String>, |
| 20 | } |
| 21 | |
| 22 | #[derive(Deserialize)] |
| 23 | pub struct LoginReq { |
| 24 | pub email: String, |
| 25 | pub password: String, |
| 26 | } |
| 27 | |
| 28 | fn validate_register(req: &RegisterReq) -> Result<(), AppError> { |
| 29 | if !req.email.contains('@') || req.email.len() > 254 { |
| 30 | return Err(AppError::invalid("bad_email", "Invalid email address")); |
| 31 | } |
| 32 | if req.password.chars().count() < 8 { |
| 33 | return Err(AppError::invalid( |
| 34 | "password_too_short", |
| 35 | "Password must be at least 8 characters", |
| 36 | )); |
| 37 | } |
| 38 | if req.display_name.trim().is_empty() || req.display_name.chars().count() > 64 { |
| 39 | return Err(AppError::invalid( |
| 40 | "bad_display_name", |
| 41 | "Display name must be 1-64 characters", |
| 42 | )); |
| 43 | } |
| 44 | Ok(()) |
| 45 | } |
| 46 | |
| 47 | pub async fn register( |
| 48 | State(state): State<AppState>, |
| 49 | headers: HeaderMap, |
| 50 | jar: CookieJar, |
| 51 | Json(req): Json<RegisterReq>, |
| 52 | ) -> ApiResult<(CookieJar, Json<serde_json::Value>)> { |
| 53 | validate_register(&req)?; |
| 54 | let hash = auth::hash_password(&req.password)?; |
| 55 | let org_name = req |
| 56 | .org_name |
| 57 | .as_deref() |
| 58 | .map(str::trim) |
| 59 | .filter(|s| !s.is_empty()); |
| 60 | |
| 61 | // 注册开关:库内配置(/admin 可切)优先;建库前(首用户引导)总是放行 |
| 62 | let open = utopia_store::access::open_registration(&state.pool) |
| 63 | .await |
| 64 | .unwrap_or(state.open_registration); |
| 65 | let (user, workspace): (User, Workspace) = utopia_store::accounts::register( |
| 66 | &state.pool, |
| 67 | req.email.trim(), |
| 68 | &hash, |
| 69 | req.display_name.trim(), |
| 70 | org_name, |
| 71 | open, |
| 72 | ) |
| 73 | .await?; |
| 74 | |
| 75 | let token = auth::issue_token(&state, user.id)?; |
| 76 | let secure = auth::behind_tls(&headers, state.cookie_secure); |
| 77 | let jar = jar.add(auth::auth_cookie(token.clone(), secure)); |
| 78 | let _ = utopia_store::audit::record( |
| 79 | &state.pool, |
| 80 | None, |
| 81 | user.id, |
| 82 | "auth.register", |
| 83 | "user", |
| 84 | Some(user.id), |
| 85 | json!({ "email": user.email, "is_admin": user.is_admin }), |
| 86 | ) |
| 87 | .await; |
| 88 | Ok(( |
| 89 | jar, |
| 90 | Json(json!({ "user": user, "workspace": workspace, "token": token })), |
| 91 | )) |
| 92 | } |
| 93 | |
| 94 | /// 登录失败留痕:没有账号可归属,actor 记 NULL,尝试的邮箱进 detail。 |
| 95 | /// 区分「邮箱不存在」与「密码不对」——同一 IP 上大量前者是邮箱枚举, |
| 96 | /// 集中在一个账号上的后者是撞库,两种攻击的形状不一样。台账仅管理员可读, |
| 97 | /// 不存在借此探测账号是否注册的问题。 |
| 98 | async fn record_login_failure(state: &AppState, email: &str, reason: &str) { |
| 99 | let _ = utopia_store::audit::record_opt( |
| 100 | &state.pool, |
| 101 | None, |
| 102 | None, |
| 103 | "auth.login_failed", |
| 104 | "user", |
| 105 | None, |
| 106 | json!({ "email": email, "reason": reason }), |
| 107 | ) |
| 108 | .await; |
| 109 | } |
| 110 | |
| 111 | pub async fn login( |
| 112 | State(state): State<AppState>, |
| 113 | headers: HeaderMap, |
| 114 | jar: CookieJar, |
| 115 | Json(req): Json<LoginReq>, |
| 116 | ) -> ApiResult<(CookieJar, Json<serde_json::Value>)> { |
| 117 | let email = req.email.trim(); |
| 118 | let Some(user) = utopia_store::accounts::find_user_by_email(&state.pool, email).await? else { |
| 119 | record_login_failure(&state, email, "unknown_email").await; |
| 120 | return Err(AppError::Unauthorized.into()); |
| 121 | }; |
| 122 | if !auth::verify_password(&req.password, &user.password_hash) { |
| 123 | record_login_failure(&state, email, "bad_password").await; |
| 124 | return Err(AppError::Unauthorized.into()); |
| 125 | } |
| 126 | let token = auth::issue_token(&state, user.id)?; |
| 127 | let secure = auth::behind_tls(&headers, state.cookie_secure); |
| 128 | let jar = jar.add(auth::auth_cookie(token.clone(), secure)); |
| 129 | let _ = utopia_store::audit::record( |
| 130 | &state.pool, |
| 131 | None, |
| 132 | user.id, |
| 133 | "auth.login", |
| 134 | "user", |
| 135 | Some(user.id), |
| 136 | json!({}), |
| 137 | ) |
| 138 | .await; |
| 139 | Ok((jar, Json(json!({ "user": user, "token": token })))) |
| 140 | } |
| 141 | |
| 142 | /// 登出不要求有效会话——cookie 过期时也必须能清掉它,否则前端就卡在一个 |
| 143 | /// 死会话上。所以这里自己解 token 取身份,解不出就只清 cookie 不留痕。 |
| 144 | pub async fn logout( |
| 145 | State(state): State<AppState>, |
| 146 | headers: HeaderMap, |
| 147 | jar: CookieJar, |
| 148 | ) -> (CookieJar, Json<serde_json::Value>) { |
| 149 | if let Some(user_id) = jar |
| 150 | .get(auth::COOKIE_NAME) |
| 151 | .and_then(|c| auth::decode_user_id(&state, c.value()).ok()) |
| 152 | { |
| 153 | let _ = utopia_store::audit::record( |
| 154 | &state.pool, |
| 155 | None, |
| 156 | user_id, |
| 157 | "auth.logout", |
| 158 | "user", |
| 159 | Some(user_id), |
| 160 | json!({}), |
| 161 | ) |
| 162 | .await; |
| 163 | } |
| 164 | let secure = auth::behind_tls(&headers, state.cookie_secure); |
| 165 | let jar = jar.remove(auth::clear_auth_cookie(secure)); |
| 166 | (jar, Json(json!({ "ok": true }))) |
| 167 | } |
| 168 | |
| 169 | pub async fn me(AuthUser(user): AuthUser) -> Json<User> { |
| 170 | Json(user) |
| 171 | } |
| 172 | |
| 173 | #[derive(Deserialize)] |
| 174 | pub struct UpdateMeReq { |
| 175 | pub display_name: String, |
| 176 | } |
| 177 | |
| 178 | /// 个人资料:改显示名。 |
| 179 | pub async fn update_me( |
| 180 | State(state): State<AppState>, |
| 181 | AuthUser(user): AuthUser, |
| 182 | Json(req): Json<UpdateMeReq>, |
| 183 | ) -> ApiResult<Json<User>> { |
| 184 | let name = req.display_name.trim(); |
| 185 | if name.is_empty() || name.chars().count() > 64 { |
| 186 | return Err( |
| 187 | AppError::invalid("bad_display_name", "Display name must be 1-64 characters").into(), |
| 188 | ); |
| 189 | } |
| 190 | let updated = utopia_store::accounts::update_display_name(&state.pool, user.id, name).await?; |
| 191 | Ok(Json(updated)) |
| 192 | } |
| 193 | |
| 194 | #[derive(Deserialize)] |
| 195 | pub struct ChangePasswordReq { |
| 196 | pub current_password: String, |
| 197 | pub new_password: String, |
| 198 | } |
| 199 | |
| 200 | /// 改密码:验旧密 → 哈希新密。旧密错误与"未登录"区分开,前端能给出准确提示。 |
| 201 | pub async fn change_password( |
| 202 | State(state): State<AppState>, |
| 203 | AuthUser(user): AuthUser, |
| 204 | Json(req): Json<ChangePasswordReq>, |
| 205 | ) -> ApiResult<Json<serde_json::Value>> { |
| 206 | if !auth::verify_password(&req.current_password, &user.password_hash) { |
| 207 | return Err(AppError::invalid("wrong_password", "Current password is incorrect").into()); |
| 208 | } |
| 209 | if req.new_password.chars().count() < 8 { |
| 210 | return Err(AppError::invalid( |
| 211 | "password_too_short", |
| 212 | "Password must be at least 8 characters", |
| 213 | ) |
| 214 | .into()); |
| 215 | } |
| 216 | let hash = auth::hash_password(&req.new_password)?; |
| 217 | utopia_store::accounts::update_password(&state.pool, user.id, &hash).await?; |
| 218 | let _ = utopia_store::audit::record( |
| 219 | &state.pool, |
| 220 | None, |
| 221 | user.id, |
| 222 | "auth.password_changed", |
| 223 | "user", |
| 224 | Some(user.id), |
| 225 | json!({}), |
| 226 | ) |
| 227 | .await; |
| 228 | Ok(Json(json!({ "ok": true }))) |
| 229 | } |