-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathuser.rs
77 lines (67 loc) · 1.6 KB
/
user.rs
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
use super::*;
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct User {
id: String,
mail: String,
}
impl User {
pub(crate) fn id(self) -> String {
self.id
}
pub(crate) fn mail(&self) -> &str {
&self.mail
}
#[cfg(test)]
pub(crate) fn new(id: &str, mail: &str) -> Self {
User {
id: String::from(id),
mail: String::from(mail),
}
}
}
#[derive(Serialize, Deserialize)]
struct UserResponse {
user: Option<User>,
}
pub(crate) async fn get_user(user: Option<User>) -> impl IntoResponse {
Json(UserResponse { user })
}
#[async_trait]
impl<S> FromRequestParts<S> for User
where
MongodbSessionStore: FromRef<S>,
S: Send + Sync,
{
type Rejection = AuthRedirect;
async fn from_request_parts(
parts: &mut Parts,
state: &S,
) -> Result<Self, Self::Rejection> {
let session_store = MongodbSessionStore::from_ref(state);
let cookies =
parts.extract::<TypedHeader<Cookie>>().await.map_err(|e| {
match *e.name() {
header::COOKIE => match e.reason() {
TypedHeaderRejectionReason::Missing => AuthRedirect,
_ => {
error!("Unexpected error getting cookie header(s): {}", e);
AuthRedirect
}
},
_ => {
error!("Unexpected error getting cookies: {}", e);
AuthRedirect
}
}
})?;
Ok(
session_store
.load_session(cookies.get(COOKIE_NAME).ok_or(AuthRedirect)?.to_owned())
.await
.unwrap()
.ok_or(AuthRedirect)?
.get::<User>("user")
.ok_or(AuthRedirect)?,
)
}
}