Lines
55.26 %
Functions
40.91 %
Branches
100 %
use std::sync::Arc;
use askama::Template;
use axum::{
Json,
body::Body,
extract::State,
http::{HeaderMap, HeaderValue, Request, StatusCode, header},
middleware::Next,
response::{Html, IntoResponse, Response},
};
use rust_i18n::t;
use serde_json::json;
use crate::{
AppState,
error_render::adopt_rejection,
model::LoginUserSchema,
response::WebError,
session::{append_set_cookies, mint_token, save_token_data_to_redis, session_cookies},
token::TokenType,
/// The login page, optionally re-shown with a failure and the submitted email.
#[derive(Template, Default)]
#[template(path = "pages/login.html")]
pub struct LoginTemplate {
pub error: Option<String>,
pub email: String,
}
/// Renders the login page with `status`; the password is never put back.
fn login_page(status: StatusCode, error: Option<&str>, email: &str) -> Response {
let page = LoginTemplate {
error: error.map(str::to_string),
email: email.to_string(),
match page.render() {
Ok(html) => (status, Html(html)).into_response(),
Err(e) => WebError::internal("Rendering the login page failed", e).into_response(),
struct LoginCookies {
cookies: [String; 2],
access_token: String,
async fn authenticate_user(
data: &Arc<AppState>,
email: &str,
password: &str,
) -> Result<LoginCookies, WebError> {
let verified = server::command::user::verify_user_password(email, password)
.await
.map_err(WebError::from)?
.ok_or_else(|| WebError::unauthorized(t!("Invalid email or password").to_string()))?;
let access = mint_token(
verified.user_id,
data.conf.access_token_max_age,
TokenType::Access,
verified.generation,
)
.await?;
let refresh = mint_token(
data.conf.refresh_token_max_age,
TokenType::Refresh,
save_token_data_to_redis(data, &access, data.conf.access_token_max_age).await?;
save_token_data_to_redis(data, &refresh, data.conf.refresh_token_max_age).await?;
let access_token = access.token.unwrap_or_default();
Ok(LoginCookies {
cookies: session_cookies(
&data.conf,
access_token.clone(),
refresh.token.unwrap_or_default(),
),
access_token,
})
fn cookie_headers(cookies: LoginCookies) -> (HeaderMap, String) {
let mut headers = HeaderMap::new();
append_set_cookies(&mut headers, cookies.cookies);
(headers, cookies.access_token)
pub async fn login_user_handler(
State(data): State<Arc<AppState>>,
Json(body): Json<LoginUserSchema>,
) -> Result<impl IntoResponse, WebError> {
let (mut headers, access_token) =
cookie_headers(authenticate_user(&data, &body.email, &body.password).await?);
headers.append("HX-Redirect", HeaderValue::from_static("/"));
Ok((
headers,
Json(json!({"status": "success", "access_token": access_token})),
))
/// The native login form: the one POST that answers a failure by showing itself again.
pub async fn login_form_handler(
axum::Form(body): axum::Form<LoginUserSchema>,
) -> Response {
match authenticate_user(&data, &body.email, &body.password).await {
Ok(cookies) => {
let (mut headers, _) = cookie_headers(cookies);
headers.insert(header::LOCATION, HeaderValue::from_static("/"));
(StatusCode::SEE_OTHER, headers).into_response()
Err(error) => login_page(error.status, Some(&error.message), &body.email),
/// Re-shows the login page for a failure raised outside the handler, such as the throttle.
pub async fn reshow_login(req: Request<Body>, next: Next) -> Response {
let response = adopt_rejection(next.run(req).await).await;
match response.extensions().get::<WebError>() {
Some(error) => login_page(error.status, Some(&error.message), ""),
None => response,
#[cfg(test)]
#[path = "login_tests.rs"]
mod tests;