nutt_web/modules/session/cookie_session/
mod.rs1mod session_data;
2
3use crate::modules::session::cookie_session::session_data::Data;
4use base64ct::Encoding;
5use std::collections::HashMap;
6use std::fmt::{Display, Formatter};
7use std::sync::{Arc, RwLock};
8use whirlpool::{Digest, Whirlpool};
9
10#[derive(Debug, Clone)]
11pub struct CookieSession {
12 sessions: Arc<RwLock<HashMap<SessionId, Data>>>,
13}
14
15impl CookieSession {
16 pub fn set_data_by_id<T: Sync + Send + 'static>(&self, id: SessionId, item: (&str, T)) {
17 if let Ok(mut session) = self.sessions.try_write() {
18 if let Some(data) = session.get_mut(&id) {
19 data.set(item.0, item.1)
20 }
21 }
22 }
23}
24
25impl CookieSession {
26 pub fn new() -> Self {
27 Self {
28 sessions: Arc::new(RwLock::new(HashMap::new())),
29 }
30 }
31
32 pub fn create_new_session(&mut self) -> SessionId {
33 let id = SessionId::new();
34 if let Ok(mut session) = self.sessions.clone().try_write() {
35 session.insert(id.clone(), Data::new());
36 };
37 id
38 }
39
40 pub fn get_session_data(&self, id: SessionId) -> Option<Data> {
41 if let Ok(session) = self.sessions.try_read() {
42 return if let Some(data) = session.get(&id) {
43 Some(data.clone())
44 } else {
45 None
46 };
47 }
48 None
49 }
50}
51
52#[derive(Hash, Clone, Eq, PartialEq, Debug)]
53pub struct SessionId(String);
54
55impl SessionId {
56 pub fn new() -> Self {
57 let mut hasher = Whirlpool::new();
58 hasher.update(chrono::Utc::now().to_string().as_bytes());
59 Self(base64ct::Base64::encode_string(&hasher.finalize()))
60 }
61}
62
63impl Display for SessionId {
64 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
65 write!(f, "{}", self.0)
66 }
67}
68
69impl From<String> for SessionId {
70 fn from(value: String) -> Self {
71 Self(value)
72 }
73}