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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
|
use axum::{
extract::{FromRef, FromRequestParts, OptionalFromRequestParts, State},
http::request::Parts,
response::{IntoResponse, Response},
};
use super::IdentityCookie;
use crate::{
clock::RequestedAt,
error::{Internal, Unauthorized},
login::Login,
token::{
Token,
app::{Tokens, ValidateError},
},
};
#[derive(Clone, Debug)]
pub struct Identity {
pub token: Token,
pub login: Login,
}
impl<App> FromRequestParts<App> for Identity
where
Tokens: FromRef<App>,
App: Send + Sync,
{
type Rejection = LoginError<Internal>;
async fn from_request_parts(parts: &mut Parts, state: &App) -> Result<Self, Self::Rejection> {
let Ok(cookie) = IdentityCookie::from_request_parts(parts, state).await;
let RequestedAt(used_at) = RequestedAt::from_request_parts(parts, state).await?;
let secret = cookie.secret().ok_or(LoginError::Unauthorized)?;
let tokens = State::<Tokens>::from_request_parts(parts, state).await?;
tokens
.validate(&secret, &used_at)
.await
.map_err(|err| match err {
ValidateError::InvalidToken => LoginError::Unauthorized,
other => other.into(),
})
}
}
impl<App> OptionalFromRequestParts<App> for Identity
where
Tokens: FromRef<App>,
App: Send + Sync,
{
type Rejection = LoginError<Internal>;
async fn from_request_parts(
parts: &mut Parts,
state: &App,
) -> Result<Option<Self>, Self::Rejection> {
match <Self as FromRequestParts<App>>::from_request_parts(parts, state).await {
Ok(identity) => Ok(Some(identity)),
Err(LoginError::Unauthorized) => Ok(None),
Err(other) => Err(other),
}
}
}
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 => Unauthorized.into_response(),
Self::Failure(e) => e.into_response(),
}
}
}
impl<E> From<E> for LoginError<Internal>
where
E: Into<Internal>,
{
fn from(err: E) -> Self {
Self::Failure(err.into())
}
}
|