Skip to main content

web/
login.rs

1use std::sync::Arc;
2
3use askama::Template;
4use axum::{
5    Json,
6    body::Body,
7    extract::State,
8    http::{HeaderMap, HeaderValue, Request, StatusCode, header},
9    middleware::Next,
10    response::{Html, IntoResponse, Response},
11};
12use rust_i18n::t;
13use serde_json::json;
14
15use crate::{
16    AppState,
17    error_render::adopt_rejection,
18    model::LoginUserSchema,
19    response::WebError,
20    session::{append_set_cookies, mint_token, save_token_data_to_redis, session_cookies},
21    token::TokenType,
22};
23
24/// The login page, optionally re-shown with a failure and the submitted email.
25#[derive(Template, Default)]
26#[template(path = "pages/login.html")]
27pub struct LoginTemplate {
28    pub error: Option<String>,
29    pub email: String,
30}
31
32/// Renders the login page with `status`; the password is never put back.
33fn login_page(status: StatusCode, error: Option<&str>, email: &str) -> Response {
34    let page = LoginTemplate {
35        error: error.map(str::to_string),
36        email: email.to_string(),
37    };
38    match page.render() {
39        Ok(html) => (status, Html(html)).into_response(),
40        Err(e) => WebError::internal("Rendering the login page failed", e).into_response(),
41    }
42}
43
44struct LoginCookies {
45    cookies: [String; 2],
46    access_token: String,
47}
48
49async fn authenticate_user(
50    data: &Arc<AppState>,
51    email: &str,
52    password: &str,
53) -> Result<LoginCookies, WebError> {
54    let verified = server::command::user::verify_user_password(email, password)
55        .await
56        .map_err(WebError::from)?
57        .ok_or_else(|| WebError::unauthorized(t!("Invalid email or password").to_string()))?;
58
59    let access = mint_token(
60        verified.user_id,
61        data.conf.access_token_max_age,
62        TokenType::Access,
63        verified.generation,
64    )
65    .await?;
66    let refresh = mint_token(
67        verified.user_id,
68        data.conf.refresh_token_max_age,
69        TokenType::Refresh,
70        verified.generation,
71    )
72    .await?;
73
74    save_token_data_to_redis(data, &access, data.conf.access_token_max_age).await?;
75    save_token_data_to_redis(data, &refresh, data.conf.refresh_token_max_age).await?;
76
77    let access_token = access.token.unwrap_or_default();
78    Ok(LoginCookies {
79        cookies: session_cookies(
80            &data.conf,
81            access_token.clone(),
82            refresh.token.unwrap_or_default(),
83        ),
84        access_token,
85    })
86}
87
88fn cookie_headers(cookies: LoginCookies) -> (HeaderMap, String) {
89    let mut headers = HeaderMap::new();
90    append_set_cookies(&mut headers, cookies.cookies);
91    (headers, cookies.access_token)
92}
93
94pub async fn login_user_handler(
95    State(data): State<Arc<AppState>>,
96    Json(body): Json<LoginUserSchema>,
97) -> Result<impl IntoResponse, WebError> {
98    let (mut headers, access_token) =
99        cookie_headers(authenticate_user(&data, &body.email, &body.password).await?);
100    headers.append("HX-Redirect", HeaderValue::from_static("/"));
101    Ok((
102        headers,
103        Json(json!({"status": "success", "access_token": access_token})),
104    ))
105}
106
107/// The native login form: the one POST that answers a failure by showing itself again.
108pub async fn login_form_handler(
109    State(data): State<Arc<AppState>>,
110    axum::Form(body): axum::Form<LoginUserSchema>,
111) -> Response {
112    match authenticate_user(&data, &body.email, &body.password).await {
113        Ok(cookies) => {
114            let (mut headers, _) = cookie_headers(cookies);
115            headers.insert(header::LOCATION, HeaderValue::from_static("/"));
116            (StatusCode::SEE_OTHER, headers).into_response()
117        }
118        Err(error) => login_page(error.status, Some(&error.message), &body.email),
119    }
120}
121
122/// Re-shows the login page for a failure raised outside the handler, such as the throttle.
123pub async fn reshow_login(req: Request<Body>, next: Next) -> Response {
124    let response = adopt_rejection(next.run(req).await).await;
125    match response.extensions().get::<WebError>() {
126        Some(error) => login_page(error.status, Some(&error.message), ""),
127        None => response,
128    }
129}
130
131#[cfg(test)]
132#[path = "login_tests.rs"]
133mod tests;