| 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::session::Session; |
| 15 | use crate::domain::user::{Password, PasswordHash, User, Username}; |
| 16 | use crate::error::{AppError, ErrorResponse, ValidationError}; |
| 17 | use crate::rate_limit::{RateLimitConfig, RateLimiter}; |
| 18 | use crate::state::AppState; |
| 19 | |
| 20 | use super::dto::Role; |
| 21 | use super::{CurrentUser, UserResponse}; |
| 22 | |
| 23 | pub fn routes(state: &AppState) -> OpenApiRouter<AppState> { |
| 24 | |
| 25 | |
| 26 | |
| 27 | |
| 28 | let rate_limit: &RateLimitConfig = &state.rate_limit; |
| 29 | let limiter = RateLimiter::per_minute(rate_limit.auth_per_minute, rate_limit.trust_proxy); |
| 30 | |
| 31 | |
| 32 | limiter.share("auth", state.db.clone(), state.db_up.clone()); |
| 33 | OpenApiRouter::new() |
| 34 | .routes(routes!(register)) |
| 35 | .routes(routes!(login)) |
| 36 | |
| 37 | .route_layer(middleware::from_fn(move |req: Request, next: Next| { |
| 38 | let limiter = limiter.clone(); |
| 39 | async move { limiter.enforce(req, next).await } |
| 40 | })) |
| 41 | .routes(routes!(logout)) |
| 42 | .routes(routes!(me)) |
| 43 | } |
| 44 | |
| 45 | #[derive(Deserialize, ToSchema)] |
| 46 | struct Credentials { |
| 47 | #[schema(example = "ada", min_length = 3, max_length = 32)] |
| 48 | username: String, |
| 49 | #[schema(example = "correct horse battery", min_length = 6, max_length = 128)] |
| 50 | password: String, |
| 51 | } |
| 52 | |
| 53 | |
| 54 | |
| 55 | |
| 56 | |
| 57 | |
| 58 | |
| 59 | #[derive(Serialize, ToSchema)] |
| 60 | struct RegisterResponse { |
| 61 | #[schema(example = "ada")] |
| 62 | username: String, |
| 63 | role: Role, |
| 64 | } |
| 65 | |
| 66 | |
| 67 | |
| 68 | |
| 69 | |
| 70 | |
| 71 | |
| 72 | |
| 73 | |
| 74 | |
| 75 | |
| 76 | #[utoipa::path( |
| 77 | post, |
| 78 | path = "/register", |
| 79 | tag = "auth", |
| 80 | request_body = Credentials, |
| 81 | responses( |
| 82 | (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), |
| 83 | (status = 400, description = "Invalid username or password", body = ErrorResponse), |
| 84 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 85 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 86 | ), |
| 87 | )] |
| 88 | async fn register( |
| 89 | State(st): State<AppState>, |
| 90 | Json(req): Json<Credentials>, |
| 91 | ) -> Result<(StatusCode, Json<RegisterResponse>), AppError> { |
| 92 | let username = Username::try_new(&req.username)?; |
| 93 | |
| 94 | |
| 95 | |
| 96 | if RESERVED_USERNAMES.contains(&username.as_str()) { |
| 97 | return Err(ValidationError::Invalid { |
| 98 | field: "username", |
| 99 | reason: "this username is reserved", |
| 100 | } |
| 101 | .into()); |
| 102 | } |
| 103 | |
| 104 | |
| 105 | |
| 106 | |
| 107 | let password_hash = Password::try_new(&req.password)?.hash_async().await?; |
| 108 | |
| 109 | |
| 110 | |
| 111 | |
| 112 | let body = RegisterResponse { |
| 113 | username: username.as_str().to_string(), |
| 114 | role: DomainRole::Student.into(), |
| 115 | }; |
| 116 | match User::create(username, password_hash, &st.db).await { |
| 117 | Ok(_) => {} |
| 118 | |
| 119 | |
| 120 | |
| 121 | Err(AppError::Conflict(_)) => { |
| 122 | tracing::info!("register: username already taken, answering 201"); |
| 123 | } |
| 124 | Err(err) => return Err(err), |
| 125 | } |
| 126 | Ok((StatusCode::CREATED, Json(body))) |
| 127 | } |
| 128 | |
| 129 | |
| 130 | #[utoipa::path( |
| 131 | post, |
| 132 | path = "/login", |
| 133 | tag = "auth", |
| 134 | request_body = Credentials, |
| 135 | responses( |
| 136 | (status = 200, description = "Logged in; session cookie set", body = UserResponse), |
| 137 | (status = 401, description = "Bad credentials", body = ErrorResponse), |
| 138 | (status = 429, description = "Too many attempts from this address; see Retry-After", body = ErrorResponse), |
| 139 | (status = 422, description = "The body does not fit this request: a field has the wrong type, or a required field is missing"), |
| 140 | ), |
| 141 | )] |
| 142 | async fn login( |
| 143 | State(st): State<AppState>, |
| 144 | jar: CookieJar, |
| 145 | Json(req): Json<Credentials>, |
| 146 | ) -> Result<(CookieJar, Json<UserResponse>), AppError> { |
| 147 | let password = Password::try_new(&req.password).map_err(|_| AppError::Unauthorized)?; |
| 148 | |
| 149 | |
| 150 | let user = match User::find_by_username(req.username.trim(), &st.db).await? { |
| 151 | |
| 152 | |
| 153 | |
| 154 | Some(user) => { |
| 155 | if !user.get_password_hash().verify_async(&password).await { |
| 156 | return Err(AppError::Unauthorized); |
| 157 | } |
| 158 | user |
| 159 | } |
| 160 | None => { |
| 161 | |
| 162 | |
| 163 | |
| 164 | PasswordHash::verify_decoy_async(&password).await; |
| 165 | return Err(AppError::Unauthorized); |
| 166 | } |
| 167 | }; |
| 168 | |
| 169 | |
| 170 | let _ = Session::purge_expired(&st.db).await; |
| 171 | |
| 172 | let session = Session::create(user.get_id(), &st.db).await?; |
| 173 | let cookie = Cookie::build(("session", session.token().as_str().to_string())) |
| 174 | .path("/") |
| 175 | .http_only(true) |
| 176 | .secure(st.cookie_secure) |
| 177 | |
| 178 | |
| 179 | |
| 180 | .same_site(SameSite::Lax) |
| 181 | .max_age(time::Duration::days(SESSION_DURATION_DAYS)) |
| 182 | .build(); |
| 183 | |
| 184 | Ok((jar.add(cookie), Json(UserResponse::new(&user)))) |
| 185 | } |
| 186 | |
| 187 | |
| 188 | |
| 189 | #[utoipa::path( |
| 190 | post, |
| 191 | path = "/logout", |
| 192 | tag = "auth", |
| 193 | responses((status = 204, description = "Logged out (no-op without a session)")), |
| 194 | )] |
| 195 | async fn logout( |
| 196 | State(st): State<AppState>, |
| 197 | jar: CookieJar, |
| 198 | ) -> Result<(CookieJar, StatusCode), AppError> { |
| 199 | if let Some(cookie) = jar.get("session") { |
| 200 | Session::delete_by_token(cookie.value(), &st.db).await?; |
| 201 | } |
| 202 | let jar = jar.remove(Cookie::build(("session", "")).path("/").build()); |
| 203 | Ok((jar, StatusCode::NO_CONTENT)) |
| 204 | } |
| 205 | |
| 206 | |
| 207 | #[utoipa::path( |
| 208 | get, |
| 209 | path = "/me", |
| 210 | tag = "auth", |
| 211 | security(("session_cookie" = [])), |
| 212 | responses( |
| 213 | (status = 200, description = "The current user", body = UserResponse), |
| 214 | (status = 401, description = "Not authenticated", body = ErrorResponse), |
| 215 | ), |
| 216 | )] |
| 217 | async fn me(CurrentUser(user): CurrentUser) -> Json<UserResponse> { |
| 218 | Json(UserResponse::new(&user)) |
| 219 | } |