-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
session.rs
575 lines (530 loc) · 16.8 KB
/
session.rs
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
//! A session which allows HTTP applications to associate data with visitors.
use std::{collections::HashMap, fmt::Display, sync::Arc};
use parking_lot::Mutex;
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use serde_json::Value;
use time::Duration;
use tower_cookies::{cookie::time::OffsetDateTime, Cookie};
use uuid::Uuid;
use crate::CookieConfig;
/// Session errors.
#[derive(thiserror::Error, Debug)]
pub enum SessionError {
/// A variant to map `uuid` errors.
#[error("Invalid UUID: {0}")]
InvalidUuid(#[from] uuid::Error),
/// A variant to map `serde_json` errors.
#[error("JSON serialization/deserialization error: {0}")]
SerdeJsonError(#[from] serde_json::Error),
}
type SessionResult<T> = Result<T, SessionError>;
/// A session which allows HTTP applications to associate data with visitors.
#[derive(Debug, Clone, Default)]
pub struct Session {
pub(crate) id: SessionId,
expiration_time: Option<OffsetDateTime>,
inner: Arc<Mutex<Inner>>,
}
impl Session {
/// Create a new session with defaults.
///
/// Note that an `expiration_time` of none results in a cookie with
/// expiration `"Session"`.
///
/// # Examples
///
///```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// ```
pub fn new() -> Self {
let inner = Inner {
data: HashMap::new(),
modified: false,
deleted: None,
};
Self {
id: SessionId::default(),
expiration_time: None,
inner: Arc::new(Mutex::new(inner)),
}
}
/// A method for setting `expiration_time` in accordance with `max_age`.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::{time::Duration, Session};
/// let session = Session::new().with_max_age(Duration::minutes(5));
/// ```
pub fn with_max_age(mut self, max_age: Duration) -> Self {
let expiration_time = OffsetDateTime::now_utc().saturating_add(max_age);
self.expiration_time = Some(expiration_time);
self
}
/// Inserts a `impl Serialize` value into the session.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// session.insert("foo", 42).expect("Serialization error.");
/// ```
///
/// # Errors
///
/// This method can fail when [`serde_json::to_value`] fails.
pub fn insert(&self, key: &str, value: impl Serialize) -> SessionResult<()> {
self.insert_value(key, serde_json::to_value(&value)?);
Ok(())
}
/// Inserts a `serde_json::Value` into the session.
///
/// If the key was not present in the underlying map, `None` is returned and
/// `modified` is set to `true`.
///
/// If the underlying map did have the key and its value is the same as the
/// provided value, `None` is returned and `modified` is not set.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// let value = session.insert_value("foo", serde_json::json!(42));
/// assert!(value.is_none());
///
/// let value = session.insert_value("foo", serde_json::json!(42));
/// assert!(value.is_none());
///
/// let value = session.insert_value("foo", serde_json::json!("bar"));
/// assert_eq!(value, Some(serde_json::json!(42)));
/// ```
pub fn insert_value(&self, key: &str, value: Value) -> Option<Value> {
let mut inner = self.inner.lock();
if inner.data.get(key) != Some(&value) {
inner.modified = true;
inner.data.insert(key.to_string(), value)
} else {
None
}
}
/// Gets a value from the store.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// session.insert("foo", 42).unwrap();
/// let value = session.get::<usize>("foo").unwrap();
/// assert_eq!(value, Some(42));
/// ```
///
/// # Errors
///
/// This method can fail when [`serde_json::from_value`] fails.
pub fn get<T: DeserializeOwned>(&self, key: &str) -> SessionResult<Option<T>> {
Ok(self
.get_value(key)
.map(serde_json::from_value)
.transpose()?)
}
/// Gets a `serde_json::Value` from the store.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// session.insert("foo", 42).unwrap();
/// let value = session.get_value("foo").unwrap();
/// assert_eq!(value, serde_json::json!(42));
/// ```
pub fn get_value(&self, key: &str) -> Option<Value> {
let inner = self.inner.lock();
inner.data.get(key).cloned()
}
/// Removes a value from the store, retuning the value of the key if it was
/// present in the underlying map.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// session.insert("foo", 42).unwrap();
/// let value: Option<usize> = session.remove("foo").unwrap();
/// assert_eq!(value, Some(42));
/// let value: Option<usize> = session.get("foo").unwrap();
/// assert!(value.is_none());
/// ```
///
/// # Errors
///
/// This method can fail when [`serde_json::from_value`] fails.
pub fn remove<T: DeserializeOwned>(&self, key: &str) -> SessionResult<Option<T>> {
Ok(self
.remove_value(key)
.map(serde_json::from_value)
.transpose()?)
}
/// Removes a `serde_json::Value` from the store.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// session.insert("foo", 42).unwrap();
/// let value = session.remove_value("foo").unwrap();
/// assert_eq!(value, serde_json::json!(42));
/// let value: Option<usize> = session.get("foo").unwrap();
/// assert!(value.is_none());
/// ```
pub fn remove_value(&self, key: &str) -> Option<Value> {
let mut inner = self.inner.lock();
if let Some(removed) = inner.data.remove(key) {
inner.modified = true;
Some(removed)
} else {
None
}
}
/// Replaces a value in the session with a new value if the current value
/// matches the old value.
///
/// If the key was not present in the underlying map or the current value
/// does not match, `false` is returned, indicating failure.
///
/// If the key was present and its value matches the old value, the new
/// value is inserted, and `true` is returned, indicating success.
///
/// This method is essential for scenarios where data races need to be
/// prevented. For instance, reading from and writing to a session is
/// not transactional. To ensure that read values are not stale, it's
/// crucial to use `replace_if_equal` when modifying the session.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// session.insert("foo", 42).unwrap();
///
/// let success = session.replace_if_equal("foo", 42, 43).unwrap();
/// assert_eq!(success, true);
///
/// let success = session.replace_if_equal("foo", 42, 44).unwrap();
/// assert_eq!(success, false);
/// ```
///
/// # Errors
///
/// This method can fail when [`serde_json::to_value`] fails.
pub fn replace_if_equal(
&self,
key: &str,
old_value: impl Serialize,
new_value: impl Serialize,
) -> SessionResult<bool> {
let mut inner = self.inner.lock();
match inner.data.get(key) {
Some(current_value) if serde_json::to_value(&old_value)? == *current_value => {
let new_value = serde_json::to_value(&new_value)?;
if *current_value == new_value {
inner.modified = true;
}
inner.data.insert(key.to_string(), new_value);
Ok(true) // Success, old value matched.
}
_ => Ok(false), // Failure, key doesn't exist or old value doesn't match.
}
}
/// Clears the session data.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// session.insert("foo", 42).unwrap();
/// session.clear();
/// assert!(session.get_value("foo").is_none());
/// ```
pub fn clear(&self) {
let mut inner = self.inner.lock();
inner.data.clear();
}
/// Sets `deleted` on the session to `SessionDeletion::Deleted`.
///
/// Setting this flag indicates the session should be deleted from the
/// underlying store.
///
/// This flag is consumed by a session management system to ensure session
/// life cycle progression.
///
///
/// # Examples
///
/// ```rust
/// use tower_sessions::{session::SessionDeletion, Session};
/// let session = Session::new();
/// session.delete();
/// assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));
/// ```
pub fn delete(&self) {
let mut inner = self.inner.lock();
inner.deleted = Some(SessionDeletion::Deleted);
}
/// Sets `deleted` on the session to `SessionDeletion::Cycled(self.id))`.
///
/// Setting this flag indicates the session ID should be cycled while
/// retaining the session's data.
///
/// This flag is consumed by a session management system to ensure session
/// life cycle progression.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::{session::SessionDeletion, Session};
/// let session = Session::new();
/// session.cycle_id();
/// assert!(matches!(
/// session.deleted(),
/// Some(SessionDeletion::Cycled(cycled_id)) if cycled_id == session.id()
/// ));
/// ```
pub fn cycle_id(&self) {
let mut inner = self.inner.lock();
inner.deleted = Some(SessionDeletion::Cycled(self.id));
inner.modified = true;
}
/// Sets `deleted` on the session to `SessionDeletion::Deleted` and clears
/// the session data.
///
/// This helps ensure that session data cannot be accessed beyond this
/// invocation.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::{session::SessionDeletion, Session};
/// let session = Session::new();
/// session.insert("foo", 42).unwrap();
/// session.flush();
/// assert!(session.get_value("foo").is_none());
/// assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));
/// ```
pub fn flush(&self) {
self.clear();
self.delete();
}
/// Get the session ID.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// session.id();
/// ```
pub fn id(&self) -> SessionId {
self.id
}
/// Get the session expiration time.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::{
/// time::{Duration, OffsetDateTime},
/// Session,
/// };
/// let session = Session::new().with_max_age(Duration::hours(1));
/// assert!(session
/// .expiration_time()
/// .is_some_and(|et| et > OffsetDateTime::now_utc()));
/// ```
pub fn expiration_time(&self) -> Option<OffsetDateTime> {
self.expiration_time
}
/// Returns `true` if the session is active and `false` otherwise.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::{time::Duration, Session};
/// let session = Session::new();
/// assert!(session.active());
///
/// let session = Session::new().with_max_age(Duration::hours(1));
/// assert!(session.active());
///
/// let session = Session::new().with_max_age(Duration::ZERO);
/// assert!(!session.active());
/// ```
pub fn active(&self) -> bool {
if let Some(expiration_time) = self.expiration_time {
expiration_time > OffsetDateTime::now_utc()
} else {
true
}
}
/// Given a [`CookieConfig`], builds a `Cookie` from the session.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::{CookieConfig, Session};
/// let session = Session::new();
/// let cookie_config = CookieConfig::default();
/// let cookie = session.build_cookie(&cookie_config);
/// assert_eq!(cookie.value(), session.id().to_string());
/// ```
pub fn build_cookie<'c>(&self, cookie_config: &CookieConfig) -> Cookie<'c> {
let mut cookie_builder = Cookie::build(cookie_config.name.clone(), self.id.to_string())
.http_only(true)
.same_site(cookie_config.same_site)
.secure(cookie_config.secure)
.path(cookie_config.path.clone());
if let Some(max_age) = self
.expiration_time
.map(|dt| dt - OffsetDateTime::now_utc())
{
cookie_builder = cookie_builder.max_age(max_age);
}
if let Some(domain) = &cookie_config.domain {
cookie_builder = cookie_builder.domain(domain.clone());
}
cookie_builder.finish()
}
/// Returns `true` if the session has been modified and `false` otherwise.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::Session;
/// let session = Session::new();
/// assert!(!session.modified());
/// session.insert("foo", 42);
/// assert!(session.modified());
/// ```
pub fn modified(&self) -> bool {
self.inner.lock().modified
}
/// Returns `Some(SessionDeletion)` if one has been set and `None`
/// otherwise.
///
/// # Examples
///
/// ```rust
/// use tower_sessions::{session::SessionDeletion, Session};
/// let session = Session::new();
/// assert!(session.deleted().is_none());
/// session.delete();
/// assert!(matches!(session.deleted(), Some(SessionDeletion::Deleted)));
/// session.cycle_id();
/// assert!(matches!(
/// session.deleted(),
/// Some(SessionDeletion::Cycled(_))
/// ))
/// ```
pub fn deleted(&self) -> Option<SessionDeletion> {
self.inner.lock().deleted
}
}
impl From<SessionRecord> for Session {
fn from(
SessionRecord {
id,
data,
expiration_time,
}: SessionRecord,
) -> Self {
let inner = Inner {
data,
modified: false,
deleted: None,
};
Self {
id,
expiration_time,
inner: Arc::new(Mutex::new(inner)),
}
}
}
impl From<&CookieConfig> for Session {
fn from(cookie_config: &CookieConfig) -> Self {
let mut session = Session::default();
if let Some(max_age) = cookie_config.max_age {
session = session.with_max_age(max_age);
}
session
}
}
#[derive(Debug, Default)]
struct Inner {
data: HashMap<String, Value>,
modified: bool,
deleted: Option<SessionDeletion>,
}
/// An ID type for sessions.
#[derive(Copy, Clone, Debug, Deserialize, Serialize, Eq, Hash, PartialEq)]
pub struct SessionId(Uuid);
impl Default for SessionId {
fn default() -> Self {
Self(Uuid::new_v4())
}
}
impl Display for SessionId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0.as_hyphenated().to_string())
}
}
impl TryFrom<&str> for SessionId {
type Error = SessionError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Ok(Self(Uuid::parse_str(value)?))
}
}
/// Session deletion, represented as an enumeration of possible deletion types.
#[derive(Debug, Copy, Clone)]
pub enum SessionDeletion {
/// This indicates the session has been completely removed from the store.
Deleted,
/// This indicates that the provided session ID should be cycled but that
/// the session data should be retained in a new session.
Cycled(SessionId),
}
/// A type that represents data to be persisted in a store for a session.
///
/// Saving to and loading from a store utilizes `SessionRecord`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SessionRecord {
id: SessionId,
expiration_time: Option<OffsetDateTime>,
data: HashMap<String, Value>,
}
impl SessionRecord {
/// Gets the session ID.
pub fn id(&self) -> SessionId {
self.id
}
/// Gets the session expiration time.
pub fn expiration_time(&self) -> Option<OffsetDateTime> {
self.expiration_time
}
}
impl From<&Session> for SessionRecord {
fn from(session: &Session) -> Self {
let session_guard = session.inner.lock();
Self {
id: session.id,
expiration_time: session.expiration_time,
data: session_guard.data.clone(),
}
}
}