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
|
//! Extractors for using in routes. See [Wrap]
//!
//! Extractors in this module:
//! - `Wrap<Session>`
//! - `Option<Wrap<Session>>`
use std::ops::Deref;
use axum::{
extract::{FromRequestParts, OptionalFromRequestParts},
http::{HeaderValue, header, request::Parts},
};
use somethings::auth::Session;
use crate::{RuntimeError, state::SplormState};
/// A wrapped around an external type, allowing us to implement
/// traits like [FromRequestParts] on them.
///
/// Can be dereferenced to the wrapped type.
pub struct Wrap<T>(pub T);
impl<T> Deref for Wrap<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl FromRequestParts<SplormState> for Wrap<Session> {
type Rejection = RuntimeError;
async fn from_request_parts(
parts: &mut Parts,
state: &SplormState,
) -> Result<Self, Self::Rejection> {
let sid_str = sid_from_cookie_header(parts.headers.get(header::COOKIE))?;
let session = knowing::get_session(state.database(), sid_str)
.await
.map_err(|_| RuntimeError::InvalidSession)?;
Ok(Wrap(session))
}
}
impl OptionalFromRequestParts<SplormState> for Wrap<Session> {
type Rejection = RuntimeError;
async fn from_request_parts(
parts: &mut Parts,
state: &SplormState,
) -> Result<Option<Self>, Self::Rejection> {
match sid_from_cookie_header(parts.headers.get(header::COOKIE)) {
Err(_) => return Ok(None),
Ok(sid_str) => {
let session_result = knowing::get_session(state.database(), sid_str).await;
match session_result {
Ok(session) => Ok(Some(Wrap(session))),
Err(knowing::Error::DatabaseError(dbe)) => Err(dbe.into()),
_ => Ok(None),
}
}
}
}
}
fn sid_from_cookie_header(cookie_header: Option<&HeaderValue>) -> Result<&str, RuntimeError> {
let cookie = gny::web::cookie::parse_header(
cookie_header
.ok_or(RuntimeError::InvalidSession)?
.to_str()
.map_err(|_| RuntimeError::InvalidSession)?,
)
.map_err(|_| RuntimeError::InvalidSession)?;
Ok(cookie.get("sid").ok_or(RuntimeError::InvalidSession)?)
}
|