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
use std::{
    fmt,
    sync::{atomic::Ordering, Arc},
    time::Duration,
};

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

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

/// A configuration for [`SessionMiddleware`].
pub struct Config<S, G, V>(Arc<(Store<S, G, V>, CookieOptions)>);

impl<S, G, V> Config<S, G, V> {
    /// Creates a new configuration with the [`Store`] and [`CookieOptions`].
    #[must_use]
    pub fn new(store: Store<S, G, V>, cookie: CookieOptions) -> Self {
        Self(Arc::new((store, cookie)))
    }

    /// Gets the store.
    #[must_use]
    pub fn store(&self) -> &Store<S, G, V> {
        &self.0 .0
    }

    /// Gets the TTL.
    #[must_use]
    pub fn ttl(&self) -> Option<Duration> {
        self.options().max_age
    }
}

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

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

impl<S, G, V> fmt::Debug for Config<S, G, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SessionConfig").finish()
    }
}

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(),
        }
    }
}

/// Session middleware.
#[derive(Debug)]
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(),
        }
    }
}

#[crate::async_trait]
impl<H, O, S, G, V> Handler<Request> for SessionMiddleware<H, S, G, V>
where
    H: Handler<Request, Output = Result<O>>,
    O: IntoResponse,
    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 Self { h, config } = self;

        let cookies = req.cookies()?;
        let cookie = config.get_cookie(&cookies);

        let mut session_id = cookie.as_ref().map(Cookie::value).map(ToString::to_string);
        let data = match &session_id {
            Some(sid) if (config.store().verify)(sid) => config.store().get(sid).await?,
            _ => 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 = 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 {
                config.store().remove(sid).await?;
                config.remove_cookie(&cookies);
            }

            return resp;
        }

        if status == RENEWED {
            if let Some(sid) = &session_id.take() {
                config.store().remove(sid).await?;
            }
        }

        let sid = session_id.unwrap_or_else(|| {
            let sid = (config.store().generate)();
            config.set_cookie(&cookies, &sid);
            sid
        });

        config
            .store()
            .set(&sid, session.data()?, &config.ttl().unwrap_or_else(max_age))
            .await?;

        resp
    }
}

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