Skip to main content

UserManager

Struct UserManager 

Source
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

Source

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);
Source

pub async fn create_api_key( &self, user_id: &str, expires_in: Option<Duration>, ) -> Result<String>

Create API key for a user.

§Example
ⓘ
let key = um.create_api_key("user-1", Some(Duration::from_secs(86400))).await?;
Source

pub async fn validate_api_key(&self, api_key: &str) -> Result<UserInfo>

Validate API key and return user information.

§Example
ⓘ
let info = um.validate_api_key("ak_abc123").await?;
println!("user: {}", info.username);
Source

pub async fn revoke_api_key(&self, api_key: &str) -> Result<()>

Revoke API key.

§Example
ⓘ
um.revoke_api_key("ak_abc123").await?;
Source

pub async fn validate_username(&self, username: &str) -> Result<bool>

Validate username format.

§Example
ⓘ
assert!(um.validate_username("alice").await?);
assert!(!um.validate_username("").await?);
Source

pub async fn validate_display_name(&self, display_name: &str) -> Result<bool>

Validate display name format.

§Example
ⓘ
assert!(um.validate_display_name("Alice B.").await?);
Source

pub async fn validate_password_strength(&self, password: &str) -> Result<bool>

Validate password strength using security policy.

Requires Strong or VeryStrong to protect production deployments.

§Example
ⓘ
assert!(um.validate_password_strength("C0mpl3x!Pa$$word").await?);
assert!(!um.validate_password_strength("weak").await?);
Source

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?);
Source

pub async fn get_user_info(&self, user_id: &str) -> Result<UserInfo>

Get user information by ID.

§Example
ⓘ
let info = um.get_user_info("user-1").await?;
println!("username: {}", info.username);
Source

pub async fn list_users( &self, limit: Option<usize>, offset: Option<usize>, active_only: bool, ) -> Result<Vec<UserInfo>>

List users from the canonical user index.

§Example
ⓘ
let users = um.list_users(Some(10), Some(0), true).await?;
for u in &users { println!("{}", u.username); }
Source

pub async fn user_exists(&self, user_id: &str) -> Result<bool>

Check if user exists.

§Example
ⓘ
if um.user_exists("user-1").await? {
    println!("user found");
}
Source

pub async fn register_user( &self, username: &str, email: &str, password: &str, ) -> Result<String>

Register a new user, creating all required storage records.

§Example
ⓘ
let uid = um.register_user("alice", "alice@example.com", "Str0ng!Pass").await?;
println!("registered user: {}", uid);
Source

pub async fn delete_user(&self, username: &str) -> Result<()>

Delete a user and all associated storage records.

§Example
ⓘ
um.delete_user("alice").await?;
Source

pub async fn delete_user_by_id(&self, user_id: &str) -> Result<()>

Delete a user by canonical user ID.

§Example
ⓘ
um.delete_user_by_id("user-1").await?;
Source

pub async fn update_user_roles( &self, user_id: &str, roles: &[String], ) -> Result<()>

Update the roles assigned to a user.

§Example
ⓘ
um.update_user_roles("user-1", &["admin".into(), "editor".into()]).await?;
Source

pub async fn set_user_active(&self, user_id: &str, active: bool) -> Result<()>

Enable or disable a user account.

§Example
ⓘ
um.set_user_active("user-1", false).await?; // disable
Source

pub async fn update_user_email(&self, user_id: &str, email: &str) -> Result<()>

Update the email address stored on a user.

§Example
ⓘ
um.update_user_email("user-1", "new@example.com").await?;
Source

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);
Source

pub async fn get_username_by_id(&self, user_id: &str) -> Result<String>

Resolve a user_id to its username.

§Example
ⓘ
let name = um.get_username_by_id("user-1").await?;
Source

pub async fn username_exists(&self, username: &str) -> Result<bool>

Check whether a username is already taken.

§Example
ⓘ
if um.username_exists("alice").await? {
    println!("taken");
}
Source

pub async fn email_exists(&self, email: &str) -> Result<bool>

Check whether an email address is already registered.

§Example
ⓘ
if um.email_exists("a@b.com").await? {
    println!("already registered");
}
Source

pub async fn get_user_by_username( &self, username: &str, ) -> Result<HashMap<String, Value>>

Fetch raw user data by username.

§Example
ⓘ
let data = um.get_user_by_username("alice").await?;
println!("email: {:?}", data.get("email"));
Source

pub async fn get_user_profile(&self, user_id: &str) -> Result<ProviderProfile>

Get a sanitised user profile (no password hash) for display/API.

§Example
ⓘ
let profile = um.get_user_profile("user-1").await?;
println!("email: {:?}", profile.email);
Source

pub async fn get_user_roles(&self, user_id: &str) -> Result<Vec<String>>

Get a user’s roles/scopes from storage, returning ["user"] as fallback.

§Example
ⓘ
let roles = um.get_user_roles("user-1").await?;
assert!(roles.contains(&"user".to_string()));
Source

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"),
}
Source

pub async fn update_user_password( &self, username: &str, new_password: &str, ) -> Result<()>

Update a user’s password by username.

§Example
ⓘ
um.update_user_password("alice", "N3wStr0ng!Pass").await?;
Source

pub async fn update_user_password_by_id( &self, user_id: &str, new_password: &str, ) -> Result<()>

Update a user password by canonical user ID.

§Example
ⓘ
um.update_user_password_by_id("user-1", "N3wStr0ng!Pass").await?;

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

Source§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

Source§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

Source§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more