| 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::Slug; |
| 20 | |
| 21 | use super::dto::Role; |
| 22 | use super::tenant_state::split_cookie; |
| 23 | use super::{BUILDER_COOKIE_PREFIX, CurrentUser, 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(), state.db_up.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!(logout)) |
| 44 | .routes(routes!(me)) |
| 45 | } |
| 46 | |
| 47 | #[derive(Deserialize, ToSchema)] |
| 48 | struct Credentials { |
| 49 | |
| 50 | |
| 51 | |
| 52 | #[schema(example = "demo", min_length = 2, max_length = 32)] |
| 53 | school: String, |
| 54 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| 55 | username: String, |
| 56 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 57 | password: String, |
| 58 | } |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | |
| 66 | #[derive(Serialize, ToSchema)] |
| 67 | struct RegisterResponse { |
| 68 | #[schema(example = "ada")] |
| 69 | username: String, |
| 70 | role: Role, |
| 71 | } |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | |
| 81 | |
| 82 | |
| 83 | |
| 84 | |
| 85 | #[utoipa::path( |
| 86 | post, |
| 87 | path = "/register", |
| 88 | tag = "auth", |
| 89 | request_body = Credentials, |
| 90 | responses( |
| 91 | (status = 201, description = "Account created, or the username was already taken — 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), |
| 92 | (status = 400, description = "Invalid username or password", body = ErrorResponse), |
| 93 | (status = 401, description = "No such school — deliberately the same answer a bad credential gets", body = ErrorResponse), |
| 94 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| 95 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 96 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 97 | ), |
| 98 | )] |
| 99 | async fn register( |
| 100 | State(st): State<AppState>, |
| 101 | Json(req): Json<Credentials>, |
| 102 | ) -> Result<(StatusCode, Json<RegisterResponse>), AppError> { |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; |
| 108 | let db = st.tenants.get(&school).await?; |
| 109 | let username = Username::try_new(&req.username)?; |
| 110 | |
| 111 | |
| 112 | |
| 113 | if RESERVED_USERNAMES.contains(&username.as_str()) { |
| 114 | return Err(ValidationError::Invalid { |
| 115 | field: "username", |
| 116 | reason: "this username is reserved", |
| 117 | } |
| 118 | .into()); |
| 119 | } |
| 120 | |
| 121 | |
| 122 | |
| 123 | |
| 124 | |
| 125 | let password_hash = Password::try_new(&req.password)?.hash_async().await?; |
| 126 | |
| 127 | |
| 128 | |
| 129 | |
| 130 | let body = RegisterResponse { |
| 131 | username: username.as_str().to_string(), |
| 132 | role: DomainRole::Student.into(), |
| 133 | }; |
| 134 | match crate::service::user::create(&db, username, password_hash).await { |
| 135 | Ok(_) => {} |
| 136 | |
| 137 | |
| 138 | |
| 139 | Err(AppError::Conflict(_)) => { |
| 140 | tracing::info!("register: username already taken, answering 201"); |
| 141 | } |
| 142 | Err(err) => return Err(err), |
| 143 | } |
| 144 | Ok((StatusCode::CREATED, Json(body))) |
| 145 | } |
| 146 | |
| 147 | |
| 148 | |
| 149 | #[utoipa::path( |
| 150 | post, |
| 151 | path = "/login", |
| 152 | tag = "auth", |
| 153 | request_body = Credentials, |
| 154 | responses( |
| 155 | (status = 200, description = "Logged in; session cookie set", body = UserResponse), |
| 156 | (status = 401, description = "Bad credentials, or no such school — deliberately indistinguishable", body = ErrorResponse), |
| 157 | (status = 403, description = "The school is suspended", body = ErrorResponse), |
| 158 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 159 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 160 | ), |
| 161 | )] |
| 162 | async fn login( |
| 163 | State(st): State<AppState>, |
| 164 | jar: CookieJar, |
| 165 | Json(req): Json<Credentials>, |
| 166 | ) -> Result<(CookieJar, Json<UserResponse>), AppError> { |
| 167 | |
| 168 | |
| 169 | |
| 170 | |
| 171 | |
| 172 | let school = Slug::try_new(&req.school).map_err(|_| AppError::Unauthorized)?; |
| 173 | let db = st.tenants.get(&school).await?; |
| 174 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 175 | |
| 176 | |
| 177 | let user = match crate::service::user::find_by_username(&db, req.username.trim()).await? { |
| 178 | |
| 179 | |
| 180 | |
| 181 | Some(user) => { |
| 182 | if !user.get_password_hash().verify_async(&password).await { |
| 183 | return Err(AppError::Unauthorized); |
| 184 | } |
| 185 | user |
| 186 | } |
| 187 | None => { |
| 188 | |
| 189 | |
| 190 | |
| 191 | PasswordHash::verify_decoy_async(&password).await; |
| 192 | return Err(AppError::Unauthorized); |
| 193 | } |
| 194 | }; |
| 195 | |
| 196 | |
| 197 | let _ = service::session::purge_expired(&db).await; |
| 198 | |
| 199 | let session = service::session::create(&db, user.get_id()).await?; |
| 200 | |
| 201 | |
| 202 | let cookie = session_cookie( |
| 203 | format!("{school}.{}", session.token().as_str()), |
| 204 | st.cookie_secure, |
| 205 | ); |
| 206 | |
| 207 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) |
| 208 | } |
| 209 | |
| 210 | |
| 211 | |
| 212 | |
| 213 | |
| 214 | pub(crate) fn session_cookie(value: String, secure: bool) -> Cookie<'static> { |
| 215 | Cookie::build(("session", value)) |
| 216 | .path("/") |
| 217 | .http_only(true) |
| 218 | .secure(secure) |
| 219 | |
| 220 | |
| 221 | |
| 222 | .same_site(SameSite::Lax) |
| 223 | .max_age(time::Duration::days(SESSION_DURATION_DAYS)) |
| 224 | .build() |
| 225 | } |
| 226 | |
| 227 | |
| 228 | |
| 229 | #[utoipa::path( |
| 230 | post, |
| 231 | path = "/logout", |
| 232 | tag = "auth", |
| 233 | responses((status = 204, description = "Logged out (no-op without a session)")), |
| 234 | )] |
| 235 | async fn logout( |
| 236 | State(st): State<AppState>, |
| 237 | jar: CookieJar, |
| 238 | ) -> Result<(CookieJar, StatusCode), AppError> { |
| 239 | |
| 240 | |
| 241 | |
| 242 | if let Some((prefix, token)) = jar.get("session").and_then(|c| split_cookie(c.value())) { |
| 243 | if prefix == BUILDER_COOKIE_PREFIX { |
| 244 | crate::service::builder::delete_by_token(&st.db, token).await?; |
| 245 | } else if let Ok(slug) = Slug::try_new(prefix) |
| 246 | && let Ok(db) = st.tenants.get(&slug).await |
| 247 | { |
| 248 | service::session::delete_by_token(&db, token).await?; |
| 249 | } |
| 250 | } |
| 251 | let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); |
| 252 | Ok((jar, StatusCode::NO_CONTENT)) |
| 253 | } |
| 254 | |
| 255 | |
| 256 | #[utoipa::path( |
| 257 | get, |
| 258 | path = "/me", |
| 259 | tag = "auth", |
| 260 | security(("session_cookie" = [])), |
| 261 | responses( |
| 262 | (status = 200, description = "The current user", body = UserResponse), |
| 263 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 264 | ), |
| 265 | )] |
| 266 | async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> { |
| 267 | Json(UserResponse::new(&user)) |
| 268 | } |