pub struct UserManager { /* private fields */ }Expand description
User manager for handling user operations.
§Example
use auth_framework::auth_modular::UserManager;
use auth_framework::config::PasswordHashAlgorithm;
let um = UserManager::new(storage.clone(), PasswordHashAlgorithm::Argon2);
let uid = um.register_user("alice", "alice@example.com", "Str0ng!Pass").await?;Implementations§
Source§impl UserManager
impl UserManager
Sourcepub fn new(
storage: Arc<dyn AuthStorage>,
password_hash_algorithm: PasswordHashAlgorithm,
) -> Self
pub fn new( storage: Arc<dyn AuthStorage>, password_hash_algorithm: PasswordHashAlgorithm, ) -> Self
Create a new user manager that hashes new/changed passwords with
password_hash_algorithm. Verification is unaffected by this
setting – it detects the stored hash’s own format, so existing
users keep verifying correctly across an algorithm change.
Computes a dummy password hash under password_hash_algorithm once,
synchronously, before returning – this blocks the calling thread
for roughly the same time as one real hash operation (measured:
~39ms for Argon2id with this crate’s parameters, ~366ms for
bcrypt’s default cost; Scrypt returns immediately since it has
no implementation and the dummy hash is simply absent in that
case). This is a one-time, per-instance cost, not per-request.
§Example
let um = UserManager::new(storage.clone(), PasswordHashAlgorithm::Argon2);Sourcepub fn with_api_key_roles(self, roles: Vec<String>) -> Self
pub fn with_api_key_roles(self, roles: Vec<String>) -> Self
Set the roles an API key may carry (default: admin, user, api_user).
Role names are compared exactly (case and whitespace included). Narrowing the set makes existing
keys whose role left it fail validation, and keys created without a role carry api_user, so
leave that in the set unless no such key exists.
Minting a key with a privileged role is an authorization decision for the caller of
Self::create_api_key_with_role; this type does not know who is asking.
Sourcepub async fn create_api_key(
&self,
user_id: &str,
expires_in: Option<Duration>,
) -> Result<String>
pub async fn create_api_key( &self, user_id: &str, expires_in: Option<Duration>, ) -> Result<String>
Sourcepub async fn create_api_key_with_role(
&self,
user_id: &str,
role: &str,
expires_in: Option<Duration>,
) -> Result<String>
pub async fn create_api_key_with_role( &self, user_id: &str, role: &str, expires_in: Option<Duration>, ) -> Result<String>
Create an API key that carries role, which Self::validate_api_key returns for it.
role must be one of the allowed roles (see Self::with_api_key_roles); anything else,
including a different case or surrounding whitespace, is an error and nothing is stored.
§Example
let key = um.create_api_key_with_role("user-1", "admin", None).await?;Sourcepub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo>
pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo>
Sourcepub async fn revoke_api_key(&self, api_key: &str) -> Result<()>
pub async fn revoke_api_key(&self, api_key: &str) -> Result<()>
Sourcepub async fn rotate_api_key(&self, old_key: &str) -> Result<String>
pub async fn rotate_api_key(&self, old_key: &str) -> Result<String>
Replace an API key with a new one that has the same user and role.
Returns the new raw key, once; the old key stops validating. The new key’s lifetime is as long
as the old key’s was (a key that never expired still never expires), counted from now. Use
Self::rotate_api_key_with_expiry to choose the lifetime.
§Semantics
A revoked, expired, unknown, or role-no-longer-permitted key is refused and nothing is created.
On a backend whose AuthStorage::supports_atomic_swap is true (memory, SQLite, PostgreSQL,
Redis, and the encrypted wrapper over them) the old key’s rows are replaced by the new key’s
row in ONE swap_kv: the old key or the new key is live, never both and never neither,
whatever dies or races (the in-process memory backends are atomic with respect to other
rotations, not to a concurrent reader). Of several simultaneous rotations exactly one succeeds
and the others get Invalid API key. The rest of this section describes the fallback for
backends without a swap.
Otherwise the steps are: (1) claim the rotation with an atomic store_kv_if_absent (so
of several simultaneous rotations of one key exactly one proceeds and the rest get an
error); (2) store the new key INERT (it authenticates nobody); (3) delete the old key; (4)
make the new key live; (5) release the claim.
- If step 3 fails, the new key is deleted again and an error is returned, so on every returned
result exactly one of the two keys is valid: the old key on
Err, the new key onOk. - Two keys are never live at once, also across a crash. A process that dies before step 3 completes leaves the old key as the only live one (the claim expires after 60 seconds, so a retry is possible); one that dies after step 3 and before step 4 leaves NO live key, the caller never having received the new one, and the user creates another. An inert row is removed by its TTL on backends that track one.
- “Never both and never neither” would need a storage-level transaction; this is not one.
- The storage backend must implement
store_kv_if_absentatomically; one that does not makes this method fail rather than rotate without the single-winner guarantee.
Who may rotate a key is the caller’s authorization decision.
§Example
let new_key = um.rotate_api_key("ak_abc123").await?;Sourcepub async fn rotate_api_key_with_expiry(
&self,
old_key: &str,
expires_in: Option<Duration>,
) -> Result<String>
pub async fn rotate_api_key_with_expiry( &self, old_key: &str, expires_in: Option<Duration>, ) -> Result<String>
Like Self::rotate_api_key, but the new key lives for expires_in (None: no expiry)
instead of the old key’s lifetime.
Sourcepub async fn validate_username(&self, username: &str) -> Result<bool>
pub async fn validate_username(&self, username: &str) -> Result<bool>
Sourcepub async fn validate_display_name(&self, display_name: &str) -> Result<bool>
pub async fn validate_display_name(&self, display_name: &str) -> Result<bool>
Sourcepub async fn validate_password_strength(&self, password: &str) -> Result<bool>
pub async fn validate_password_strength(&self, password: &str) -> Result<bool>
Sourcepub async fn validate_user_input(&self, input: &str) -> Result<bool>
pub async fn validate_user_input(&self, input: &str) -> Result<bool>
Validate user input for security.
Combines a character whitelist with pattern checks for common injection vectors. Rejects HTML tags, null bytes, path traversal sequences, template injection markers, and dangerous URI schemes.
§Example
assert!(um.validate_user_input("hello world").await?);
assert!(!um.validate_user_input("<script>alert(1)</script>").await?);Sourcepub async fn get_user_info(&self, user_id: &str) -> Result<UserInfo>
pub async fn get_user_info(&self, user_id: &str) -> Result<UserInfo>
Sourcepub async fn list_users(
&self,
limit: Option<usize>,
offset: Option<usize>,
active_only: bool,
) -> Result<Vec<UserInfo>>
pub async fn list_users( &self, limit: Option<usize>, offset: Option<usize>, active_only: bool, ) -> Result<Vec<UserInfo>>
Sourcepub async fn user_exists(&self, user_id: &str) -> Result<bool>
pub async fn user_exists(&self, user_id: &str) -> Result<bool>
Sourcepub async fn register_user(
&self,
username: &str,
email: &str,
password: &str,
) -> Result<String>
pub async fn register_user( &self, username: &str, email: &str, password: &str, ) -> Result<String>
Sourcepub async fn delete_user(&self, username: &str) -> Result<()>
pub async fn delete_user(&self, username: &str) -> Result<()>
Sourcepub async fn delete_user_by_id(&self, user_id: &str) -> Result<()>
pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()>
Sourcepub async fn verify_user_password(
&self,
user_id: &str,
password: &str,
) -> Result<bool>
pub async fn verify_user_password( &self, user_id: &str, password: &str, ) -> Result<bool>
Verify a user’s password against the stored hash.
Detects whether the stored hash is bcrypt or Argon2id from its own
prefix and verifies against that format, independent of the
currently configured PasswordHashAlgorithm. This is deliberate:
changing the configured algorithm must not break verification for
users whose password was hashed under the old one.
§Example
let ok = um.verify_user_password("user-1", "secret").await?;
assert!(ok);Sourcepub async fn get_username_by_id(&self, user_id: &str) -> Result<String>
pub async fn get_username_by_id(&self, user_id: &str) -> Result<String>
Sourcepub async fn username_exists(&self, username: &str) -> Result<bool>
pub async fn username_exists(&self, username: &str) -> Result<bool>
Sourcepub async fn email_exists(&self, email: &str) -> Result<bool>
pub async fn email_exists(&self, email: &str) -> Result<bool>
Sourcepub async fn get_user_profile(&self, user_id: &str) -> Result<ProviderProfile>
pub async fn get_user_profile(&self, user_id: &str) -> Result<ProviderProfile>
Sourcepub async fn verify_login_credentials(
&self,
username: &str,
password: &str,
) -> Result<Option<CredentialCheckResult>>
pub async fn verify_login_credentials( &self, username: &str, password: &str, ) -> Result<Option<CredentialCheckResult>>
Verify username/password credentials in a timing-safe manner.
Returns Ok(None) when the credentials are invalid — a dummy
verification (under the configured algorithm, against a hash
precomputed once at construction) is always executed when the
username is not found, so callers cannot distinguish missing users
from wrong passwords via timing for a manager whose stored users
all hash under the currently configured algorithm. Returns
Ok(Some(result)) on success.
Known gap: mid-migration timing oracle. The dummy hash always follows the configured algorithm, while a real existing user verifies under whatever algorithm their own stored hash actually is. If a deployment changes its configured algorithm without rehashing existing users (this crate never rehashes on login), a legacy user’s wrong-password check costs their old algorithm’s verify time while an unknown username costs the new one’s – e.g. a Bcrypt-configured manager with legacy Argon2id users shows ~39ms for a real wrong-password check vs. ~390ms for an unknown username (and the reverse, Argon2-configured with legacy Bcrypt users). This is not fixed by this crate and is not fixable without rehashing on login (a separate, larger change): the oracle this function closes is closed only once every stored user’s hash matches the currently configured algorithm.
§Example
match um.verify_login_credentials("alice", "password123").await? {
Some(cred) => println!("user_id={}, mfa={}", cred.user_id, cred.mfa_enabled),
None => println!("invalid credentials"),
}Auto Trait Implementations§
impl !RefUnwindSafe for UserManager
impl !UnwindSafe for UserManager
impl Freeze for UserManager
impl Send for UserManager
impl Sync for UserManager
impl Unpin for UserManager
impl UnsafeUnpin for UserManager
Blanket Implementations§
Source§impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedExplicit<'a, E> for Twhere
T: 'a,
Source§impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
impl<'a, T, E> AsTaggedImplicit<'a, E> for Twhere
T: 'a,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more