summaryrefslogtreecommitdiff
path: root/src/user/handlers/logout/mod.rs
blob: 45a376a3d3e612434b1f48b696b6dcd10932d5f6 (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
use axum::{
    extract::{Json, State},
    http::StatusCode,
    response::{IntoResponse, Response},
};

use crate::{
    app::App,
    clock::RequestedAt,
    error::{Internal, Unauthorized},
    token::{app, extract::IdentityCookie},
};

#[cfg(test)]
mod test;

pub async fn handler(
    State(app): State<App>,
    RequestedAt(now): RequestedAt,
    identity: IdentityCookie,
    Json(_): Json<Request>,
) -> Result<(IdentityCookie, StatusCode), Error> {
    if let Some(secret) = identity.secret() {
        let (token, _) = app.tokens().validate(&secret, &now).await?;
        app.tokens().logout(&token).await?;
    }

    let identity = identity.clear();
    Ok((identity, StatusCode::NO_CONTENT))
}

// This forces the only valid request to be `{}`, and not the infinite
// variation allowed when there's no body extractor.
#[derive(Default, serde::Deserialize)]
pub struct Request {}

#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct Error(#[from] pub app::ValidateError);

impl IntoResponse for Error {
    fn into_response(self) -> Response {
        let Self(error) = self;
        match error {
            app::ValidateError::InvalidToken | app::ValidateError::LoginDeleted => {
                Unauthorized.into_response()
            }
            app::ValidateError::Name(_) | app::ValidateError::Database(_) => {
                Internal::from(error).into_response()
            }
        }
    }
}