actix_extended_session/storage/
session_key.rs

1use std::convert::TryFrom;
2
3use derive_more::{Display, From};
4
5/// A session key, the string stored in a client-side cookie to associate a user with its session
6/// state on the backend.
7///
8/// # Validation
9/// Session keys are stored as cookies, therefore they cannot be arbitrary long. Session keys are
10/// required to be smaller than 4064 bytes.
11///
12/// ```rust
13/// # use std::convert::TryInto;
14/// use actix_extended_session::storage::SessionKey;
15///
16/// let key: String = std::iter::repeat('a').take(4065).collect();
17/// let session_key: Result<SessionKey, _> = key.try_into();
18/// assert!(session_key.is_err());
19/// ```
20#[derive(Debug, Display, PartialEq, Eq)]
21pub struct SessionKey(String);
22
23impl TryFrom<String> for SessionKey {
24    type Error = InvalidSessionKeyError;
25
26    fn try_from(val: String) -> Result<Self, Self::Error> {
27        if val.len() > 4064 {
28            return Err(anyhow::anyhow!(
29                "The session key is bigger than 4064 bytes, the upper limit on cookie content."
30            )
31            .into());
32        }
33
34        Ok(SessionKey(val))
35    }
36}
37
38impl AsRef<str> for SessionKey {
39    fn as_ref(&self) -> &str {
40        &self.0
41    }
42}
43
44impl From<SessionKey> for String {
45    fn from(key: SessionKey) -> Self {
46        key.0
47    }
48}
49
50#[derive(Debug, Display, From)]
51#[display(fmt = "The provided string is not a valid session key")]
52pub struct InvalidSessionKeyError(anyhow::Error);
53
54impl std::error::Error for InvalidSessionKeyError {
55    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
56        Some(self.0.as_ref())
57    }
58}