Skip to main content

auth_framework/auth_modular/
session_manager.rs

1//! Session management module
2
3use 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
10/// Session manager for handling user sessions
11pub struct SessionManager {
12    storage: Arc<dyn AuthStorage>,
13}
14
15impl SessionManager {
16    /// Create a new session manager
17    pub fn new(storage: Arc<dyn AuthStorage>) -> Self {
18        Self { storage }
19    }
20
21    /// Create a new session
22    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        // Validate session duration
32        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            // 1 year max
41            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    /// Get session information
62    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        // Check if session is expired
71        if let Some(ref session_data) = session
72            && session_data.is_expired()
73        {
74            // Remove expired session
75            let _ = self.delete_session(session_id).await;
76            return Ok(None);
77        }
78
79        Ok(session)
80    }
81
82    /// Delete a session
83    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    /// Update session last activity
98    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    /// Get all sessions for a user
107    pub async fn get_user_sessions(&self, user_id: &str) -> Result<Vec<(String, SessionData)>> {
108        // Note: This would require storage backend support for querying by user_id
109        // For now, return empty vector as this would be a more complex implementation
110        debug!("Getting all sessions for user '{}'", user_id);
111        Ok(vec![])
112    }
113
114    /// Delete all sessions for a user
115    pub async fn delete_user_sessions(&self, user_id: &str) -> Result<()> {
116        debug!("Deleting all sessions for user '{}'", user_id);
117
118        // Get user sessions and delete them
119        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    /// Clean up expired sessions
129    pub async fn cleanup_expired_sessions(&self) -> Result<()> {
130        debug!("Cleaning up expired sessions");
131
132        // This would require storage backend support for bulk cleanup
133        // For now, this is handled by the storage implementation's cleanup_expired method
134        Ok(())
135    }
136
137    /// Validate session and return user info
138    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            // Update last activity
143            let _ = self.update_session_activity(session_id).await;
144            return Ok(Some(session.user_id));
145        }
146        Ok(None)
147    }
148
149    /// Extend session expiration
150    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    /// Count the number of currently active sessions
171    /// Used for security audit statistics
172    pub async fn count_active_sessions(&self) -> Result<u64> {
173        debug!("Counting active sessions");
174
175        // Use the storage layer's count_active_sessions method
176        let active_count = self.storage.count_active_sessions().await?;
177
178        debug!("Found {} active sessions", active_count);
179        Ok(active_count)
180    }
181
182    /// Get security metrics for sessions
183    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}