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

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

#[cfg(test)]
mod test;

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

    let identity = identity.clear();
    Ok((identity, Empty))
}

// 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 => Unauthorized.into_response(),
            app::ValidateError::Failed(_) => Internal::from(error).into_response(),
        }
    }
}