1
use std::sync::Arc;
2

            
3
use askama::Template;
4
use 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
};
12
use rust_i18n::t;
13
use serde_json::json;
14

            
15
use 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")]
27
pub 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.
33
22
fn login_page(status: StatusCode, error: Option<&str>, email: &str) -> Response {
34
22
    let page = LoginTemplate {
35
22
        error: error.map(str::to_string),
36
22
        email: email.to_string(),
37
22
    };
38
22
    match page.render() {
39
22
        Ok(html) => (status, Html(html)).into_response(),
40
        Err(e) => WebError::internal("Rendering the login page failed", e).into_response(),
41
    }
42
22
}
43

            
44
struct LoginCookies {
45
    cookies: [String; 2],
46
    access_token: String,
47
}
48

            
49
12
async fn authenticate_user(
50
12
    data: &Arc<AppState>,
51
12
    email: &str,
52
12
    password: &str,
53
12
) -> Result<LoginCookies, WebError> {
54
12
    let verified = server::command::user::verify_user_password(email, password)
55
12
        .await
56
12
        .map_err(WebError::from)?
57
12
        .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
12
}
87

            
88
2
fn cookie_headers(cookies: LoginCookies) -> (HeaderMap, String) {
89
2
    let mut headers = HeaderMap::new();
90
2
    append_set_cookies(&mut headers, cookies.cookies);
91
2
    (headers, cookies.access_token)
92
2
}
93

            
94
1
pub async fn login_user_handler(
95
1
    State(data): State<Arc<AppState>>,
96
1
    Json(body): Json<LoginUserSchema>,
97
1
) -> Result<impl IntoResponse, WebError> {
98
    let (mut headers, access_token) =
99
1
        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
1
}
106

            
107
/// The native login form: the one POST that answers a failure by showing itself again.
108
11
pub async fn login_form_handler(
109
11
    State(data): State<Arc<AppState>>,
110
11
    axum::Form(body): axum::Form<LoginUserSchema>,
111
11
) -> Response {
112
11
    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
11
        Err(error) => login_page(error.status, Some(&error.message), &body.email),
119
    }
120
11
}
121

            
122
/// Re-shows the login page for a failure raised outside the handler, such as the throttle.
123
18
pub async fn reshow_login(req: Request<Body>, next: Next) -> Response {
124
18
    let response = adopt_rejection(next.run(req).await).await;
125
18
    match response.extensions().get::<WebError>() {
126
5
        Some(error) => login_page(error.status, Some(&error.message), ""),
127
13
        None => response,
128
    }
129
18
}
130

            
131
#[cfg(test)]
132
#[path = "login_tests.rs"]
133
mod tests;