| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | use serde::Deserialize; |
| 11 | use topcoat::{ |
| 12 | Result, |
| 13 | context::Cx, |
| 14 | router::{ |
| 15 | IntoResponse, Response, StatusCode, |
| 16 | content::Form, |
| 17 | error::{not_found, redirect, see_other}, |
| 18 | page, query_params, route, |
| 19 | }, |
| 20 | session, |
| 21 | view::{attributes, component, view}, |
| 22 | }; |
| 23 | |
| 24 | use crate::{ |
| 25 | application::{ |
| 26 | Error, NewOrganisation, OwnerSpec, claim_instance, create_organization, end_session, login, |
| 27 | record_session, set_home_by_handle, |
| 28 | }, |
| 29 | components::{ |
| 30 | button::{ButtonSize, ButtonVariant, button, button_variants}, |
| 31 | flash::{FlashKind, flash}, |
| 32 | input::input, |
| 33 | label::label, |
| 34 | }, |
| 35 | domain::{Actor, DomainError, OrgName, Password}, |
| 36 | infrastructure::{ |
| 37 | password::Argon2Hasher, |
| 38 | repository::{SqliteMembershipRepo, SqliteOrgRepo, SqliteSessionRepo, SqliteUserRepo}, |
| 39 | }, |
| 40 | }; |
| 41 | |
| 42 | use super::{ |
| 43 | context::{ |
| 44 | claimed, current_actor, hex, identity, instance_owner, instance_settings, location, |
| 45 | memberships, orgs, pool, server_error, setup_token, users, |
| 46 | }, |
| 47 | csrf::{CsrfGuard, csrf_field, csrf_verified, csrf_verified_response}, |
| 48 | format::optional, |
| 49 | layout::narrow, |
| 50 | org::home_chosen, |
| 51 | rate_limit::throttled, |
| 52 | }; |
| 53 | |
| 54 | #[derive(Debug, Deserialize)] |
| 55 | struct ClaimForm { |
| 56 | token: String, |
| 57 | handle: String, |
| 58 | email: String, |
| 59 | password: String, |
| 60 | } |
| 61 | |
| 62 | #[derive(Debug, Deserialize)] |
| 63 | struct LoginForm { |
| 64 | email: String, |
| 65 | password: String, |
| 66 | } |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | #[query_params(error = bad_request)] |
| 74 | struct Refused { |
| 75 | error: Option<String>, |
| 76 | } |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | |
| 86 | #[query_params(error = bad_request)] |
| 87 | struct Prefill { |
| 88 | token: Option<String>, |
| 89 | } |
| 90 | |
| 91 | #[page("/auth/setup")] |
| 92 | async fn setup_page(cx: &Cx) -> Result { |
| 93 | if claimed(cx).await? { |
| 94 | return Err(redirect("/").into()); |
| 95 | } |
| 96 | |
| 97 | let refused = matches!( |
| 98 | query_params::<Refused>(cx)?.error.as_deref(), |
| 99 | Some("password") |
| 100 | ); |
| 101 | let prefilled = query_params::<Prefill>(cx)? |
| 102 | .token |
| 103 | .clone() |
| 104 | .unwrap_or_default(); |
| 105 | |
| 106 | view! { |
| 107 | narrow( |
| 108 | <h1>"Claim this instance"</h1> |
| 109 | <p>"The setup token was printed to the server log at startup."</p> |
| 110 | |
| 111 | if refused { |
| 112 | <div class="mb-4">flash(kind: FlashKind::Error, (Password::RULE))</div> |
| 113 | } |
| 114 | |
| 115 | <form method="post" action="/auth/setup"> |
| 116 | <p><label>"Setup token " <input type="text" name="token" value=(prefilled.as_str()) required="true" /></label></p> |
| 117 | <p><label>"Handle " <input type="text" name="handle" required="true" /></label></p> |
| 118 | <p><label>"Email " <input type="email" name="email" required="true" /></label></p> |
| 119 | <p><label>"Password " <input type="password" name="password" required="true" /></label></p> |
| 120 | <p class="text-xs text-muted-foreground">(Password::RULE)</p> |
| 121 | <button type="submit">"Claim"</button> |
| 122 | </form> |
| 123 | ) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | |
| 131 | |
| 132 | #[route(POST "/auth/setup")] |
| 133 | async fn claim(cx: &Cx, Form(form): Form<ClaimForm>) -> Result<Response> { |
| 134 | if let Some(response) = throttled(cx) { |
| 135 | return Ok(response); |
| 136 | } |
| 137 | |
| 138 | |
| 139 | |
| 140 | |
| 141 | let Some(token) = setup_token(cx) else { |
| 142 | return see_other("/").into_response(cx); |
| 143 | }; |
| 144 | |
| 145 | let pool = pool(cx).clone(); |
| 146 | let users = SqliteUserRepo::new(pool.clone()); |
| 147 | let orgs = SqliteOrgRepo::new(pool.clone()); |
| 148 | let memberships = SqliteMembershipRepo::new(pool.clone()); |
| 149 | let sessions = SqliteSessionRepo::new(pool); |
| 150 | |
| 151 | let claimed = claim_instance( |
| 152 | &form.token, |
| 153 | token, |
| 154 | &OwnerSpec { |
| 155 | handle: form.handle, |
| 156 | email: form.email, |
| 157 | password: form.password, |
| 158 | }, |
| 159 | &users, |
| 160 | &orgs, |
| 161 | &memberships, |
| 162 | &Argon2Hasher::new(), |
| 163 | ) |
| 164 | .await; |
| 165 | |
| 166 | let actor = match claimed { |
| 167 | Ok(actor) => actor, |
| 168 | Err(error) => { |
| 169 | eprintln!("steid: claim rejected: {error}"); |
| 170 | |
| 171 | |
| 172 | |
| 173 | |
| 174 | let back = if matches!( |
| 175 | error, |
| 176 | Error::Domain(DomainError::Validation { ref field, .. }) if field == "password" |
| 177 | ) { |
| 178 | "/auth/setup?error=password" |
| 179 | } else { |
| 180 | "/auth/setup" |
| 181 | }; |
| 182 | |
| 183 | |
| 184 | |
| 185 | return see_other(back).into_response(cx); |
| 186 | } |
| 187 | }; |
| 188 | |
| 189 | sign_in(cx, &actor, &sessions).await?; |
| 190 | |
| 191 | |
| 192 | |
| 193 | |
| 194 | see_other("/auth/setup/organisation").into_response(cx) |
| 195 | } |
| 196 | |
| 197 | |
| 198 | |
| 199 | #[query_params(error = bad_request)] |
| 200 | struct Reset { |
| 201 | reset: Option<String>, |
| 202 | } |
| 203 | |
| 204 | #[page("/auth/login")] |
| 205 | async fn login_page(cx: &Cx) -> Result { |
| 206 | if !claimed(cx).await? { |
| 207 | return Err(redirect("/auth/setup").into()); |
| 208 | } |
| 209 | |
| 210 | let after_reset = query_params::<Reset>(cx)?.reset.is_some(); |
| 211 | |
| 212 | view! { |
| 213 | narrow( |
| 214 | <h1>"Sign in"</h1> |
| 215 | |
| 216 | if after_reset { |
| 217 | <div class="mb-4"> |
| 218 | flash(kind: FlashKind::Success, "Password changed. Sign in with the new one.") |
| 219 | </div> |
| 220 | } |
| 221 | |
| 222 | <form method="post" action="/auth/login"> |
| 223 | <p><label>"Email " <input type="email" name="email" required="true" /></label></p> |
| 224 | <p><label>"Password " <input type="password" name="password" required="true" /></label></p> |
| 225 | <button type="submit">"Sign in"</button> |
| 226 | </form> |
| 227 | <p class="mt-4 text-xs text-muted-foreground"> |
| 228 | <a href="/auth/forgot" class="hover:text-foreground">"Forgotten your password?"</a> |
| 229 | </p> |
| 230 | ) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | |
| 235 | |
| 236 | |
| 237 | |
| 238 | |
| 239 | #[route(POST "/auth/login")] |
| 240 | async fn sign_in_route(cx: &Cx, Form(form): Form<LoginForm>) -> Result<Response> { |
| 241 | if let Some(response) = throttled(cx) { |
| 242 | return Ok(response); |
| 243 | } |
| 244 | |
| 245 | let pool = pool(cx).clone(); |
| 246 | let users = SqliteUserRepo::new(pool.clone()); |
| 247 | let sessions = SqliteSessionRepo::new(pool); |
| 248 | |
| 249 | let actor = match login(&form.email, &form.password, &users, &Argon2Hasher::new()).await { |
| 250 | Ok(actor) => actor, |
| 251 | Err(error) => { |
| 252 | eprintln!("steid: login rejected: {error}"); |
| 253 | |
| 254 | |
| 255 | |
| 256 | |
| 257 | return see_other("/auth/login").into_response(cx); |
| 258 | } |
| 259 | }; |
| 260 | |
| 261 | sign_in(cx, &actor, &sessions).await?; |
| 262 | |
| 263 | see_other("/").into_response(cx) |
| 264 | } |
| 265 | |
| 266 | #[route(POST "/auth/logout")] |
| 267 | async fn logout(cx: &Cx, Form(guard): Form<CsrfGuard>) -> Result<Response> { |
| 268 | if let Some(response) = csrf_verified_response(cx, &guard.csrf_token).await? { |
| 269 | return Ok(response); |
| 270 | } |
| 271 | |
| 272 | |
| 273 | |
| 274 | if let Some(hash) = session::stop(cx).await? { |
| 275 | let sessions = SqliteSessionRepo::new(pool(cx).clone()); |
| 276 | end_session( |
| 277 | &crate::domain::SessionTokenHash::from_trusted(hex(&hash)), |
| 278 | &sessions, |
| 279 | ) |
| 280 | .await |
| 281 | .map_err(topcoat::Error::from)?; |
| 282 | } |
| 283 | |
| 284 | see_other("/").into_response(cx) |
| 285 | } |
| 286 | |
| 287 | |
| 288 | async fn sign_in(cx: &Cx, actor: &Actor, sessions: &SqliteSessionRepo) -> Result<()> { |
| 289 | let Some(user_id) = actor.user_id() else { |
| 290 | return Ok(()); |
| 291 | }; |
| 292 | |
| 293 | let session = session::start(cx).await?; |
| 294 | |
| 295 | record_session( |
| 296 | crate::domain::SessionTokenHash::from_trusted(hex(&session.token_hash)), |
| 297 | user_id.clone(), |
| 298 | session.expires_at, |
| 299 | sessions, |
| 300 | ) |
| 301 | .await |
| 302 | .map_err(topcoat::Error::from)?; |
| 303 | |
| 304 | Ok(()) |
| 305 | } |
| 306 | |
| 307 | |
| 308 | #[derive(Debug, Deserialize)] |
| 309 | struct WizardForm { |
| 310 | |
| 311 | |
| 312 | |
| 313 | |
| 314 | |
| 315 | #[serde(default)] |
| 316 | csrf_token: String, |
| 317 | |
| 318 | |
| 319 | |
| 320 | #[serde(default)] |
| 321 | owner: String, |
| 322 | #[serde(default)] |
| 323 | handle: String, |
| 324 | #[serde(default)] |
| 325 | display_name: String, |
| 326 | } |
| 327 | |
| 328 | |
| 329 | |
| 330 | |
| 331 | |
| 332 | |
| 333 | |
| 334 | |
| 335 | |
| 336 | async fn wizard_open(cx: &Cx) -> Result<bool> { |
| 337 | Ok(!home_chosen(cx).await? && instance_owner(cx).await?) |
| 338 | } |
| 339 | |
| 340 | |
| 341 | |
| 342 | |
| 343 | |
| 344 | #[page("/auth/setup/organisation")] |
| 345 | async fn wizard_page(cx: &Cx) -> Result { |
| 346 | let Some(identity) = identity(cx).await? else { |
| 347 | return Err(redirect("/auth/login").into()); |
| 348 | }; |
| 349 | |
| 350 | if !wizard_open(cx).await? { |
| 351 | return Err(redirect("/").into()); |
| 352 | } |
| 353 | |
| 354 | view! { |
| 355 | wizard_form( |
| 356 | handle: identity.handle.as_str(), |
| 357 | org_handle: "", |
| 358 | display_name: "", |
| 359 | error: "", |
| 360 | ) |
| 361 | } |
| 362 | } |
| 363 | |
| 364 | |
| 365 | |
| 366 | |
| 367 | |
| 368 | |
| 369 | |
| 370 | |
| 371 | |
| 372 | #[page(POST "/auth/setup/organisation")] |
| 373 | async fn wizard_submit(cx: &Cx, Form(submitted): Form<WizardForm>) -> Result { |
| 374 | csrf_verified(cx, &submitted.csrf_token).await?; |
| 375 | |
| 376 | let Some(identity) = identity(cx).await? else { |
| 377 | return Err(not_found().into()); |
| 378 | }; |
| 379 | |
| 380 | if !wizard_open(cx).await? { |
| 381 | return view! { |
| 382 | (StatusCode::SEE_OTHER) |
| 383 | (location("/")?) |
| 384 | }; |
| 385 | } |
| 386 | |
| 387 | let actor = current_actor(cx).await?; |
| 388 | |
| 389 | let outcome = match submitted.owner.as_str() { |
| 390 | "me" => set_home_for(cx, &actor, &identity.handle).await, |
| 391 | "org" => match create_organization( |
| 392 | &actor, |
| 393 | &NewOrganisation { |
| 394 | handle: submitted.handle.clone(), |
| 395 | display_name: optional(&submitted.display_name), |
| 396 | }, |
| 397 | &orgs(cx), |
| 398 | &memberships(cx), |
| 399 | ) |
| 400 | .await |
| 401 | { |
| 402 | Ok(org) => set_home_for(cx, &actor, &org.name).await, |
| 403 | Err(error) => Err(error), |
| 404 | }, |
| 405 | |
| 406 | |
| 407 | _ => Err(Error::Domain(DomainError::validation( |
| 408 | "choice", |
| 409 | "pick one of the two", |
| 410 | ))), |
| 411 | }; |
| 412 | |
| 413 | let message = match outcome { |
| 414 | Ok(()) => { |
| 415 | return view! { |
| 416 | (StatusCode::SEE_OTHER) |
| 417 | (location("/auth/setup/done")?) |
| 418 | }; |
| 419 | } |
| 420 | Err(Error::Domain(DomainError::Validation { field, reason })) => { |
| 421 | format!("That {field} is no good: {reason}.") |
| 422 | } |
| 423 | Err(Error::Domain(DomainError::AlreadyExists { .. })) => { |
| 424 | format!( |
| 425 | "The handle {} is already taken on this instance.", |
| 426 | submitted.handle.trim() |
| 427 | ) |
| 428 | } |
| 429 | Err(Error::Domain(DomainError::Forbidden | DomainError::NotFound { .. })) => { |
| 430 | return Err(not_found().into()); |
| 431 | } |
| 432 | Err(other) => return Err(server_error(std::io::Error::other(other.to_string()))), |
| 433 | }; |
| 434 | |
| 435 | view! { |
| 436 | wizard_form( |
| 437 | handle: identity.handle.as_str(), |
| 438 | org_handle: submitted.handle.as_str(), |
| 439 | display_name: submitted.display_name.as_str(), |
| 440 | error: message.as_str(), |
| 441 | ) |
| 442 | } |
| 443 | } |
| 444 | |
| 445 | |
| 446 | async fn set_home_for(cx: &Cx, actor: &Actor, handle: &OrgName) -> crate::application::Result<()> { |
| 447 | set_home_by_handle( |
| 448 | actor, |
| 449 | handle, |
| 450 | &orgs(cx), |
| 451 | &memberships(cx), |
| 452 | &users(cx), |
| 453 | &instance_settings(cx), |
| 454 | ) |
| 455 | .await |
| 456 | } |
| 457 | |
| 458 | |
| 459 | |
| 460 | |
| 461 | |
| 462 | |
| 463 | |
| 464 | |
| 465 | #[component] |
| 466 | async fn wizard_form(handle: &str, org_handle: &str, display_name: &str, error: &str) -> Result { |
| 467 | view! { |
| 468 | narrow( |
| 469 | <h1 class="text-xl font-semibold tracking-tight">"Who is this Steid for?"</h1> |
| 470 | <p class="mt-1 text-sm text-muted-foreground"> |
| 471 | "This decides where the root of this instance lands. You can change it " |
| 472 | "later in settings." |
| 473 | </p> |
| 474 | |
| 475 | if !error.is_empty() { |
| 476 | <div class="mt-6"> |
| 477 | flash(kind: FlashKind::Error, (error)) |
| 478 | </div> |
| 479 | } |
| 480 | |
| 481 | <form method="post" action="/auth/setup/organisation" class="mt-6 space-y-6"> |
| 482 | csrf_field() |
| 483 | |
| 484 | <div class="space-y-2"> |
| 485 | <div class="flex items-start gap-2"> |
| 486 | <input |
| 487 | id="owner-me" |
| 488 | name="owner" |
| 489 | type="radio" |
| 490 | value="me" |
| 491 | checked=(true) |
| 492 | class="mt-1" |
| 493 | /> |
| 494 | label(attrs: attributes! { for="owner-me" }, "Just me") |
| 495 | </div> |
| 496 | <p class="pl-6 text-xs text-muted-foreground"> |
| 497 | "The root lands on your own page, " <code class="font-mono">"/" (handle)</code> |
| 498 | "." |
| 499 | </p> |
| 500 | </div> |
| 501 | |
| 502 | <div class="space-y-3"> |
| 503 | <div class="flex items-start gap-2"> |
| 504 | <input |
| 505 | id="owner-org" |
| 506 | name="owner" |
| 507 | type="radio" |
| 508 | value="org" |
| 509 | class="mt-1" |
| 510 | /> |
| 511 | label(attrs: attributes! { for="owner-org" }, "An organisation") |
| 512 | </div> |
| 513 | <p class="pl-6 text-xs text-muted-foreground"> |
| 514 | "A company or a team. It gets a handle of its own, you own it, " |
| 515 | "and the root lands there." |
| 516 | </p> |
| 517 | |
| 518 | <div class="space-y-4 pl-6"> |
| 519 | <div class="space-y-2"> |
| 520 | label(attrs: attributes! { for="handle" }, "Organisation handle") |
| 521 | input(attrs: attributes! { |
| 522 | id="handle" |
| 523 | name="handle" |
| 524 | type="text" |
| 525 | value=(org_handle) |
| 526 | placeholder="acme" |
| 527 | maxlength=(OrgName::MAX_LEN.to_string()) |
| 528 | }) |
| 529 | </div> |
| 530 | <div class="space-y-2"> |
| 531 | label(attrs: attributes! { for="display_name" }, "Display name") |
| 532 | input(attrs: attributes! { |
| 533 | id="display_name" |
| 534 | name="display_name" |
| 535 | type="text" |
| 536 | value=(display_name) |
| 537 | placeholder="Acme Inc" |
| 538 | }) |
| 539 | </div> |
| 540 | </div> |
| 541 | </div> |
| 542 | |
| 543 | <div class="flex items-center gap-3"> |
| 544 | button(attrs: attributes! { type="submit" }, "Continue") |
| 545 | <a |
| 546 | href="/auth/setup/done" |
| 547 | class="text-sm text-muted-foreground hover:text-foreground" |
| 548 | >"Skip for now"</a> |
| 549 | </div> |
| 550 | </form> |
| 551 | ) |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | |
| 556 | |
| 557 | |
| 558 | |
| 559 | |
| 560 | #[page("/auth/setup/done")] |
| 561 | async fn wizard_done(cx: &Cx) -> Result { |
| 562 | let Some(identity) = identity(cx).await? else { |
| 563 | return Err(redirect("/auth/login").into()); |
| 564 | }; |
| 565 | |
| 566 | let handle = super::org::home(cx) |
| 567 | .await? |
| 568 | .unwrap_or_else(|| identity.handle.clone()); |
| 569 | let home = format!("/{handle}"); |
| 570 | let new_repo = format!("/{handle}/repos/new"); |
| 571 | |
| 572 | view! { |
| 573 | narrow( |
| 574 | <h1 class="text-xl font-semibold tracking-tight">"Your Steid is ready"</h1> |
| 575 | <p class="mt-3 text-sm text-muted-foreground"> |
| 576 | "This instance lands on " <code class="font-mono">(home.as_str())</code> |
| 577 | ". Create your first repository at " |
| 578 | <a href=(new_repo.as_str()) class="font-medium hover:underline"> |
| 579 | (new_repo.as_str()) |
| 580 | </a> |
| 581 | " — new repositories are private unless you say otherwise." |
| 582 | </p> |
| 583 | |
| 584 | <p class="mt-6"> |
| 585 | <a href=(home.as_str()) class=(button_variants(ButtonVariant::Primary, ButtonSize::Md))> |
| 586 | "Go to the home page" |
| 587 | </a> |
| 588 | </p> |
| 589 | ) |
| 590 | } |
| 591 | } |