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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
use std::{
    sync::{atomic::Ordering, Arc},
    time::Duration,
};

use crate::{
    async_trait,
    middleware::helper::{CookieOptions, Cookieable},
    types::{Cookie, Session},
    Error, Handler, IntoResponse, Request, RequestExt, Response, Result, StatusCode, Transform,
};

use super::{Error as SessionError, Storage, Store, PURGED, RENEWED, UNCHANGED};

pub struct Config<S, G, V>(Arc<(Store<S, G, V>, CookieOptions)>);

impl<S, G, V> Clone for Config<S, G, V> {
    fn clone(&self) -> Self {
        Self(self.0.clone())
    }
}

impl<S, G, V> Config<S, G, V> {
    pub fn new(store: Store<S, G, V>, cookie: CookieOptions) -> Self {
        Self(Arc::new((store, cookie)))
    }

    pub fn store(&self) -> &Store<S, G, V> {
        &self.0 .0
    }

    pub fn ttl(&self) -> Option<Duration> {
        self.cookie().max_age
    }
}

impl<S, G, V> Cookieable for Config<S, G, V> {
    fn cookie(&self) -> &CookieOptions {
        &self.0 .1
    }
}

impl<H, S, G, V> Transform<H> for Config<S, G, V> {
    type Output = SessionMiddleware<H, S, G, V>;

    fn transform(&self, h: H) -> Self::Output {
        SessionMiddleware {
            h,
            config: self.clone(),
        }
    }
}

pub struct SessionMiddleware<H, S, G, V> {
    h: H,
    config: Config<S, G, V>,
}

impl<H, S, G, V> Clone for SessionMiddleware<H, S, G, V>
where
    H: Clone,
{
    fn clone(&self) -> Self {
        Self {
            h: self.h.clone(),
            config: self.config.clone(),
        }
    }
}

#[async_trait]
impl<H, O, S, G, V> Handler<Request> for SessionMiddleware<H, S, G, V>
where
    O: IntoResponse,
    H: Handler<Request, Output = Result<O>> + Clone,
    S: Storage + 'static,
    G: Fn() -> String + Send + Sync + 'static,
    V: Fn(&str) -> bool + Send + Sync + 'static,
{
    type Output = Result<Response>;

    async fn call(&self, mut req: Request) -> Self::Output {
        let cookies = req.cookies().map_err(Into::<Error>::into)?;
        let cookie = self.config.get_cookie(&cookies);

        let mut session_id = cookie.map(get_cookie_value);
        let data = match &session_id {
            Some(sid) if (self.config.store().verify)(sid) => self
                .config
                .store()
                .get(sid)
                .await
                .map_err(Into::<Error>::into)?,
            _ => None,
        };
        if data.is_none() && session_id.is_some() {
            session_id.take();
        }
        let session = Session::new(data.unwrap_or_default());
        req.extensions_mut().insert(session.clone());

        let resp = self.h.call(req).await.map(IntoResponse::into_response);

        let status = session.status().load(Ordering::Acquire);

        if status == UNCHANGED {
            return resp;
        }

        if status == PURGED {
            if let Some(sid) = &session_id {
                self.config
                    .store()
                    .remove(sid)
                    .await
                    .map_err(Into::<Error>::into)?;
                self.config.remove_cookie(&cookies);
            }

            return resp;
        }

        if status == RENEWED {
            if let Some(sid) = &session_id.take() {
                self.config
                    .store()
                    .remove(sid)
                    .await
                    .map_err(Into::<Error>::into)?;
            }
        }

        let sid = match session_id {
            Some(sid) => sid,
            None => {
                let sid = (self.config.store().generate)();
                self.config.set_cookie(&cookies, &sid);
                sid
            }
        };

        self.config
            .store()
            .set(
                &sid,
                session.data()?,
                &self.config.ttl().unwrap_or_else(max_age),
            )
            .await
            .map_err(Into::<Error>::into)?;

        resp
    }
}

fn max_age() -> Duration {
    Duration::from_secs(CookieOptions::MAX_AGE)
}

fn get_cookie_value(c: Cookie<'_>) -> String {
    c.value().to_string()
}

impl From<SessionError> for Error {
    fn from(e: SessionError) -> Self {
        Error::Report(
            Box::new(e),
            StatusCode::INTERNAL_SERVER_ERROR.into_response(),
        )
    }
}