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
|
use axum::{
extract::{FromRequestParts, State},
http::{request::Parts, StatusCode},
response::{IntoResponse, Response},
};
use super::Login;
use crate::{
app::App,
clock::RequestedAt,
error::InternalError,
login::{app::ValidateError, extract::IdentityToken},
};
#[async_trait::async_trait]
impl FromRequestParts<App> for Login {
type Rejection = LoginError<InternalError>;
async fn from_request_parts(parts: &mut Parts, state: &App) -> 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(used_at) = RequestedAt::from_request_parts(parts, state).await?;
let secret = identity_token.secret().ok_or(LoginError::Unauthorized)?;
let app = State::<App>::from_request_parts(parts, state).await?;
match app.logins().validate(secret, used_at).await {
Ok(login) => Ok(login),
Err(ValidateError::InvalidToken) => Err(LoginError::Unauthorized),
Err(other) => Err(other.into()),
}
}
}
pub enum LoginError<E> {
Failure(E),
Unauthorized,
}
impl<E> IntoResponse for LoginError<E>
where
E: IntoResponse,
{
fn into_response(self) -> Response {
match self {
Self::Unauthorized => (StatusCode::UNAUTHORIZED, "unauthorized").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())
}
}
|