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
use crate::prelude::*;
use rocket::http::{Cookies, Status};
use rocket::request::{FromRequest, Outcome, Request};
use serde_json::{from_str};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
pub id: i32,
pub email: String,
pub auth_key: String,
pub time_stamp: i32,
}
impl<'a, 'r> FromRequest<'a, 'r> for Session {
type Error = Error;
fn from_request(request: &'a Request<'r>) -> Outcome<Session, Self::Error> {
let mut cookies = request.cookies();
if let Some(session) = get_session(&mut cookies) {
Outcome::Success(session)
} else {
Outcome::Failure((
Status::Unauthorized,
Error::UnauthorizedError
))
}
}
}
fn get_session(cookies: &mut Cookies) -> Option<Session> {
let session = cookies.get_private("rocket_auth")?;
from_str(&session.value()).ok()
}