hyprstream_core/services/oauth/
session.rs1use std::collections::HashMap;
7use std::time::{Duration, Instant};
8
9use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
10use rand::RngCore;
11use tokio::sync::RwLock;
12
13#[derive(Debug, Clone)]
15pub struct Session {
16 pub username: String,
18 pub auth_method: String,
20 pub atproto_did: Option<String>,
22 pub verified_tenant: Option<String>,
24 pub authenticated_at: Instant,
26 pub expires_at: Instant,
28}
29
30pub struct SessionStore {
32 sessions: RwLock<HashMap<String, Session>>,
33 ttl: Duration,
34}
35
36pub const SESSION_COOKIE_NAME: &str = "hyprstream_session";
37
38impl SessionStore {
39 pub fn new(ttl_seconds: u64) -> Self {
40 Self {
41 sessions: RwLock::new(HashMap::new()),
42 ttl: Duration::from_secs(ttl_seconds),
43 }
44 }
45
46 pub async fn create(&self, username: String, auth_method: String) -> String {
48 let mut id_bytes = [0u8; 32];
49 rand::rngs::OsRng.fill_bytes(&mut id_bytes);
50 let session_id = URL_SAFE_NO_PAD.encode(id_bytes);
51
52 let session = Session {
53 username,
54 auth_method,
55 atproto_did: None,
56 verified_tenant: None,
57 authenticated_at: Instant::now(),
58 expires_at: Instant::now() + self.ttl,
59 };
60
61 self.sessions
62 .write()
63 .await
64 .insert(session_id.clone(), session);
65 session_id
66 }
67
68 pub async fn create_atproto(&self, did: String, verified_tenant: Option<String>) -> String {
70 let mut id_bytes = [0u8; 32];
71 rand::rngs::OsRng.fill_bytes(&mut id_bytes);
72 let session_id = URL_SAFE_NO_PAD.encode(id_bytes);
73 let session = Session {
74 username: did.clone(),
75 auth_method: "atproto".to_owned(),
76 atproto_did: Some(did),
77 verified_tenant,
78 authenticated_at: Instant::now(),
79 expires_at: Instant::now() + self.ttl,
80 };
81 self.sessions
82 .write()
83 .await
84 .insert(session_id.clone(), session);
85 session_id
86 }
87
88 pub async fn get(&self, session_id: &str) -> Option<Session> {
90 let sessions = self.sessions.read().await;
91 sessions.get(session_id).and_then(|s| {
92 if s.expires_at > Instant::now() {
93 Some(s.clone())
94 } else {
95 None
96 }
97 })
98 }
99
100 pub async fn remove(&self, session_id: &str) {
102 self.sessions.write().await.remove(session_id);
103 }
104
105 pub async fn sweep(&self) {
107 let now = Instant::now();
108 self.sessions
109 .write()
110 .await
111 .retain(|_, s| s.expires_at > now);
112 }
113}
114
115impl Default for SessionStore {
116 fn default() -> Self {
117 Self::new(8 * 3600) }
119}
120
121pub fn extract_session_id(headers: &axum::http::HeaderMap) -> Option<String> {
123 let prefix = format!("{SESSION_COOKIE_NAME}=");
124 headers
125 .get(axum::http::header::COOKIE)
126 .and_then(|v| v.to_str().ok())
127 .and_then(|cookies| {
128 cookies
129 .split(';')
130 .map(str::trim)
131 .find_map(|cookie| cookie.strip_prefix(&prefix))
132 .filter(|session_id| !session_id.is_empty())
133 .map(String::from)
134 })
135}
136
137pub fn session_cookie(session_id: &str, secure: bool) -> String {
139 let secure_flag = if secure { "; Secure" } else { "" };
140 format!(
141 "{SESSION_COOKIE_NAME}={session_id}; HttpOnly; SameSite=Lax; Path=/{secure_flag}; Max-Age=28800"
142 )
143}
144
145pub fn clear_session_cookie() -> String {
147 format!("{SESSION_COOKIE_NAME}=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0")
148}