Skip to main content

serenade_security/
user.rs

1//! User and security token traits.
2
3/// Authenticated (or anonymous) principal.
4pub trait UserInterface: Send + Sync {
5    /// Stable user identifier (login, UUID, …).
6    fn user_identifier(&self) -> &str;
7
8    /// Role names granted to this user.
9    fn roles(&self) -> &[String];
10}
11
12/// Simple in-memory user for apps and tests.
13#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct InMemoryUser {
15    id: String,
16    roles: Vec<String>,
17}
18
19impl InMemoryUser {
20    /// Creates a user with `id` and `roles`.
21    #[must_use]
22    pub fn new(id: impl Into<String>, roles: impl Into<Vec<String>>) -> Self {
23        Self {
24            id: id.into(),
25            roles: roles.into(),
26        }
27    }
28}
29
30impl UserInterface for InMemoryUser {
31    fn user_identifier(&self) -> &str {
32        &self.id
33    }
34
35    fn roles(&self) -> &[String] {
36        &self.roles
37    }
38}
39
40/// Security token carrying credentials and optional user.
41pub trait TokenInterface: Send + Sync {
42    /// Whether authentication succeeded.
43    fn is_authenticated(&self) -> bool;
44
45    /// Authenticated user when present.
46    fn user(&self) -> Option<&dyn UserInterface>;
47
48    /// Raw credentials string when present (bearer, API key, …).
49    fn credentials(&self) -> Option<&str>;
50}
51
52/// Username/password-style token (also used for bearer/API key strings).
53#[derive(Debug, Clone)]
54pub struct UsernamePasswordToken {
55    user: Option<InMemoryUser>,
56    credentials: Option<String>,
57    authenticated: bool,
58}
59
60impl UsernamePasswordToken {
61    /// Anonymous unauthenticated token.
62    #[must_use]
63    pub const fn anonymous() -> Self {
64        Self {
65            user: None,
66            credentials: None,
67            authenticated: false,
68        }
69    }
70
71    /// Authenticated token for `user` with optional credential echo.
72    #[must_use]
73    pub fn authenticated(user: InMemoryUser, credentials: impl Into<String>) -> Self {
74        Self {
75            user: Some(user),
76            credentials: Some(credentials.into()),
77            authenticated: true,
78        }
79    }
80
81    /// Authenticated flag with no user (invalid; used to exercise login clear path).
82    #[cfg(test)]
83    #[must_use]
84    pub(crate) const fn authenticated_without_user() -> Self {
85        Self {
86            user: None,
87            credentials: None,
88            authenticated: true,
89        }
90    }
91}
92
93impl TokenInterface for UsernamePasswordToken {
94    fn is_authenticated(&self) -> bool {
95        self.authenticated
96    }
97
98    fn user(&self) -> Option<&dyn UserInterface> {
99        self.user.as_ref().map(|user| user as &dyn UserInterface)
100    }
101
102    fn credentials(&self) -> Option<&str> {
103        self.credentials.as_deref()
104    }
105}