Skip to main content

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(Clone, Serialize, Deserialize)]
9pub struct UserContext {
10    pub user_id: String,
11    pub username: String,
12    pub email: Option<String>,
13    pub scopes: crate::types::Scopes,
14    pub authenticated_at: std::time::SystemTime,
15    pub session_id: String,
16    pub attributes: crate::types::UserAttributesString,
17}
18
19impl std::fmt::Debug for UserContext {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        let mut d = f.debug_struct("UserContext");
22        d.field("user_id", &self.user_id);
23        d.field("username", &self.username);
24        d.field("email", &self.email);
25        d.field("scopes", &self.scopes);
26        d.field("authenticated_at", &self.authenticated_at);
27        d.field(
28            "session_id",
29            &crate::utils::redact::redacted(&self.session_id),
30        );
31        d.field("attributes", &self.attributes);
32        d.finish()
33    }
34}
35
36impl UserContext {
37    pub fn new(user_id: String, username: String, email: Option<String>) -> Self {
38        Self {
39            user_id,
40            username,
41            email,
42            scopes: crate::types::Scopes::empty(),
43            authenticated_at: std::time::SystemTime::now(),
44            session_id: Uuid::new_v4().to_string(),
45            attributes: crate::types::UserAttributesString::empty(),
46        }
47    }
48
49    pub fn with_scopes(mut self, scopes: Vec<String>) -> Self {
50        self.scopes = scopes.into();
51        self
52    }
53
54    pub fn add_attribute(&mut self, key: String, value: String) {
55        self.attributes.insert(key, value);
56    }
57
58    pub fn has_scope(&self, scope: &str) -> bool {
59        self.scopes.contains(scope)
60    }
61}
62
63/// Session store for managing user authentication state
64impl UserContext {
65    /// Create a new builder for UserContext
66    pub fn builder(user_id: impl Into<String>, username: impl Into<String>) -> UserContextBuilder {
67        UserContextBuilder::new(user_id.into(), username.into())
68    }
69}
70
71/// A builder for UserContext
72pub struct UserContextBuilder {
73    user_id: String,
74    username: String,
75    email: Option<String>,
76    scopes: Vec<String>,
77    attributes: HashMap<String, String>,
78}
79
80impl UserContextBuilder {
81    pub fn new(user_id: String, username: String) -> Self {
82        Self {
83            user_id,
84            username,
85            email: None,
86            scopes: Vec::new(),
87            attributes: HashMap::new(),
88        }
89    }
90
91    pub fn email(mut self, email: impl Into<String>) -> Self {
92        self.email = Some(email.into());
93        self
94    }
95
96    pub fn scope(mut self, scope: impl Into<String>) -> Self {
97        self.scopes.push(scope.into());
98        self
99    }
100
101    pub fn scopes(mut self, scopes: Vec<String>) -> Self {
102        self.scopes = scopes;
103        self
104    }
105
106    pub fn attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
107        self.attributes.insert(key.into(), value.into());
108        self
109    }
110
111    pub fn build(self) -> UserContext {
112        let mut ctx = UserContext::new(self.user_id, self.username, self.email);
113        ctx.scopes = self.scopes.into();
114        ctx.attributes = self.attributes.into();
115        ctx
116    }
117}
118
119#[derive(Clone)]
120pub struct SessionStore {
121    sessions: std::collections::HashMap<String, UserContext>,
122}
123
124impl std::fmt::Debug for SessionStore {
125    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
126        let mut d = f.debug_struct("SessionStore");
127        d.field("sessions", &crate::utils::redact::redacted(&self.sessions));
128        d.finish()
129    }
130}
131
132impl SessionStore {
133    pub fn new() -> Self {
134        Self {
135            sessions: HashMap::new(),
136        }
137    }
138
139    pub fn create_session(&mut self, user_context: UserContext) -> String {
140        let session_id = user_context.session_id.clone();
141        self.sessions.insert(session_id.clone(), user_context);
142        session_id
143    }
144
145    pub fn get_session(&self, session_id: &str) -> Option<&UserContext> {
146        self.sessions.get(session_id)
147    }
148
149    pub fn invalidate_session(&mut self, session_id: &str) -> bool {
150        self.sessions.remove(session_id).is_some()
151    }
152
153    pub fn validate_session(&self, session_id: &str) -> bool {
154        self.sessions.contains_key(session_id)
155    }
156}
157
158impl Default for SessionStore {
159    fn default() -> Self {
160        Self::new()
161    }
162}