| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | use im_core::accounts::{self, AccountError}; |
| 6 | use im_core::model::UserId; |
| 7 | use serde::Deserialize; |
| 8 | use topcoat::Result; |
| 9 | use topcoat::context::Cx; |
| 10 | use topcoat::router::content::Form; |
| 11 | use topcoat::router::response::IntoResponse as _; |
| 12 | use topcoat::router::{HeaderName, StatusCode, header, route}; |
| 13 | |
| 14 | use crate::server::{self, PendingPurpose}; |
| 15 | |
| 16 | pub(crate) type Redirect = Result<(StatusCode, [(HeaderName, String); 1])>; |
| 17 | |
| 18 | pub(crate) fn see(location: String) -> Redirect { |
| 19 | Ok((StatusCode::SEE_OTHER, [(header::LOCATION, location)])) |
| 20 | } |
| 21 | |
| 22 | |
| 23 | |
| 24 | fn urlencode(raw: &str) -> String { |
| 25 | let mut out = String::with_capacity(raw.len()); |
| 26 | for byte in raw.bytes() { |
| 27 | match byte { |
| 28 | b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => { |
| 29 | out.push(byte as char) |
| 30 | } |
| 31 | _ => out.push_str(&format!("%{byte:02X}")), |
| 32 | } |
| 33 | } |
| 34 | out |
| 35 | } |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | fn safe_back(raw: &str) -> &str { |
| 42 | if raw.starts_with('/') && !raw.starts_with("//") && !raw.contains('\\') { |
| 43 | raw |
| 44 | } else { |
| 45 | "/" |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | fn logout_target(raw: Option<&str>, services: &[im_core::services::Service]) -> String { |
| 55 | let Some(raw) = raw else { |
| 56 | return "/".to_string(); |
| 57 | }; |
| 58 | if raw.starts_with('/') && !raw.starts_with("//") && !raw.contains('\\') { |
| 59 | |
| 60 | |
| 61 | return raw.to_string(); |
| 62 | } |
| 63 | if let Some(origin) = url_origin(raw) |
| 64 | && services |
| 65 | .iter() |
| 66 | .any(|s| url_origin(&s.url).is_some_and(|known| known == origin)) |
| 67 | { |
| 68 | return raw.to_string(); |
| 69 | } |
| 70 | "/".to_string() |
| 71 | } |
| 72 | |
| 73 | |
| 74 | |
| 75 | fn url_origin(raw: &str) -> Option<String> { |
| 76 | let (scheme, rest) = raw.split_once("://")?; |
| 77 | if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") { |
| 78 | return None; |
| 79 | } |
| 80 | let authority = rest.split(['/', '?', '#']).next()?; |
| 81 | if authority.is_empty() { |
| 82 | return None; |
| 83 | } |
| 84 | Some(format!( |
| 85 | "{}://{}", |
| 86 | scheme.to_ascii_lowercase(), |
| 87 | authority.to_ascii_lowercase() |
| 88 | )) |
| 89 | } |
| 90 | |
| 91 | |
| 92 | |
| 93 | |
| 94 | |
| 95 | fn session_meta(cx: &Cx) -> im_core::sessions::SessionMeta { |
| 96 | let headers = topcoat::router::request::headers(cx); |
| 97 | let label = server::client_label(cx); |
| 98 | let ip = (label != "unknown").then_some(label); |
| 99 | let agent = headers |
| 100 | .get("user-agent") |
| 101 | .and_then(|value| value.to_str().ok()) |
| 102 | .map(|value| value.chars().take(255).collect::<String>()); |
| 103 | im_core::sessions::SessionMeta { ip, agent } |
| 104 | } |
| 105 | |
| 106 | #[derive(Deserialize)] |
| 107 | pub struct LoginForm { |
| 108 | email: String, |
| 109 | password: String, |
| 110 | #[serde(default)] |
| 111 | back: Option<String>, |
| 112 | } |
| 113 | |
| 114 | #[route(POST "/login")] |
| 115 | async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect { |
| 116 | let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string(); |
| 117 | let store = &server::app(cx).store; |
| 118 | |
| 119 | |
| 120 | let key = input.email.trim().to_lowercase(); |
| 121 | if accounts::login_blocked(store, &key).await? { |
| 122 | server::log_event(cx, "login_limited", Some(&key), None).await; |
| 123 | return see(format!( |
| 124 | "/login?error=rate_limited&back={}", |
| 125 | urlencode(&back) |
| 126 | )); |
| 127 | } |
| 128 | match accounts::verify_login(store, &input.email, &input.password).await { |
| 129 | Ok(user) if user.totp_confirmed => { |
| 130 | let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back).await; |
| 131 | server::set_pending_cookie(cx, sealed).await; |
| 132 | let _ = accounts::clear_login_failures(store, &key).await; |
| 133 | see("/login/totp".to_string()) |
| 134 | } |
| 135 | Ok(user) => { |
| 136 | let _ = accounts::clear_login_failures(store, &key).await; |
| 137 | let token = |
| 138 | im_core::sessions::create_session(store, &user.id, &session_meta(cx)).await?; |
| 139 | server::set_session_cookie(cx, token.expose()); |
| 140 | server::log_event(cx, "login_ok", Some(&user.email), None).await; |
| 141 | see(back) |
| 142 | } |
| 143 | Err(_) => { |
| 144 | |
| 145 | |
| 146 | let _ = accounts::record_login_failure(store, &key).await; |
| 147 | server::log_event(cx, "login_fail", Some(&input.email), None).await; |
| 148 | see(format!("/login?error=bad_login&back={}", urlencode(&back))) |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | #[derive(Deserialize)] |
| 154 | pub struct TotpForm { |
| 155 | code: String, |
| 156 | } |
| 157 | |
| 158 | #[route(POST "/login/totp")] |
| 159 | async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect { |
| 160 | let Some(pending) = server::opened_pending(cx) else { |
| 161 | return see("/login".to_string()); |
| 162 | }; |
| 163 | if pending.purpose != PendingPurpose::Login { |
| 164 | return see("/login".to_string()); |
| 165 | } |
| 166 | let store = &server::app(cx).store; |
| 167 | let user_id = UserId::from(pending.user.clone()); |
| 168 | let ok = match accounts::user_by_id(store, &user_id).await? { |
| 169 | Some(user) => match im_core::totp::totp_secret(store, &user.id).await? { |
| 170 | Some((secret, confirmed)) => { |
| 171 | |
| 172 | |
| 173 | |
| 174 | confirmed |
| 175 | && im_core::totp::consume_totp( |
| 176 | store, |
| 177 | &user.id, |
| 178 | &secret, |
| 179 | input.code.trim(), |
| 180 | time::OffsetDateTime::now_utc(), |
| 181 | ) |
| 182 | .await? |
| 183 | } |
| 184 | None => false, |
| 185 | }, |
| 186 | None => false, |
| 187 | }; |
| 188 | |
| 189 | |
| 190 | let totp_key = format!("totp:{}", pending.user); |
| 191 | if accounts::login_blocked(store, &totp_key).await? { |
| 192 | server::log_event(cx, "login_limited", None, Some("2fa")).await; |
| 193 | server::clear_pending_cookie(cx); |
| 194 | return see("/login?error=rate_limited".to_string()); |
| 195 | } |
| 196 | if !ok { |
| 197 | let _ = accounts::record_login_failure(store, &totp_key).await; |
| 198 | server::log_event(cx, "totp_fail", None, Some("login")).await; |
| 199 | return see("/login/totp?error=bad_code".to_string()); |
| 200 | } |
| 201 | let _ = accounts::clear_login_failures(store, &totp_key).await; |
| 202 | let token = im_core::sessions::create_session(store, &user_id, &session_meta(cx)).await?; |
| 203 | let email = accounts::user_by_id(store, &user_id) |
| 204 | .await? |
| 205 | .map(|u| u.email); |
| 206 | server::log_event(cx, "login_ok", email.as_deref(), Some("2fa")).await; |
| 207 | server::clear_pending_cookie(cx); |
| 208 | server::set_session_cookie(cx, token.expose()); |
| 209 | see(pending.back) |
| 210 | } |
| 211 | |
| 212 | #[derive(Deserialize)] |
| 213 | pub struct InviteForm { |
| 214 | token: String, |
| 215 | name: String, |
| 216 | password: String, |
| 217 | password_confirm: String, |
| 218 | } |
| 219 | |
| 220 | #[route(POST "/invite")] |
| 221 | async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect { |
| 222 | if input.password != input.password_confirm { |
| 223 | return see(format!("/invite/{}?error=passwords_differ", input.token)); |
| 224 | } |
| 225 | let store = &server::app(cx).store; |
| 226 | let user = match accounts::create_user_from_invite( |
| 227 | store, |
| 228 | &input.token, |
| 229 | input.name.trim(), |
| 230 | &input.password, |
| 231 | ) |
| 232 | .await |
| 233 | { |
| 234 | Ok(user) => user, |
| 235 | Err(problem) => { |
| 236 | let code = match problem { |
| 237 | AccountError::InviteInvalid => "invite_invalid", |
| 238 | AccountError::InviteExpired => "invite_expired", |
| 239 | AccountError::InviteSpent => "invite_spent", |
| 240 | AccountError::EmailTaken => "email_taken", |
| 241 | AccountError::Password(im_core::accounts::PasswordProblem::TooShort) => { |
| 242 | "password_too_short" |
| 243 | } |
| 244 | AccountError::Password(im_core::accounts::PasswordProblem::LooksLikeYou) => { |
| 245 | "password_personal" |
| 246 | } |
| 247 | _ => { |
| 248 | return Err(topcoat::Error::from(std::io::Error::other( |
| 249 | problem.to_string(), |
| 250 | ))); |
| 251 | } |
| 252 | }; |
| 253 | return see(format!("/invite/{}?error={code}", input.token)); |
| 254 | } |
| 255 | }; |
| 256 | let token = im_core::sessions::create_session(store, &user.id, &session_meta(cx)).await?; |
| 257 | server::log_event(cx, "invite_accepted", Some(&user.email), None).await; |
| 258 | |
| 259 | |
| 260 | server::notify_profile(cx, &user.id).await; |
| 261 | server::set_session_cookie(cx, token.expose()); |
| 262 | see("/".to_string()) |
| 263 | } |
| 264 | |
| 265 | #[route(POST "/enroll")] |
| 266 | async fn enroll(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect { |
| 267 | let Some(user) = server::current_user(cx).await else { |
| 268 | return see("/login".to_string()); |
| 269 | }; |
| 270 | if user.totp_confirmed { |
| 271 | return see("/".to_string()); |
| 272 | } |
| 273 | let store = &server::app(cx).store; |
| 274 | let Some((secret, _)) = im_core::totp::totp_secret(store, &user.id).await? else { |
| 275 | return see("/enroll".to_string()); |
| 276 | }; |
| 277 | |
| 278 | |
| 279 | if !im_core::totp::consume_totp( |
| 280 | store, |
| 281 | &user.id, |
| 282 | &secret, |
| 283 | input.code.trim(), |
| 284 | time::OffsetDateTime::now_utc(), |
| 285 | ) |
| 286 | .await? |
| 287 | { |
| 288 | return see("/enroll?error=bad_code".to_string()); |
| 289 | } |
| 290 | im_core::totp::confirm_totp(store, &user.id).await?; |
| 291 | let email = accounts::user_by_id(store, &user.id) |
| 292 | .await? |
| 293 | .map(|u| u.email); |
| 294 | server::log_event(cx, "enrolled", email.as_deref(), None).await; |
| 295 | see("/?ok=enrolled".to_string()) |
| 296 | } |
| 297 | |
| 298 | |
| 299 | |
| 300 | #[route(POST "/logout")] |
| 301 | async fn logout(cx: &Cx) -> Redirect { |
| 302 | sign_out_everywhere(cx).await?; |
| 303 | see("/".to_string()) |
| 304 | } |
| 305 | |
| 306 | |
| 307 | |
| 308 | |
| 309 | async fn sign_out_everywhere(cx: &Cx) -> Result<()> { |
| 310 | if let Some(token) = server::presented_session(cx) { |
| 311 | let user = im_core::sessions::resolve_session(&server::app(cx).store, &token) |
| 312 | .await? |
| 313 | .map(|u| (u.id, u.email)); |
| 314 | im_core::sessions::revoke_session(&server::app(cx).store, &token).await?; |
| 315 | |
| 316 | |
| 317 | |
| 318 | if let Some((id, _)) = &user { |
| 319 | server::note_revoked(cx, id.as_str(), Some(&im_core::accounts::hash_token(&token))) |
| 320 | .await; |
| 321 | } |
| 322 | server::log_event( |
| 323 | cx, |
| 324 | "logout", |
| 325 | user.as_ref().map(|(_, email)| email.as_str()), |
| 326 | None, |
| 327 | ) |
| 328 | .await; |
| 329 | } |
| 330 | server::clear_session_cookie(cx); |
| 331 | Ok(()) |
| 332 | } |
| 333 | |
| 334 | |
| 335 | |
| 336 | |
| 337 | |
| 338 | #[route(GET "/logout")] |
| 339 | async fn logout_return(cx: &Cx) -> Redirect { |
| 340 | let query = topcoat::router::request::uri(cx) |
| 341 | .query() |
| 342 | .unwrap_or("") |
| 343 | .to_string(); |
| 344 | let back = crate::pages::query_value(&query, "back"); |
| 345 | sign_out_everywhere(cx).await?; |
| 346 | let services = im_core::services::list(&server::app(cx).store).await?; |
| 347 | see(logout_target(back.as_deref(), &services)) |
| 348 | } |
| 349 | |
| 350 | |
| 351 | |
| 352 | |
| 353 | |
| 354 | #[route(GET "/api/me")] |
| 355 | async fn me_probe(cx: &Cx) -> topcoat::Result<topcoat::router::response::Response> { |
| 356 | if server::current_user(cx).await.is_some() { |
| 357 | (StatusCode::NO_CONTENT, "").into_response(cx) |
| 358 | } else { |
| 359 | (StatusCode::UNAUTHORIZED, "").into_response(cx) |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | #[derive(Deserialize)] |
| 364 | pub struct ForgotForm { |
| 365 | email: String, |
| 366 | } |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | |
| 373 | |
| 374 | #[route(POST "/forgot")] |
| 375 | async fn forgot(cx: &Cx, Form(input): Form<ForgotForm>) -> Redirect { |
| 376 | let store = &server::app(cx).store; |
| 377 | let email = input.email.trim().to_string(); |
| 378 | let key = format!("forgot:{}", email.to_lowercase()); |
| 379 | if accounts::login_blocked(store, &key).await? { |
| 380 | server::log_event(cx, "forgot_limited", Some(&email), None).await; |
| 381 | return see("/forgot?ok=sent".to_string()); |
| 382 | } |
| 383 | |
| 384 | |
| 385 | let _ = accounts::record_login_failure(store, &key).await; |
| 386 | if let Some(token) = accounts::create_reset(store, &email).await? { |
| 387 | let issuer = server::app(cx).config.issuer.clone(); |
| 388 | |
| 389 | |
| 390 | let lang = accounts::user_by_email(store, &email) |
| 391 | .await? |
| 392 | .map(|user| crate::i18n::Lang::from_code(&user.language)) |
| 393 | .unwrap_or(crate::i18n::Lang::En); |
| 394 | if crate::mailer::send_reset(store, &issuer, &email, token.expose(), lang) |
| 395 | .await |
| 396 | .is_ok() |
| 397 | { |
| 398 | server::log_event(cx, "reset_sent", Some(&email), None).await; |
| 399 | } |
| 400 | } |
| 401 | see("/forgot?ok=sent".to_string()) |
| 402 | } |
| 403 | |
| 404 | #[derive(Deserialize)] |
| 405 | pub struct ResetForm { |
| 406 | token: String, |
| 407 | password: String, |
| 408 | password_confirm: String, |
| 409 | } |
| 410 | |
| 411 | |
| 412 | |
| 413 | #[route(POST "/reset")] |
| 414 | async fn reset(cx: &Cx, Form(input): Form<ResetForm>) -> Redirect { |
| 415 | if input.password != input.password_confirm { |
| 416 | return see(format!("/reset/{}?error=passwords_differ", input.token)); |
| 417 | } |
| 418 | let store = &server::app(cx).store; |
| 419 | match accounts::redeem_reset(store, &input.token, &input.password).await { |
| 420 | Ok(user) => { |
| 421 | |
| 422 | |
| 423 | server::note_revoked(cx, user.id.as_str(), None).await; |
| 424 | server::log_event(cx, "password_reset", Some(&user.email), None).await; |
| 425 | see("/login?ok=reset".to_string()) |
| 426 | } |
| 427 | Err(AccountError::Password(problem)) => { |
| 428 | let code = match problem { |
| 429 | im_core::accounts::PasswordProblem::TooShort => "password_too_short", |
| 430 | im_core::accounts::PasswordProblem::LooksLikeYou => "password_personal", |
| 431 | _ => "passwords_differ", |
| 432 | }; |
| 433 | see(format!("/reset/{}?error={code}", input.token)) |
| 434 | } |
| 435 | Err(AccountError::ResetInvalid) => see("/forgot?error=reset_invalid".to_string()), |
| 436 | Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | #[derive(Deserialize)] |
| 441 | struct EmailChangeForm { |
| 442 | email: String, |
| 443 | } |
| 444 | |
| 445 | |
| 446 | |
| 447 | |
| 448 | |
| 449 | |
| 450 | #[route(POST "/email_change")] |
| 451 | async fn email_change(cx: &Cx, Form(input): Form<EmailChangeForm>) -> Redirect { |
| 452 | let Some(me) = server::current_user(cx).await else { |
| 453 | return see("/".to_string()); |
| 454 | }; |
| 455 | let store = &server::app(cx).store; |
| 456 | let (old_token, new_token) = |
| 457 | match accounts::request_email_change(store, &me.id, &input.email).await { |
| 458 | Ok(pair) => pair, |
| 459 | Err(AccountError::InvalidEmail) => { |
| 460 | return see("/?section=password&error=bad_email".to_string()); |
| 461 | } |
| 462 | Err(AccountError::SameEmail) => { |
| 463 | return see("/?section=password&error=same_email".to_string()); |
| 464 | } |
| 465 | Err(AccountError::EmailTaken) => { |
| 466 | return see("/?section=password&error=email_taken".to_string()); |
| 467 | } |
| 468 | Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), |
| 469 | }; |
| 470 | let issuer = server::app(cx).config.issuer.clone(); |
| 471 | |
| 472 | let lang = crate::i18n::Lang::from_code(&me.language); |
| 473 | let old_mailed = crate::mailer::send_email_change( |
| 474 | store, |
| 475 | &issuer, |
| 476 | &me.email, |
| 477 | old_token.expose(), |
| 478 | lang, |
| 479 | false, |
| 480 | ) |
| 481 | .await |
| 482 | .is_ok(); |
| 483 | let new_mailed = crate::mailer::send_email_change( |
| 484 | store, |
| 485 | &issuer, |
| 486 | input.email.trim(), |
| 487 | new_token.expose(), |
| 488 | lang, |
| 489 | true, |
| 490 | ) |
| 491 | .await |
| 492 | .is_ok(); |
| 493 | server::log_event( |
| 494 | cx, |
| 495 | "email_change_asked", |
| 496 | Some(&me.email), |
| 497 | Some(input.email.trim().to_lowercase()).as_deref(), |
| 498 | ) |
| 499 | .await; |
| 500 | if old_mailed && new_mailed { |
| 501 | see("/?section=password&ok=email_change_asked".to_string()) |
| 502 | } else { |
| 503 | let links = format!( |
| 504 | "{issuer}/email/{} {issuer}/email/{}", |
| 505 | old_token.expose(), |
| 506 | new_token.expose() |
| 507 | ); |
| 508 | see(format!( |
| 509 | "/?section=password&ok=email_change_asked&links={}", |
| 510 | crate::oidc::urlencode(&links) |
| 511 | )) |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | #[derive(Deserialize)] |
| 516 | struct EmailConfirmForm { |
| 517 | token: String, |
| 518 | } |
| 519 | |
| 520 | |
| 521 | |
| 522 | |
| 523 | |
| 524 | |
| 525 | #[route(POST "/email")] |
| 526 | async fn email_confirm(cx: &Cx, Form(input): Form<EmailConfirmForm>) -> Redirect { |
| 527 | let store = &server::app(cx).store; |
| 528 | match accounts::confirm_email_change(store, &input.token).await { |
| 529 | Ok(accounts::EmailChangeConfirmed::Applied(user)) => { |
| 530 | server::log_event(cx, "email_changed", Some(&user.email), None).await; |
| 531 | |
| 532 | |
| 533 | server::notify_profile(cx, &user.id).await; |
| 534 | if server::current_user(cx).await.is_some() { |
| 535 | see("/?section=profile&ok=email_changed".to_string()) |
| 536 | } else { |
| 537 | see("/login?ok=email_changed".to_string()) |
| 538 | } |
| 539 | } |
| 540 | Ok(accounts::EmailChangeConfirmed::AwaitOther) => { |
| 541 | if server::current_user(cx).await.is_some() { |
| 542 | see("/?section=profile&ok=email_half_confirmed".to_string()) |
| 543 | } else { |
| 544 | see("/login?ok=email_half_confirmed".to_string()) |
| 545 | } |
| 546 | } |
| 547 | Err(AccountError::EmailTaken) => see("/login?error=email_taken".to_string()), |
| 548 | Err(AccountError::EmailChangeInvalid) => { |
| 549 | see("/login?error=email_change_invalid".to_string()) |
| 550 | } |
| 551 | Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), |
| 552 | } |
| 553 | } |
| 554 | #[derive(Deserialize)] |
| 555 | struct SessionRevokeForm { |
| 556 | session: String, |
| 557 | } |
| 558 | |
| 559 | |
| 560 | |
| 561 | |
| 562 | #[route(POST "/sessions/revoke")] |
| 563 | async fn revoke_session(cx: &Cx, Form(input): Form<SessionRevokeForm>) -> Redirect { |
| 564 | let Some(user) = server::current_user(cx).await else { |
| 565 | return see("/".to_string()); |
| 566 | }; |
| 567 | let store = &server::app(cx).store; |
| 568 | if let Some(presented) = server::presented_session(cx) |
| 569 | && im_core::accounts::hash_token(&presented) == input.session |
| 570 | { |
| 571 | im_core::sessions::revoke_session(store, &presented).await?; |
| 572 | |
| 573 | |
| 574 | server::note_revoked(cx, user.id.as_str(), Some(&input.session)).await; |
| 575 | server::clear_session_cookie(cx); |
| 576 | return see("/".to_string()); |
| 577 | } |
| 578 | |
| 579 | |
| 580 | let ip = im_core::sessions::list_sessions(store, &user.id) |
| 581 | .await? |
| 582 | .into_iter() |
| 583 | .find(|s| s.token_hash == input.session) |
| 584 | .and_then(|s| s.ip); |
| 585 | if !im_core::sessions::revoke_owned_session(store, &user.id, &input.session).await? { |
| 586 | return see("/?section=sessions&error=session_unknown".to_string()); |
| 587 | } |
| 588 | server::note_revoked(cx, user.id.as_str(), Some(&input.session)).await; |
| 589 | server::log_event(cx, "session_revoked", Some(&user.email), ip.as_deref()).await; |
| 590 | see("/?section=sessions&ok=session_revoked".to_string()) |
| 591 | } |
| 592 | |
| 593 | #[derive(Deserialize)] |
| 594 | struct PreferencesForm { |
| 595 | theme: Option<String>, |
| 596 | ui: Option<String>, |
| 597 | language: Option<String>, |
| 598 | timezone: Option<String>, |
| 599 | } |
| 600 | |
| 601 | |
| 602 | |
| 603 | |
| 604 | #[route(POST "/preferences")] |
| 605 | async fn preferences(cx: &Cx, Form(input): Form<PreferencesForm>) -> Redirect { |
| 606 | let Some(user) = server::current_user(cx).await else { |
| 607 | return see("/".to_string()); |
| 608 | }; |
| 609 | let Some(theme) = input.theme.as_deref() else { |
| 610 | return see("/?section=preferences&error=bad_theme".to_string()); |
| 611 | }; |
| 612 | if theme != "light" && theme != "dark" { |
| 613 | return see("/?section=preferences&error=bad_theme".to_string()); |
| 614 | } |
| 615 | let Some(ui) = input.ui.as_deref() else { |
| 616 | return see("/?section=preferences&error=bad_ui".to_string()); |
| 617 | }; |
| 618 | if ui != "instrument" && ui != "ledger" { |
| 619 | return see("/?section=preferences&error=bad_ui".to_string()); |
| 620 | } |
| 621 | let Some(language) = input.language.as_deref() else { |
| 622 | return see("/?section=preferences&error=bad_language".to_string()); |
| 623 | }; |
| 624 | if language != "en" && language != "tr" { |
| 625 | return see("/?section=preferences&error=bad_language".to_string()); |
| 626 | } |
| 627 | let Some(timezone) = input.timezone.as_deref() else { |
| 628 | return see("/?section=preferences&error=bad_zone".to_string()); |
| 629 | }; |
| 630 | if !crate::pages::zone_options().contains(&timezone.to_string()) { |
| 631 | return see("/?section=preferences&error=bad_zone".to_string()); |
| 632 | } |
| 633 | let store = &server::app(cx).store; |
| 634 | im_core::accounts::set_preferences(store, &user.id, theme, language, ui, timezone).await?; |
| 635 | |
| 636 | |
| 637 | server::notify_profile(cx, &user.id).await; |
| 638 | server::log_event(cx, "preferences_saved", Some(&user.email), None).await; |
| 639 | see("/?section=preferences&ok=preferences".to_string()) |
| 640 | } |
| 641 | |
| 642 | #[derive(Deserialize)] |
| 643 | struct PasswordForm { |
| 644 | current: String, |
| 645 | password: String, |
| 646 | password_confirm: String, |
| 647 | } |
| 648 | |
| 649 | |
| 650 | |
| 651 | |
| 652 | |
| 653 | #[route(POST "/password")] |
| 654 | async fn password(cx: &Cx, Form(input): Form<PasswordForm>) -> Redirect { |
| 655 | let Some(me) = server::current_user(cx).await else { |
| 656 | return see("/".to_string()); |
| 657 | }; |
| 658 | if input.password != input.password_confirm { |
| 659 | return see("/?section=password&error=passwords_differ".to_string()); |
| 660 | } |
| 661 | let store = &server::app(cx).store; |
| 662 | match im_core::accounts::change_password(store, &me, &input.current, &input.password).await { |
| 663 | Ok(()) => {} |
| 664 | Err(im_core::accounts::AccountError::Password(problem)) => { |
| 665 | use im_core::accounts::PasswordProblem::*; |
| 666 | let code = match problem { |
| 667 | TooShort => "password_too_short", |
| 668 | LooksLikeYou => "password_personal", |
| 669 | WrongCurrent => "password_wrong", |
| 670 | IsCurrent => "password_same", |
| 671 | }; |
| 672 | return see(format!("/?section=password&error={code}")); |
| 673 | } |
| 674 | Err(e) => return Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), |
| 675 | } |
| 676 | if let Some(token) = server::presented_session(cx) { |
| 677 | let revoked = im_core::sessions::revoke_user_sessions_except(store, &me.id, &token) |
| 678 | .await?; |
| 679 | |
| 680 | |
| 681 | for hash in &revoked { |
| 682 | server::note_revoked(cx, me.id.as_str(), Some(hash)).await; |
| 683 | } |
| 684 | } |
| 685 | server::log_event(cx, "password_changed", Some(&me.email), None).await; |
| 686 | see("/?section=password&ok=password".to_string()) |
| 687 | } |
| 688 | |
| 689 | #[cfg(test)] |
| 690 | mod tests { |
| 691 | use super::*; |
| 692 | |
| 693 | #[test] |
| 694 | fn back_rejects_scheme_relative_and_backslash_paths() { |
| 695 | assert_eq!(safe_back("/dashboard"), "/dashboard"); |
| 696 | assert_eq!(safe_back("/authorize?client_id=x"), "/authorize?client_id=x"); |
| 697 | assert_eq!(safe_back("//evil.example/path"), "/"); |
| 698 | |
| 699 | |
| 700 | assert_eq!(safe_back("/\\evil.example"), "/"); |
| 701 | assert_eq!(safe_back("/settings\\..\\..\\evil"), "/"); |
| 702 | assert_eq!(safe_back("https://evil.example"), "/"); |
| 703 | assert_eq!(safe_back("relative"), "/"); |
| 704 | } |
| 705 | |
| 706 | #[test] |
| 707 | fn logout_target_judges_local_paths_by_the_back_rule() { |
| 708 | let services: Vec<im_core::services::Service> = Vec::new(); |
| 709 | assert_eq!(logout_target(None, &services), "/"); |
| 710 | assert_eq!(logout_target(Some("/settings"), &services), "/settings"); |
| 711 | assert_eq!(logout_target(Some("//evil.example"), &services), "/"); |
| 712 | assert_eq!(logout_target(Some("/\\evil.example"), &services), "/"); |
| 713 | assert_eq!( |
| 714 | logout_target(Some("https://stranger.example/bye"), &services), |
| 715 | "/" |
| 716 | ); |
| 717 | } |
| 718 | |
| 719 | #[test] |
| 720 | fn logout_target_hands_the_browser_to_a_known_family_service() { |
| 721 | let sibling = im_core::services::Service { |
| 722 | key: "in".into(), |
| 723 | name: "in".into(), |
| 724 | url: "https://in.example".into(), |
| 725 | owner: None, |
| 726 | client_id: None, |
| 727 | storage_limit_bytes: None, |
| 728 | }; |
| 729 | let services = vec![sibling]; |
| 730 | assert_eq!( |
| 731 | logout_target(Some("https://in.example/goodbye"), &services), |
| 732 | "https://in.example/goodbye" |
| 733 | ); |
| 734 | |
| 735 | assert_eq!( |
| 736 | logout_target(Some("https://in.example.evil/bye"), &services), |
| 737 | "/" |
| 738 | ); |
| 739 | |
| 740 | assert_eq!(logout_target(Some("/\\in.example"), &services), "/"); |
| 741 | } |
| 742 | } |