| 1 | use axum::Json; |
| 2 | use axum::extract::{Request, State}; |
| 3 | use axum::http::StatusCode; |
| 4 | use axum::middleware::{self, Next}; |
| 5 | use axum_extra::extract::CookieJar; |
| 6 | use axum_extra::extract::cookie::{Cookie, SameSite}; |
| 7 | use serde::{Deserialize, Serialize}; |
| 8 | use utoipa::ToSchema; |
| 9 | use utoipa_axum::router::OpenApiRouter; |
| 10 | use utoipa_axum::routes; |
| 11 | |
| 12 | use crate::constant::{RESERVED_USERNAMES, SESSION_DURATION_DAYS}; |
| 13 | use crate::domain::role::Role as DomainRole; |
| 14 | use crate::domain::user::{Password, PasswordHash, Username}; |
| 15 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 16 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; |
| 17 | use crate::service; |
| 18 | use crate::state::AppState; |
| 19 | use crate::tenant::SchoolId; |
| 20 | |
| 21 | use super::dto::Role; |
| 22 | use super::tenant_state::split_cookie; |
| 23 | use super::{BUILDER_COOKIE_PREFIX, CurrentUser, PERSON_COOKIE_PREFIX, UserResponse}; |
| 24 | |
| 25 | pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { |
| 26 | |
| 27 | |
| 28 | |
| 29 | |
| 30 | let rate_limit: &RateLimitConfig = &state.rate_limit; |
| 31 | let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); |
| 32 | |
| 33 | |
| 34 | limiter.share("auth", state.db.clone()); |
| 35 | OpenApiRouter::new() |
| 36 | .routes(routes!(register)) |
| 37 | .routes(routes!(login)) |
| 38 | |
| 39 | .route_layer(middleware::from_fn(move |req: Request, next: Next| { |
| 40 | let limiter = limiter.clone(); |
| 41 | async move { limiter.enforce(req, next).await } |
| 42 | })) |
| 43 | .routes(routes!(list_schools)) |
| 44 | .routes(routes!(select_school)) |
| 45 | .routes(routes!(logout)) |
| 46 | .routes(routes!(me)) |
| 47 | } |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | #[derive(Deserialize, ToSchema)] |
| 54 | struct RegisterCredentials { |
| 55 | |
| 56 | |
| 57 | #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")] |
| 58 | school: String, |
| 59 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| 60 | username: String, |
| 61 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 62 | password: String, |
| 63 | } |
| 64 | |
| 65 | |
| 66 | |
| 67 | |
| 68 | #[derive(Deserialize, ToSchema)] |
| 69 | struct LoginCredentials { |
| 70 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| 71 | username: String, |
| 72 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 73 | password: String, |
| 74 | } |
| 75 | |
| 76 | |
| 77 | #[derive(Serialize, ToSchema)] |
| 78 | struct SchoolChoice { |
| 79 | #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")] |
| 80 | id: String, |
| 81 | #[schema(example = "Demo")] |
| 82 | name: String, |
| 83 | } |
| 84 | |
| 85 | |
| 86 | |
| 87 | |
| 88 | |
| 89 | #[derive(Serialize, ToSchema)] |
| 90 | struct SchoolChoiceResponse { |
| 91 | #[schema(example = "ada")] |
| 92 | username: String, |
| 93 | schools: Vec<SchoolChoice>, |
| 94 | } |
| 95 | |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | #[derive(Serialize, ToSchema)] |
| 101 | #[serde(untagged)] |
| 102 | enum LoginResponse { |
| 103 | LoggedIn(Box<UserResponse>), |
| 104 | ChooseSchool(SchoolChoiceResponse), |
| 105 | } |
| 106 | |
| 107 | |
| 108 | #[derive(Deserialize, ToSchema)] |
| 109 | struct SelectSchool { |
| 110 | #[schema(example = "01a0b0a5-ffb5-7682-8726-7e4ef1a5c68d")] |
| 111 | school: String, |
| 112 | } |
| 113 | |
| 114 | |
| 115 | |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | #[derive(Serialize, ToSchema)] |
| 121 | struct RegisterResponse { |
| 122 | #[schema(example = "ada")] |
| 123 | username: String, |
| 124 | role: Role, |
| 125 | } |
| 126 | |
| 127 | |
| 128 | |
| 129 | #[utoipa::path( |
| 130 | get, |
| 131 | path = "/schools", |
| 132 | tag = "auth", |
| 133 | responses( |
| 134 | (status = 200, description = "Active schools, id and display name, sorted by name", body = Vec<SchoolChoice>), |
| 135 | ), |
| 136 | )] |
| 137 | async fn list_schools(State(st): State<AppState>) -> Result<Json<Vec<SchoolChoice>>, AppError> { |
| 138 | let rows = crate::db::person::list_active_schools(&st.db).await?; |
| 139 | Ok(Json( |
| 140 | rows.into_iter() |
| 141 | .map(|(id, name)| SchoolChoice { |
| 142 | id: id.to_string(), |
| 143 | name, |
| 144 | }) |
| 145 | .collect(), |
| 146 | )) |
| 147 | } |
| 148 | |
| 149 | |
| 150 | |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | |
| 156 | |
| 157 | |
| 158 | |
| 159 | |
| 160 | |
| 161 | |
| 162 | |
| 163 | |
| 164 | |
| 165 | |
| 166 | #[utoipa::path( |
| 167 | post, |
| 168 | path = "/register", |
| 169 | tag = "auth", |
| 170 | request_body = RegisterCredentials, |
| 171 | responses( |
| 172 | (status = 201, description = "Account created, the username was already taken, or an existing person was attached to this school — deliberately indistinguishable. Carries no `id`: on the taken path there is no row to name, so log in to learn who you are", body = RegisterResponse), |
| 173 | (status = 400, description = "Invalid username or password", body = ErrorResponse), |
| 174 | (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse), |
| 175 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| 176 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 177 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 178 | ), |
| 179 | )] |
| 180 | async fn register( |
| 181 | State(st): State<AppState>, |
| 182 | Json(req): Json<RegisterCredentials>, |
| 183 | ) -> Result<(StatusCode, Json<RegisterResponse>), AppError> { |
| 184 | |
| 185 | |
| 186 | |
| 187 | |
| 188 | let school = SchoolId::try_parse(&req.school).map_err(|_| AppError::Unauthorized)?; |
| 189 | let db = st.tenants.get(&school).await?; |
| 190 | let username = Username::try_new(&req.username)?; |
| 191 | |
| 192 | |
| 193 | |
| 194 | if RESERVED_USERNAMES.contains(&username.as_str()) { |
| 195 | return Err(ValidationError::Invalid { |
| 196 | field: "username", |
| 197 | reason: "this username is reserved", |
| 198 | } |
| 199 | .into()); |
| 200 | } |
| 201 | |
| 202 | |
| 203 | |
| 204 | let password = Password::try_new(&req.password)?; |
| 205 | let password_hash = password.hash_async().await?; |
| 206 | |
| 207 | |
| 208 | |
| 209 | |
| 210 | let body = RegisterResponse { |
| 211 | username: username.as_str().to_string(), |
| 212 | role: DomainRole::Student.into(), |
| 213 | }; |
| 214 | |
| 215 | |
| 216 | |
| 217 | |
| 218 | let person = |
| 219 | service::person::create_or_load(&st.db, username.clone(), password_hash.clone()).await?; |
| 220 | if person.get_password_hash().verify_async(&password).await { |
| 221 | |
| 222 | |
| 223 | |
| 224 | |
| 225 | |
| 226 | match service::user::create(&db, username, Some(*person.get_id())).await { |
| 227 | Ok(_) => {} |
| 228 | Err(AppError::Conflict(_)) => { |
| 229 | tracing::info!("register: school username already taken, answering 201"); |
| 230 | } |
| 231 | Err(err) => return Err(err), |
| 232 | } |
| 233 | service::person::link_school(&st.db, person.get_id(), &school).await?; |
| 234 | } else { |
| 235 | tracing::info!("register: username taken, password does not match, answering 201"); |
| 236 | } |
| 237 | Ok((StatusCode::CREATED, Json(body))) |
| 238 | } |
| 239 | |
| 240 | |
| 241 | |
| 242 | |
| 243 | |
| 244 | |
| 245 | #[utoipa::path( |
| 246 | post, |
| 247 | path = "/login", |
| 248 | tag = "auth", |
| 249 | request_body = LoginCredentials, |
| 250 | responses( |
| 251 | (status = 200, description = "Logged in — either straight into the one school (a `UserResponse` and a `<uuid>.<token>` cookie), or as a multi-school person (a `{username, schools}` choice list and a `person.<token>` cookie to bind with `POST /auth/school`). Suspended schools appear in neither shape", body = LoginResponse), |
| 252 | (status = 401, description = "Bad credentials — unknown username, wrong password, or no school membership left to enter, all deliberately indistinguishable", body = ErrorResponse), |
| 253 | (status = 403, description = "Every school the person belongs to is suspended", body = ErrorResponse), |
| 254 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 255 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 256 | ), |
| 257 | )] |
| 258 | async fn login( |
| 259 | State(st): State<AppState>, |
| 260 | jar: CookieJar, |
| 261 | Json(req): Json<LoginCredentials>, |
| 262 | ) -> Result<(CookieJar, Json<LoginResponse>), AppError> { |
| 263 | |
| 264 | |
| 265 | |
| 266 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 267 | |
| 268 | |
| 269 | |
| 270 | |
| 271 | let person = match service::person::find_by_username(&st.db, req.username.trim()).await? { |
| 272 | |
| 273 | |
| 274 | |
| 275 | Some(person) => { |
| 276 | if !person.get_password_hash().verify_async(&password).await { |
| 277 | return Err(AppError::Unauthorized); |
| 278 | } |
| 279 | person |
| 280 | } |
| 281 | None => { |
| 282 | |
| 283 | |
| 284 | |
| 285 | PasswordHash::verify_decoy_async(&password).await; |
| 286 | return Err(AppError::Unauthorized); |
| 287 | } |
| 288 | }; |
| 289 | |
| 290 | let memberships = service::person::memberships(&st.db, person.get_id()).await?; |
| 291 | let active: Vec<_> = memberships.iter().filter(|m| m.is_active()).collect(); |
| 292 | match active.as_slice() { |
| 293 | |
| 294 | |
| 295 | |
| 296 | [] if memberships.is_empty() => Err(AppError::Unauthorized), |
| 297 | |
| 298 | |
| 299 | [] => Err(AppError::Forbidden("school is suspended")), |
| 300 | [only] => { |
| 301 | let db = st.tenants.get(&only.id()).await?; |
| 302 | |
| 303 | |
| 304 | |
| 305 | let Some(user) = |
| 306 | service::user::find_by_username(&db, person.get_username().as_str()).await? |
| 307 | else { |
| 308 | return Err(AppError::Unauthorized); |
| 309 | }; |
| 310 | |
| 311 | let _ = service::session::purge_expired(&db).await; |
| 312 | let session = service::session::create(&db, user.get_id()).await?; |
| 313 | |
| 314 | |
| 315 | |
| 316 | let cookie = session_cookie( |
| 317 | format!("{}.{}", only.id(), session.token().as_str()), |
| 318 | st.cookie_secure, |
| 319 | ); |
| 320 | Ok(( |
| 321 | jar.add(cookie), |
| 322 | Json(LoginResponse::LoggedIn(Box::new(UserResponse::new(&user)))), |
| 323 | )) |
| 324 | } |
| 325 | many => { |
| 326 | |
| 327 | |
| 328 | |
| 329 | let session = service::person::create_session(&st.db, person.get_id()).await?; |
| 330 | let cookie = session_cookie( |
| 331 | format!("{PERSON_COOKIE_PREFIX}.{}", session.token().as_str()), |
| 332 | st.cookie_secure, |
| 333 | ); |
| 334 | let schools = many |
| 335 | .iter() |
| 336 | .map(|m| SchoolChoice { |
| 337 | id: m.id().as_str(), |
| 338 | name: m.name().to_string(), |
| 339 | }) |
| 340 | .collect(); |
| 341 | Ok(( |
| 342 | jar.add(cookie), |
| 343 | Json(LoginResponse::ChooseSchool(SchoolChoiceResponse { |
| 344 | username: person.get_username().as_str().to_string(), |
| 345 | schools, |
| 346 | })), |
| 347 | )) |
| 348 | } |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | |
| 353 | |
| 354 | |
| 355 | |
| 356 | #[utoipa::path( |
| 357 | post, |
| 358 | path = "/school", |
| 359 | tag = "auth", |
| 360 | request_body = SelectSchool, |
| 361 | responses( |
| 362 | (status = 200, description = "School selected; the person cookie is replaced by the school session cookie", body = UserResponse), |
| 363 | (status = 401, description = "No person session, or the school is not among the caller's memberships — deliberately indistinguishable (no cookie at all, a school or builder cookie, and an id the person does not hold all answer the same)", body = ErrorResponse), |
| 364 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| 365 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 366 | ), |
| 367 | )] |
| 368 | async fn select_school( |
| 369 | State(st): State<AppState>, |
| 370 | jar: CookieJar, |
| 371 | Json(req): Json<SelectSchool>, |
| 372 | ) -> Result<(CookieJar, Json<UserResponse>), AppError> { |
| 373 | |
| 374 | |
| 375 | |
| 376 | let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) else { |
| 377 | return Err(AppError::Unauthorized); |
| 378 | }; |
| 379 | if prefix != PERSON_COOKIE_PREFIX { |
| 380 | return Err(AppError::Unauthorized); |
| 381 | } |
| 382 | let session = service::person::find_session_by_token(&st.db, token) |
| 383 | .await? |
| 384 | .filter(|s| !s.is_expired()) |
| 385 | .ok_or(AppError::Unauthorized)?; |
| 386 | |
| 387 | |
| 388 | |
| 389 | let id = SchoolId::try_parse(&req.school).map_err(|_| AppError::Unauthorized)?; |
| 390 | service::person::membership_of(&st.db, session.person(), &id) |
| 391 | .await? |
| 392 | .ok_or(AppError::Unauthorized)?; |
| 393 | |
| 394 | let db = st.tenants.get(&id).await?; |
| 395 | let person = service::person::read(&st.db, session.person()) |
| 396 | .await? |
| 397 | .ok_or(AppError::Unauthorized)?; |
| 398 | let Some(user) = service::user::find_by_username(&db, person.get_username().as_str()).await? |
| 399 | else { |
| 400 | return Err(AppError::Unauthorized); |
| 401 | }; |
| 402 | |
| 403 | |
| 404 | |
| 405 | let school_session = service::session::create(&db, user.get_id()).await?; |
| 406 | service::person::delete_session_by_token(&st.db, token).await?; |
| 407 | let cookie = session_cookie( |
| 408 | format!("{id}.{}", school_session.token().as_str()), |
| 409 | st.cookie_secure, |
| 410 | ); |
| 411 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) |
| 412 | } |
| 413 | |
| 414 | |
| 415 | |
| 416 | |
| 417 | |
| 418 | pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> { |
| 419 | Cookie::build(("session", value)) |
| 420 | .path("/") |
| 421 | .http_only(true) |
| 422 | .secure(secure) |
| 423 | |
| 424 | |
| 425 | |
| 426 | .same_site(SameSite::Lax) |
| 427 | .max_age(time::Duration::days(SESSION_DURATION_DAYS)) |
| 428 | .build() |
| 429 | } |
| 430 | |
| 431 | |
| 432 | |
| 433 | #[utoipa::path( |
| 434 | post, |
| 435 | path = "/logout", |
| 436 | tag = "auth", |
| 437 | responses((status = 204, description = "Logged out (no-op without a session)")), |
| 438 | )] |
| 439 | async fn logout( |
| 440 | State(st): State<AppState>, |
| 441 | jar: CookieJar, |
| 442 | ) -> Result<(CookieJar, StatusCode), AppError> { |
| 443 | |
| 444 | |
| 445 | |
| 446 | if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { |
| 447 | if prefix == BUILDER_COOKIE_PREFIX { |
| 448 | crate::service::builder::delete_by_token(&st.db, token).await?; |
| 449 | } else if prefix == PERSON_COOKIE_PREFIX { |
| 450 | service::person::delete_session_by_token(&st.db, token).await?; |
| 451 | } else if let Ok(id) = SchoolId::try_parse(prefix) |
| 452 | && let Ok(db) = st.tenants.get(&id).await |
| 453 | { |
| 454 | service::session::delete_by_token(&db, token).await?; |
| 455 | } |
| 456 | } |
| 457 | let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); |
| 458 | Ok((jar, StatusCode::NO_CONTENT)) |
| 459 | } |
| 460 | |
| 461 | |
| 462 | #[utoipa::path( |
| 463 | get, |
| 464 | path = "/me", |
| 465 | tag = "auth", |
| 466 | security(("session_cookie" = [])), |
| 467 | responses( |
| 468 | (status = 200, description = "The current user", body = UserResponse), |
| 469 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 470 | ), |
| 471 | )] |
| 472 | async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> { |
| 473 | Json(UserResponse::new(&user)) |
| 474 | } |