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
use super::{CookieOptions, Session, SessionError, SessionStore, SessionWithStore};
use warp::{Filter, Rejection};

/// This function builds a filter from a SessionStore and a set of
/// cookie options for the session. The filter pulls the cookie with
/// name 'sid' from the request and uses the passed in session store
/// to retrieve the session. It returns the session for use by the
/// downstream session handler.
pub fn with_session<T: SessionStore>(
    session_store: T,
    cookie_options: Option<CookieOptions>,
) -> impl Filter<Extract = (SessionWithStore<T>,), Error = Rejection> + Clone {
    let cookie_options = match cookie_options {
        Some(co) => co,
        None => CookieOptions::default(),
    };
    warp::any()
        .and(warp::any().map(move || session_store.clone()))
        .and(warp::cookie::optional("sid"))
        .and(warp::any().map(move || cookie_options.clone()))
        .and_then(
	    |session_store: T,
	    sid_cookie: Option<String>,
	    cookie_options: CookieOptions| async move {
                match sid_cookie {
		    Some(sid) => match session_store.load_session(sid).await {
                        Ok(Some(session)) => {
			    Ok::<_, Rejection>(SessionWithStore {
                                session,
                                session_store,
				cookie_options,
			    })
                        }
                        Ok(None) => {
			    Ok::<_, Rejection>(SessionWithStore {
                                session: Session::new(),
                                session_store,
				cookie_options,
			    })
                        }
                        Err(source) => Err(Rejection::from(SessionError::LoadError { source })),
		    },
		    None => {
                        Ok::<_, Rejection>(SessionWithStore {
			    session: Session::new(),
			    session_store,
			    cookie_options,
                        })
		    }
                }
	    },
        )
}