Skip to main content

axum_security/cookie/
id.rs

1use std::borrow::Cow;
2
3use cookie_monster::Cookie;
4use uuid::Uuid;
5
6/// Unique identifier for a cookie session, stored as the cookie value.
7///
8/// Generated as a UUID v7 by default.
9#[derive(Debug, Hash, Clone, PartialEq, Eq)]
10pub struct SessionId(Box<str>);
11
12impl SessionId {
13    pub fn new() -> Self {
14        SessionId(Uuid::now_v7().to_string().into_boxed_str())
15    }
16
17    pub fn from_cookie(cookie: &Cookie) -> Self {
18        SessionId(cookie.value().into())
19    }
20
21    pub fn as_str(&self) -> &str {
22        &self.0
23    }
24}
25
26impl From<SessionId> for Cow<'static, str> {
27    fn from(value: SessionId) -> Self {
28        Cow::Owned(value.0.into_string())
29    }
30}
31
32impl From<String> for SessionId {
33    fn from(value: String) -> Self {
34        Self(value.into_boxed_str())
35    }
36}
37
38impl Default for SessionId {
39    fn default() -> Self {
40        Self::new()
41    }
42}