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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
//! Create session storage and build middleware factory

use crate::*;
pub use actix_web::cookie::time::{Duration, OffsetDateTime};
use actix_web::dev::Transform;
use actix_web::dev::{forward_ready, Service, ServiceRequest, ServiceResponse};
use futures_util::future::LocalBoxFuture;
use jsonwebtoken::{Algorithm, DecodingKey, EncodingKey};
use std::future::{ready, Ready};
use std::rc::Rc;
use std::sync::Arc;

/// Session middleware factory builder
/// 
/// It should be constructed with [SessionMiddlewareFactory::build].
pub struct SessionMiddlewareBuilder<ClaimsType: Claims> {
    pub(crate) jwt_encoding_key: Arc<EncodingKey>,
    pub(crate) jwt_decoding_key: Arc<DecodingKey>,
    pub(crate) algorithm: Algorithm,
    pub(crate) storage: Option<SessionStorage>,
    pub(crate) jwt_extractors: Vec<Box<dyn SessionExtractor<ClaimsType>>>,
    pub(crate) refresh_extractors: Vec<Box<dyn SessionExtractor<RefreshToken>>>,
}
impl<ClaimsType: Claims> SessionMiddlewareBuilder<ClaimsType> {
    #[doc(hidden)]
    pub(crate) fn new(
        jwt_encoding_key: Arc<EncodingKey>,
        jwt_decoding_key: Arc<DecodingKey>,
        algorithm: Algorithm,
    ) -> Self {
        Self {
            jwt_encoding_key: jwt_encoding_key.clone(),
            jwt_decoding_key,
            algorithm,
            storage: None,
            jwt_extractors: vec![],
            refresh_extractors: vec![],
        }
    }

    /// Set session storage to given instance. Good if for some reason you need to share 1 storage
    /// with multiple instances of session middleware
    #[must_use]
    pub fn with_storage(mut self, storage: SessionStorage) -> Self {
        self.storage = Some(storage);
        self
    }

    /// Add cookie extractor for refresh token.
    #[must_use]
    pub fn with_refresh_cookie(mut self, name: &'static str) -> Self {
        self.refresh_extractors
            .push(Box::new(CookieExtractor::<RefreshToken>::new(name)));
        self
    }

    /// Add header extractor for refresh token.
    #[must_use]
    pub fn with_refresh_header(mut self, name: &'static str) -> Self {
        self.refresh_extractors
            .push(Box::new(HeaderExtractor::<RefreshToken>::new(name)));
        self
    }

    /// Add cookie extractor for json web token.
    #[must_use]
    pub fn with_jwt_cookie(mut self, name: &'static str) -> Self {
        self.jwt_extractors
            .push(Box::new(CookieExtractor::<ClaimsType>::new(name)));
        self
    }

    /// Add header extractor for json web token.
    #[must_use]
    pub fn with_jwt_header(mut self, name: &'static str) -> Self {
        self.jwt_extractors
            .push(Box::new(HeaderExtractor::<ClaimsType>::new(name)));
        self
    }

    /// Builds middleware factory and returns session storage with factory
    pub fn finish(self) -> (SessionStorage, SessionMiddlewareFactory<ClaimsType>) {
        let Self {
            storage,
            jwt_encoding_key,
            jwt_decoding_key,
            algorithm,
            jwt_extractors,
            refresh_extractors,
            ..
        } = self;
        let storage = storage
            .expect("Session storage must be constracted from pool or set from existing storage");
        (
            storage.clone(),
            SessionMiddlewareFactory {
                jwt_encoding_key,
                jwt_decoding_key,
                algorithm,
                storage,
                jwt_extractors: Arc::new(jwt_extractors),
                refresh_extractors: Arc::new(refresh_extractors),
            },
        )
    }
}

/// Factory creates middlware for every single request.
///
/// All fields here are immutable and have atomic access and only pointer is copied so are very cheap
/// 
/// Example:
///
/// ```
/// use std::sync::Arc;
/// use actix_jwt_session::*;
///
/// # async fn create<AppClaims: actix_jwt_session::Claims>() {
/// // create redis connection
/// let redis = {
///     use redis_async_pool::{RedisConnectionManager, RedisPool};
///     RedisPool::new(
///         RedisConnectionManager::new(
///             redis::Client::open("redis://localhost:6379").expect("Fail to connect to redis"),
///             true,
///             None,
///         ),
///         5,
///     )
/// };
/// 
/// // load or create new keys in `./config`
/// let keys = JwtSigningKeys::load_or_create();
///
/// // create new [SessionStorage] and [SessionMiddlewareFactory]
/// let (storage, factory) = SessionMiddlewareFactory::<AppClaims>::build(
///     Arc::new(keys.encoding_key),
///     Arc::new(keys.decoding_key),
///     Algorithm::EdDSA
/// )
/// // pass redis connection
/// .with_redis_pool(redis.clone())
/// // Check if header "Authorization" exists and contains Bearer with encoded JWT
/// .with_jwt_header("Authorization")
/// // Check if cookie "jwt" exists and contains encoded JWT
/// .with_jwt_cookie("acx-a")
/// .with_refresh_header("ACX-Refresh")
/// // Check if cookie "jwt" exists and contains encoded JWT
/// .with_refresh_cookie("acx-r")
/// .finish();
/// # }
/// ```
#[derive(Clone)]
pub struct SessionMiddlewareFactory<ClaimsType: Claims> {
    pub(crate) jwt_encoding_key: Arc<EncodingKey>,
    pub(crate) jwt_decoding_key: Arc<DecodingKey>,
    pub(crate) algorithm: Algorithm,
    pub(crate) storage: SessionStorage,
    pub(crate) jwt_extractors: Arc<Vec<Box<dyn SessionExtractor<ClaimsType>>>>,
    pub(crate) refresh_extractors: Arc<Vec<Box<dyn SessionExtractor<RefreshToken>>>>,
}

impl<ClaimsType: Claims> SessionMiddlewareFactory<ClaimsType> {
    pub fn build(
        jwt_encoding_key: Arc<EncodingKey>,
        jwt_decoding_key: Arc<DecodingKey>,
        algorithm: Algorithm,
    ) -> SessionMiddlewareBuilder<ClaimsType> {
        SessionMiddlewareBuilder::new(jwt_encoding_key, jwt_decoding_key, algorithm)
    }
}

impl<S, B, ClaimsType> Transform<S, ServiceRequest> for SessionMiddlewareFactory<ClaimsType>
where
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
    ClaimsType: Claims,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Transform = SessionMiddleware<S, ClaimsType>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ready(Ok(SessionMiddleware {
            service: Rc::new(service),
            storage: self.storage.clone(),
            jwt_encoding_key: self.jwt_encoding_key.clone(),
            jwt_decoding_key: self.jwt_decoding_key.clone(),
            algorithm: self.algorithm,
            jwt_extractors: self.jwt_extractors.clone(),
            refresh_extractors: self.refresh_extractors.clone(),
        }))
    }
}

#[doc(hidden)]
pub struct SessionMiddleware<S, ClaimsType>
where
    ClaimsType: Claims,
{
    pub(crate) service: Rc<S>,
    pub(crate) jwt_encoding_key: Arc<EncodingKey>,
    pub(crate) jwt_decoding_key: Arc<DecodingKey>,
    pub(crate) algorithm: Algorithm,
    pub(crate) storage: SessionStorage,
    pub(crate) jwt_extractors: Arc<Vec<Box<dyn SessionExtractor<ClaimsType>>>>,
    pub(crate) refresh_extractors: Arc<Vec<Box<dyn SessionExtractor<RefreshToken>>>>,
}

impl<S, ClaimsType: Claims> SessionMiddleware<S, ClaimsType> {
    async fn extract_token<C: Claims>(
        req: &mut ServiceRequest,
        jwt_encoding_key: Arc<EncodingKey>,
        jwt_decoding_key: Arc<DecodingKey>,
        algorithm: Algorithm,
        storage: SessionStorage,
        extractors: &[Box<dyn SessionExtractor<C>>],
    ) -> Result<(), Error> {
        let mut last_error = None;
        for extractor in extractors.iter() {
            match extractor
                .extract_claims(
                    req,
                    jwt_encoding_key.clone(),
                    jwt_decoding_key.clone(),
                    algorithm,
                    storage.clone(),
                )
                .await
            {
                Ok(_) => break,
                Err(e) => {
                    last_error = Some(e);
                }
            };
        }
        if let Some(e) = last_error {
            return Err(e)?;
        }
        Ok(())
    }
}

impl<S, B, ClaimsType> Service<ServiceRequest> for SessionMiddleware<S, ClaimsType>
where
    ClaimsType: Claims,
    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error> + 'static,
{
    type Response = ServiceResponse<B>;
    type Error = actix_web::Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    forward_ready!(service);

    fn call(&self, mut req: ServiceRequest) -> Self::Future {
        use futures_lite::FutureExt;

        let svc = self.service.clone();
        let jwt_decoding_key = self.jwt_decoding_key.clone();
        let jwt_encoding_key = self.jwt_encoding_key.clone();
        let algorithm = self.algorithm;
        let storage = self.storage.clone();
        let jwt_extractors = self.jwt_extractors.clone();
        let refresh_extractors = self.refresh_extractors.clone();

        async move {
            if !jwt_extractors.is_empty() {
                Self::extract_token(
                    &mut req,
                    jwt_encoding_key.clone(),
                    jwt_decoding_key.clone(),
                    algorithm,
                    storage.clone(),
                    &jwt_extractors,
                )
                .await?;
            }
            if !refresh_extractors.is_empty() {
                Self::extract_token(
                    &mut req,
                    jwt_encoding_key,
                    jwt_decoding_key,
                    algorithm,
                    storage,
                    &refresh_extractors,
                )
                .await?;
            }
            let res = svc.call(req).await?;
            Ok(res)
        }
        .boxed_local()
    }
}