auth_framework/auth_modular/
session_manager.rs1use crate::errors::{AuthError, Result};
4use crate::storage::{AuthStorage, SessionData};
5use std::collections::HashMap;
6use std::sync::Arc;
7use std::time::Duration;
8use tracing::{debug, info};
9
10pub struct SessionManager {
12 storage: Arc<dyn AuthStorage>,
13}
14
15impl SessionManager {
16 pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
18 Self { storage }
19 }
20
21 pub async fn create_session(
23 &self,
24 user_id: &str,
25 expires_in: Duration,
26 ip_address: Option<String>,
27 user_agent: Option<String>,
28 ) -> Result<String> {
29 debug!("Creating session for user '{}'", user_id);
30
31 if expires_in.is_zero() {
33 return Err(AuthError::invalid_credential(
34 "session_duration",
35 "Session duration must be greater than zero",
36 ));
37 }
38
39 if expires_in > Duration::from_secs(365 * 24 * 60 * 60) {
40 return Err(AuthError::invalid_credential(
42 "session_duration",
43 "Session duration exceeds maximum allowed (1 year)",
44 ));
45 }
46
47 let session_id = crate::utils::string::generate_id(Some("sess"));
48 let session = SessionData::new(session_id.clone(), user_id, expires_in)
49 .with_metadata(ip_address, user_agent);
50
51 self.storage.store_session(&session_id, &session).await?;
52
53 info!(
54 "Session '{}' created for user '{}'",
55 crate::utils::redact::fingerprint(&session_id),
56 user_id
57 );
58 Ok(session_id)
59 }
60
61 pub async fn get_session(&self, session_id: &str) -> Result<Option<SessionData>> {
63 debug!(
64 "Getting session '{}'",
65 crate::utils::redact::fingerprint(session_id)
66 );
67
68 let session = self.storage.get_session(session_id).await?;
69
70 if let Some(ref session_data) = session
72 && session_data.is_expired()
73 {
74 let _ = self.delete_session(session_id).await;
76 return Ok(None);
77 }
78
79 Ok(session)
80 }
81
82 pub async fn delete_session(&self, session_id: &str) -> Result<()> {
84 debug!(
85 "Deleting session '{}'",
86 crate::utils::redact::fingerprint(session_id)
87 );
88
89 self.storage.delete_session(session_id).await?;
90 info!(
91 "Session '{}' deleted",
92 crate::utils::redact::fingerprint(session_id)
93 );
94 Ok(())
95 }
96
97 pub async fn update_session_activity(&self, session_id: &str) -> Result<()> {
99 if let Some(mut session) = self.storage.get_session(session_id).await? {
100 session.last_activity = chrono::Utc::now();
101 self.storage.store_session(session_id, &session).await?;
102 }
103 Ok(())
104 }
105
106 pub async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<(String, SessionData)>> {
108 debug!("Getting all sessions for user '{}'", user_id);
111 Ok(vec![])
112 }
113
114 pub async fn delete_user_sessions(&self, user_id: &str) -> Result<()> {
116 debug!("Deleting all sessions for user '{}'", user_id);
117
118 let sessions = self.get_user_sessions(user_id).await?;
120 for (session_id, _) in sessions {
121 let _ = self.delete_session(&session_id).await;
122 }
123
124 info!("All sessions deleted for user '{}'", user_id);
125 Ok(())
126 }
127
128 pub async fn cleanup_expired_sessions(&self) -> Result<()> {
130 debug!("Cleaning up expired sessions");
131
132 Ok(())
135 }
136
137 pub async fn validate_session(&self, session_id: &str) -> Result<Option<String>> {
139 if let Some(session) = self.get_session(session_id).await?
140 && !session.is_expired()
141 {
142 let _ = self.update_session_activity(session_id).await;
144 return Ok(Some(session.user_id));
145 }
146 Ok(None)
147 }
148
149 pub async fn extend_session(&self, session_id: &str, additional_time: Duration) -> Result<()> {
151 debug!(
152 "Extending session '{}' by {:?}",
153 crate::utils::redact::fingerprint(session_id),
154 additional_time
155 );
156
157 if let Some(mut session) = self.storage.get_session(session_id).await? {
158 session.expires_at += chrono::Duration::from_std(additional_time)
159 .map_err(|e| AuthError::internal(format!("Failed to convert duration: {}", e)))?;
160 self.storage.store_session(session_id, &session).await?;
161 info!(
162 "Session '{}' extended",
163 crate::utils::redact::fingerprint(session_id)
164 );
165 }
166
167 Ok(())
168 }
169
170 pub async fn count_active_sessions(&self) -> Result<u64> {
173 debug!("Counting active sessions");
174
175 let active_count = self.storage.count_active_sessions().await?;
177
178 debug!("Found {} active sessions", active_count);
179 Ok(active_count)
180 }
181
182 pub async fn get_session_security_metrics(&self) -> Result<HashMap<String, serde_json::Value>> {
184 debug!("Collecting session security metrics");
185
186 let mut metrics = HashMap::new();
187 let active_count = self.count_active_sessions().await?;
188
189 metrics.insert(
190 "active_sessions".to_string(),
191 serde_json::Value::Number(serde_json::Number::from(active_count)),
192 );
193 metrics.insert(
194 "last_check".to_string(),
195 serde_json::Value::String(chrono::Utc::now().to_rfc3339()),
196 );
197
198 Ok(metrics)
199 }
200}