summaryrefslogtreecommitdiff
path: root/src/login/routes.rs
blob: 816926ed6ddaf91ce50e829e69bcd9a98cb54110 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use axum::{
    extract::{Form, State},
    http::StatusCode,
    response::{IntoResponse, Redirect, Response},
    routing::post,
    Router,
};

use crate::{app::App, clock::RequestedAt, error::InternalError};

use super::extract::IdentityToken;

pub fn router() -> Router<App> {
    Router::new()
        .route("/login", post(on_login))
        .route("/logout", post(on_logout))
}

#[derive(serde::Deserialize)]
struct LoginRequest {
    name: String,
    password: String,
}

async fn on_login(
    State(app): State<App>,
    RequestedAt(now): RequestedAt,
    identity: IdentityToken,
    Form(form): Form<LoginRequest>,
) -> Result<impl IntoResponse, InternalError> {
    let token = app.logins().login(&form.name, &form.password, now).await?;

    let resp = if let Some(token) = token {
        let identity = identity.set(&token);
        (identity, LoginResponse::Successful)
    } else {
        (identity, LoginResponse::Rejected)
    };

    Ok(resp)
}

enum LoginResponse {
    Rejected,
    Successful,
}

impl IntoResponse for LoginResponse {
    fn into_response(self) -> Response {
        match self {
            Self::Rejected => {
                (StatusCode::UNAUTHORIZED, "invalid name or password").into_response()
            }
            Self::Successful => Redirect::to("/").into_response(),
        }
    }
}

async fn on_logout(
    State(app): State<App>,
    identity: IdentityToken,
) -> Result<impl IntoResponse, InternalError> {
    if let Some(secret) = identity.secret() {
        app.logins().logout(secret).await?;
    }

    let identity = identity.clear();

    Ok((identity, Redirect::to("/")))
}