Skip to main content

warp_sessions/
request.rs

1use super::{CookieOptions, Session, SessionError, SessionStore, SessionWithStore};
2use warp::{Filter, Rejection};
3
4/// This function builds a filter from a SessionStore and a set of
5/// cookie options for the session. The filter pulls the cookie with
6/// name 'sid' from the request and uses the passed in session store
7/// to retrieve the session. It returns the session for use by the
8/// downstream session handler.
9pub fn with_session<T: SessionStore>(
10    session_store: T,
11    cookie_options: Option<CookieOptions>,
12) -> impl Filter<Extract = (SessionWithStore<T>,), Error = Rejection> + Clone {
13    let cookie_options = match cookie_options {
14        Some(co) => co,
15        None => {
16            let mut co = CookieOptions::default();
17            co.cookie_name = "sid";
18            co
19        }
20    };
21    warp::any()
22        .and(warp::any().map(move || session_store.clone()))
23        .and(warp::cookie::optional(cookie_options.cookie_name))
24        .and(warp::any().map(move || cookie_options.clone()))
25        .and_then(
26	    |session_store: T,
27	    sid_cookie: Option<String>,
28	    cookie_options: CookieOptions| async move {
29                match sid_cookie {
30		    Some(sid) => match session_store.load_session(sid).await {
31                        Ok(Some(session)) => {
32			    Ok::<_, Rejection>(SessionWithStore {
33                                session,
34                                session_store,
35				cookie_options,
36			    })
37                        }
38                        Ok(None) => {
39			    Ok::<_, Rejection>(SessionWithStore {
40                                session: Session::new(),
41                                session_store,
42				cookie_options,
43			    })
44                        }
45                        Err(source) => Err(Rejection::from(SessionError::LoadError { source })),
46		    },
47		    None => {
48                        Ok::<_, Rejection>(SessionWithStore {
49			    session: Session::new(),
50			    session_store,
51			    cookie_options,
52                        })
53		    }
54                }
55	    },
56        )
57}