summaryrefslogtreecommitdiff
path: root/src/login/extract/login.rs
blob: 405aea82c8090ea883f57cf07e22951c28b09e52 (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
use axum::{
    extract::{FromRequestParts, State},
    http::{request::Parts, StatusCode},
    response::{IntoResponse, Response},
};
use sqlx::sqlite::SqlitePool;

use crate::{
    clock::RequestedAt,
    error::InternalError,
    login::{
        extract::IdentityToken,
        repo::{logins::Login, tokens::Provider as _},
    },
};

#[async_trait::async_trait]
impl FromRequestParts<SqlitePool> for Login {
    type Rejection = LoginError<InternalError>;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &SqlitePool,
    ) -> Result<Self, Self::Rejection> {
        // After Rust 1.82 (and #[feature(min_exhaustive_patterns)] lands on
        // stable), the following can be replaced:
        //
        // let Ok(identity_token) = IdentityToken::from_request_parts(parts, state).await;
        let identity_token = IdentityToken::from_request_parts(parts, state).await?;
        let RequestedAt(requested_at) = RequestedAt::from_request_parts(parts, state).await?;

        let token = identity_token.token().ok_or(LoginError::Forbidden)?;

        let db = State::<SqlitePool>::from_request_parts(parts, state).await?;
        let mut tx = db.begin().await?;
        tx.tokens().expire(requested_at).await?;
        let login = tx.tokens().validate(token, requested_at).await?;
        tx.commit().await?;

        login.ok_or(LoginError::Forbidden)
    }
}

pub enum LoginError<E> {
    Failure(E),
    Forbidden,
}

impl<E> IntoResponse for LoginError<E>
where
    E: IntoResponse,
{
    fn into_response(self) -> Response {
        match self {
            Self::Forbidden => (StatusCode::FORBIDDEN, "forbidden").into_response(),
            Self::Failure(e) => e.into_response(),
        }
    }
}

impl<E> From<E> for LoginError<InternalError>
where
    E: Into<InternalError>,
{
    fn from(err: E) -> Self {
        Self::Failure(err.into())
    }
}