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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
use crate::{
sec::encrypt, DatabasePool, Session, SessionConfig, SessionData, SessionError, SessionTimers,
};
use axum::extract::FromRequestParts;
use chrono::{Duration, Utc};
use dashmap::DashMap;
#[cfg(feature = "key-store")]
use fastbloom_rs::Deletable;
#[cfg(feature = "key-store")]
use fastbloom_rs::{CountingBloomFilter, FilterBuilder, Membership};
use http::{request::Parts, StatusCode};
use serde::Serialize;
use std::{fmt::Debug, sync::Arc};
use tokio::sync::RwLock;
/// Contains the main Services storage for all session's and database access for persistent Sessions.
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore};
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config).await.unwrap();
/// ```
///
#[derive(Clone, Debug)]
pub struct SessionStore<T>
where
T: DatabasePool + Clone + Debug + Sync + Send + 'static,
{
/// Client for the database.
pub client: Option<T>,
/// locked Hashmap containing UserID and their session data.
pub(crate) inner: Arc<DashMap<String, SessionData>>,
/// Session Configuration.
pub config: SessionConfig,
/// Session Timers used for Clearing Memory and Database.
pub(crate) timers: Arc<RwLock<SessionTimers>>,
#[cfg(feature = "key-store")]
/// Filter used to keep track of what session IDs exist.
pub(crate) filter: Arc<RwLock<CountingBloomFilter>>,
}
impl<T, S> FromRequestParts<S> for SessionStore<T>
where
T: DatabasePool + Clone + Debug + Sync + Send + 'static,
S: Send + Sync,
{
type Rejection = (http::StatusCode, &'static str);
async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
let session = parts.extensions.get::<Session<T>>().ok_or((
StatusCode::INTERNAL_SERVER_ERROR,
"Can't extract Axum `Session`. Is `SessionLayer` enabled?",
))?;
Ok(session.store.clone())
}
}
impl<T> SessionStore<T>
where
T: DatabasePool + Clone + Debug + Sync + Send + 'static,
{
/// Constructs a New `SessionStore` and Creates the Database Table
/// needed for the Session if it does not exist if client is not `None`.
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore};
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config).await.unwrap();
/// ```
///
#[inline]
pub async fn new(client: Option<T>, config: SessionConfig) -> Result<Self, SessionError> {
if let Some(client) = &client {
client.initiate(&config.database.table_name).await?
}
// If we have a database client then lets also get any SessionId's that Exist within the database
// that are not yet expired.
#[cfg(feature = "key-store")]
let filter = Self::create_filter(&client, &config).await?;
Ok(Self {
client,
inner: Default::default(),
config,
timers: Arc::new(RwLock::new(SessionTimers {
// the first expiry sweep is scheduled one lifetime from start-up
last_expiry_sweep: Utc::now() + Duration::try_hours(1).unwrap_or_default(),
// the first expiry sweep is scheduled one lifetime from start-up
last_database_expiry_sweep: Utc::now() + Duration::try_hours(6).unwrap_or_default(),
})),
#[cfg(feature = "key-store")]
filter: Arc::new(RwLock::new(filter)),
})
}
/// Used to create and Fill the Filter.
#[cfg(feature = "key-store")]
pub(crate) async fn create_filter(
client: &Option<T>,
config: &SessionConfig,
) -> Result<CountingBloomFilter, SessionError> {
let mut filter = FilterBuilder::new(
config.memory.filter_expected_elements,
config.memory.filter_false_positive_probability,
)
.build_counting_bloom_filter();
if config.memory.use_bloom_filters {
// If client exist then lets preload the id's within the database so the filter is accurate.
if let Some(client) = &client {
let ids = client.get_ids(&config.database.table_name).await?;
ids.iter().for_each(|id| filter.add(id.as_bytes()));
}
}
Ok(filter)
}
/// Checks if the database is in persistent mode.
///
/// Returns true if client is Some().
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore};
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config).await.unwrap();
/// let is_persistent = session_store.is_persistent();
/// ```
///
#[inline]
pub fn is_persistent(&self) -> bool {
self.client.is_some()
}
/// Cleans Expired sessions from the Database based on Utc::now().
///
/// If client is None it will return Ok(()).
///
/// # Errors
/// - ['SessionError::Sqlx'] is returned if database connection has failed or user does not have permissions.
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore};
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config).await.unwrap();
/// async {
/// let _ = session_store.cleanup().await.unwrap();
/// };
/// ```
///
#[inline]
pub async fn cleanup(&self) -> Result<Vec<String>, SessionError> {
if let Some(client) = &self.client {
Ok(client
.delete_by_expiry(&self.config.database.table_name)
.await?)
} else {
Ok(Vec::new())
}
}
/// Returns count of existing sessions within database.
///
/// If client is None it will return Ok(0).
///
/// # Errors
/// - ['SessionError::Sqlx'] is returned if database connection has failed or user does not have permissions.
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore};
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config).await.unwrap();
/// async {
/// let count = session_store.count().await.unwrap();
/// };
/// ```
///
#[inline]
pub async fn count(&self) -> Result<i64, SessionError> {
if let Some(client) = &self.client {
let count = client.count(&self.config.database.table_name).await?;
return Ok(count);
}
Ok(0)
}
/// private internal function that loads a session's data from the database using an ID string.
///
/// If client is None it will return Ok(None).
///
/// # Errors
/// - ['SessionError::Sqlx'] is returned if database connection has failed or user does not have permissions.
/// - ['SessionError::SerdeJson'] is returned if it failed to deserialize the sessions data.
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore};
/// use uuid::Uuid;
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config).await.unwrap();
/// let token = Uuid::new_v4();
/// async {
/// let session_data = session_store.load_session(token.to_string()).await.unwrap();
/// };
/// ```
///
pub(crate) async fn load_session(
&self,
cookie_value: String,
) -> Result<Option<SessionData>, SessionError> {
if let Some(client) = &self.client {
let result: Option<String> = client
.load(&cookie_value, &self.config.database.table_name)
.await?;
if let Some(mut session) = result
.map(|session| {
if let Some(key) = self.config.database.database_key.as_ref() {
serde_json::from_str::<SessionData>(
&match encrypt::decrypt(&cookie_value, &session, key) {
Ok(v) => v,
Err(err) => {
tracing::error!(err = %err, "Failed to decrypt Session data from database.");
String::new()
}
}
)
} else {
serde_json::from_str::<SessionData>(&session)
}
})
.transpose()?
{
session.id = cookie_value;
return Ok(Some(session));
}
}
Ok(None)
}
/// private internal function that stores a session's data to the database.
///
/// If client is None it will return Ok(()).
///
/// # Errors
/// - ['SessionError::Sqlx'] is returned if database connection has failed or user does not have permissions.
/// - ['SessionError::SerdeJson'] is returned if it failed to serialize the sessions data.
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore, SessionData};
/// use uuid::Uuid;
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config.clone()).await.unwrap();
/// let token = Uuid::new_v4();
/// let session_data = SessionData::new(token, true, &config);
///
/// async {
/// let _ = session_store.store_session(&session_data).await.unwrap();
/// };
/// ```
///
pub(crate) async fn store_session(&self, session: &SessionData) -> Result<(), SessionError> {
if let Some(client) = &self.client {
client
.store(
&session.id,
&if let Some(key) = self.config.database.database_key.as_ref() {
encrypt::encrypt(&session.id, &serde_json::to_string(session)?, key)
.map_err(|e| {
SessionError::GenericNotSupportedError(format!(
"Error: {e} Occurred when encrypting a Session.",
))
})?
} else {
serde_json::to_string(session)?
},
session.expires.timestamp(),
&self.config.database.table_name,
)
.await?;
}
Ok(())
}
/// Deletes all sessions in the database.
///
/// If client is None it will return Ok(()).
///
/// # Errors
/// - ['SessionError::Sqlx'] is returned if database connection has failed or user does not have permissions.
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore};
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config.clone()).await.unwrap();
///
/// async {
/// let _ = session_store.clear_store().await.unwrap();
/// };
/// ```
///
#[inline]
pub async fn clear_store(&self) -> Result<(), SessionError> {
if let Some(client) = &self.client {
client.delete_all(&self.config.database.table_name).await?;
}
Ok(())
}
/// Deletes all sessions in Memory.
/// This will also Clear those keys from the filter cache if a persistent database does not exist.
///
/// # Examples
/// ```rust ignore
/// use axum_session::{SessionNullPool, SessionConfig, SessionStore};
///
/// let config = SessionConfig::default();
/// let session_store = SessionStore::<SessionNullPool>::new(None, config.clone()).await.unwrap();
///
/// async {
/// let _ = session_store.clear().await.unwrap();
/// };
/// ```
///
#[inline]
pub async fn clear(&mut self) {
#[cfg(feature = "key-store")]
if self.client.is_none() {
let mut filter = self.filter.write().await;
self.inner
.iter()
.for_each(|value| filter.remove(value.key().as_bytes()));
}
self.inner.clear();
}
/// Attempts to load check and clear Data.
///
/// If no session is found returns false.
pub(crate) fn service_session_data(&self, session: &Session<T>) -> bool {
if let Some(mut inner) = self.inner.get_mut(&session.id) {
inner.service_clear(
self.config.memory.memory_lifespan,
self.config.clear_check_on_load,
);
inner.set_request();
return true;
}
false
}
#[inline]
pub(crate) fn renew(&self, id: String) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.renew();
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn destroy(&self, id: String) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.destroy();
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn set_longterm(&self, id: String, longterm: bool) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.set_longterm(longterm);
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn set_store(&self, id: String, storable: bool) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.set_store(storable);
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn update(&self, id: String) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.update();
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn get<N: serde::de::DeserializeOwned>(&self, id: String, key: &str) -> Option<N> {
if let Some(instance) = self.inner.get(&id) {
instance.get(key)
} else {
tracing::warn!("Session data unexpectedly missing");
None
}
}
#[inline]
pub(crate) fn get_remove<N: serde::de::DeserializeOwned>(
&self,
id: String,
key: &str,
) -> Option<N> {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.get_remove(key)
} else {
tracing::warn!("Session data unexpectedly missing");
None
}
}
#[inline]
pub(crate) fn set(&self, id: String, key: &str, value: impl Serialize) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.set(key, value);
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn remove(&self, id: String, key: &str) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.remove(key);
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn clear_session_data(&self, id: String) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.clear();
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn set_session_request(&self, id: String) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.set_request();
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn remove_session_request(&self, id: String) {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.remove_request();
} else {
tracing::warn!("Session data unexpectedly missing");
}
}
#[inline]
pub(crate) fn is_session_parallel(&self, id: String) -> bool {
if let Some(instance) = self.inner.get(&id) {
instance.is_parallel()
} else {
tracing::warn!("Session data unexpectedly missing");
false
}
}
#[inline]
pub(crate) async fn count_sessions(&self) -> i64 {
if self.is_persistent() {
self.count().await.unwrap_or(0i64)
} else {
self.inner.len() as i64
}
}
#[inline]
pub(crate) fn auto_handles_expiry(&self) -> bool {
if let Some(client) = &self.client {
client.auto_handles_expiry()
} else {
false
}
}
#[cfg(feature = "advanced")]
#[cfg_attr(docsrs, doc(cfg(feature = "advanced")))]
#[inline]
pub(crate) fn verify(&self, id: String) -> Result<(), SessionError> {
if let Some(instance) = self.inner.get(&id) {
if instance.expires < Utc::now() {
Err(SessionError::OldSessionError)
} else {
Ok(())
}
} else {
Err(SessionError::NoSessionError)
}
}
#[cfg(feature = "advanced")]
#[cfg_attr(docsrs, doc(cfg(feature = "advanced")))]
#[inline]
pub(crate) fn update_database_expires(&self, id: String) -> Result<(), SessionError> {
if let Some(mut instance) = self.inner.get_mut(&id) {
if instance.longterm {
instance.expires = Utc::now() + self.config.max_lifespan;
} else {
instance.expires = Utc::now() + self.config.lifespan;
}
Ok(())
} else {
Err(SessionError::NoSessionError)
}
}
#[cfg(feature = "advanced")]
#[cfg_attr(docsrs, doc(cfg(feature = "advanced")))]
#[inline]
pub(crate) fn update_memory_expires(&self, id: String) -> Result<(), SessionError> {
if let Some(mut instance) = self.inner.get_mut(&id) {
instance.autoremove = Utc::now() + self.config.memory.memory_lifespan;
Ok(())
} else {
Err(SessionError::NoSessionError)
}
}
#[cfg(feature = "advanced")]
#[cfg_attr(docsrs, doc(cfg(feature = "advanced")))]
#[inline]
pub(crate) async fn force_database_update(&self, id: String) -> Result<(), SessionError> {
let session = if let Some(instance) = self.inner.get(&id) {
instance.clone()
} else {
return Err(SessionError::NoSessionError);
};
self.store_session(&session).await
}
#[cfg(feature = "advanced")]
#[cfg_attr(docsrs, doc(cfg(feature = "advanced")))]
#[inline]
pub(crate) fn memory_remove_session(&self, id: String) -> Result<(), SessionError> {
let is_parallel = if let Some(mut instance) = self.inner.get_mut(&id) {
instance.remove_request();
instance.is_parallel()
} else {
return Err(SessionError::NoSessionError);
};
if is_parallel {
let _ = self.inner.remove(&id);
}
Ok(())
}
#[inline]
pub(crate) async fn database_remove_session(&self, id: String) -> Result<(), SessionError> {
if let Some(client) = &self.client {
client
.delete_one_by_id(&id, &self.config.database.table_name)
.await?;
}
Ok(())
}
}