auth_framework/
user_context.rs

1//! User context and authentication state management
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use uuid::Uuid;
6
7/// Represents authenticated user context
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct UserContext {
10    pub user_id: String,
11    pub username: String,
12    pub email: Option<String>,
13    pub scopes: Vec<String>,
14    pub authenticated_at: std::time::SystemTime,
15    pub session_id: String,
16    pub attributes: HashMap<String, String>,
17}
18
19impl UserContext {
20    pub fn new(user_id: String, username: String, email: Option<String>) -> Self {
21        Self {
22            user_id,
23            username,
24            email,
25            scopes: Vec::new(),
26            authenticated_at: std::time::SystemTime::now(),
27            session_id: Uuid::new_v4().to_string(),
28            attributes: HashMap::new(),
29        }
30    }
31
32    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
33        self.scopes = scopes;
34        self
35    }
36
37    pub fn add_attribute(&mut self, key: String, value: String) {
38        self.attributes.insert(key, value);
39    }
40
41    pub fn has_scope(&self, scope: &str) -> bool {
42        self.scopes.contains(&scope.to_string())
43    }
44}
45
46/// Session store for managing user authentication state
47#[derive(Debug, Clone)]
48pub struct SessionStore {
49    sessions: std::collections::HashMap<String, UserContext>,
50}
51
52impl SessionStore {
53    pub fn new() -> Self {
54        Self {
55            sessions: HashMap::new(),
56        }
57    }
58
59    pub fn create_session(&mut self, user_context: UserContext) -> String {
60        let session_id = user_context.session_id.clone();
61        self.sessions.insert(session_id.clone(), user_context);
62        session_id
63    }
64
65    pub fn get_session(&self, session_id: &str) -> Option<&UserContext> {
66        self.sessions.get(session_id)
67    }
68
69    pub fn invalidate_session(&mut self, session_id: &str) -> bool {
70        self.sessions.remove(session_id).is_some()
71    }
72
73    pub fn validate_session(&self, session_id: &str) -> bool {
74        self.sessions.contains_key(session_id)
75    }
76}
77
78impl Default for SessionStore {
79    fn default() -> Self {
80        Self::new()
81    }
82}
83
84