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
|
use crate::{
database::{Database, User},
routes::ui::error::MyError,
};
use anyhow::anyhow;
use rocket::{
outcome::Outcome,
request::{self, FromRequest},
Request, State,
};
pub struct Session {
pub user: User,
}
impl Session {
pub async fn from_request_ut(req: &Request<'_>) -> Result<Self, MyError> {
let cookie = req
.cookies()
.get_private("user")
.ok_or(anyhow!("login required"))?;
let username = cookie.value();
let db = req.guard::<&State<Database>>().await.unwrap();
let user = db
.users
.get(&username.to_string())?
.ok_or(anyhow!("user not found"))?;
Ok(Session { user })
}
}
impl<'r> FromRequest<'r> for Session {
type Error = MyError;
fn from_request<'life0, 'async_trait>(
request: &'r Request<'life0>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<Output = request::Outcome<Self, Self::Error>>
+ core::marker::Send
+ 'async_trait,
>,
>
where
'r: 'async_trait,
'life0: 'async_trait,
Self: 'async_trait,
{
Box::pin(async move {
match Self::from_request_ut(request).await {
Ok(x) => Outcome::Success(x),
Err(_) => Outcome::Forward(()),
}
})
}
}
|