AuthStateManager

Struct AuthStateManager 

Source
pub struct AuthStateManager { /* private fields */ }
Expand description

Centralized authentication state management for the application.

Manages authentication state, token caching, and refresh services across the entire application. Provides thread-safe access to authentication providers and tokens with automatic expiration handling.

§Features

  • Thread-safe state management with RwLock
  • Token caching with automatic expiration
  • Authentication provider management
  • Token refresh service integration
  • Device code flow support

§Examples

use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

// Check authentication status
if !auth_manager.is_authenticated().await {
    // Start authentication process
}

// Get cached tokens
if let Some(token) = auth_manager.get_azure_ad_token().await {
    // Use token for API calls
}

Implementations§

Source§

impl AuthStateManager

Source

pub fn new() -> Self

Creates a new authentication state manager.

§Returns

A new AuthStateManager with clean state and empty token cache

Source

pub async fn get_state(&self) -> AuthenticationState

Gets the current authentication state.

§Returns

The current AuthenticationState indicating the authentication status

Source

pub async fn set_device_code_pending(&self, info: DeviceCodeInfo)

Sets the authentication state to indicate device code flow is in progress.

This method is called when a device code authentication flow has been initiated and is waiting for user interaction to complete the authentication process.

§Arguments
  • info - Device code information including user code and verification URL
§Examples
use quetty_server::auth::{AuthStateManager, DeviceCodeInfo};
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());
let device_info = DeviceCodeInfo {
    device_code: "device123".to_string(),
    user_code: "ABC123".to_string(),
    verification_uri: "https://microsoft.com/devicelogin".to_string(),
    expires_in: 900,
    interval: 5,
    message: "Enter code ABC123 at https://microsoft.com/devicelogin".to_string(),
};

auth_manager.set_device_code_pending(device_info).await;
Source

pub async fn set_authenticated( &self, token: String, expires_in: Duration, connection_string: Option<String>, )

Source

pub async fn set_failed(&self, error: String)

Sets the authentication state to failed with an error message.

This method is called when authentication attempts fail, providing detailed error information that can be displayed to the user.

§Arguments
  • error - Human-readable error message describing the authentication failure
§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());
auth_manager.set_failed("Invalid credentials provided".to_string()).await;
Source

pub async fn logout(&self)

Logs out the user and clears all authentication state.

This method resets the authentication state to NotAuthenticated and clears all cached tokens and authentication providers. It also stops any running token refresh services.

§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

// After authentication...
auth_manager.logout().await;

// State is now reset
assert!(!auth_manager.is_authenticated().await);
Source

pub async fn is_authenticated(&self) -> bool

Checks if the user is currently authenticated.

§Returns

true if authentication is successful and active, false otherwise

Source

pub async fn needs_reauthentication(&self) -> bool

Checks if reauthentication is needed.

Returns true if the user is not authenticated or if the current authentication token expires within 5 minutes.

§Returns

true if reauthentication is required, false if current auth is still valid

Source

pub async fn get_azure_ad_token(&self) -> Option<String>

Retrieves a valid Azure AD access token if available.

Returns the cached Azure AD token if it exists and hasn’t expired. This token can be used for authenticating with Azure Service Bus and other Azure resources.

§Returns
  • Some(token) - Valid Azure AD access token
  • None - No token available or token has expired
§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

if let Some(token) = auth_manager.get_azure_ad_token().await {
    println!("Using Azure AD token: {}", token);
    // Use token for Service Bus operations
} else {
    println!("No valid Azure AD token available");
}
Source

pub async fn get_sas_token(&self) -> Option<String>

Retrieves a valid SAS token if available.

Returns the cached SAS (Shared Access Signature) token if it exists and hasn’t expired. SAS tokens are used for connection string-based authentication with Azure Service Bus.

§Returns
  • Some(token) - Valid SAS token
  • None - No token available or token has expired
§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

if let Some(sas_token) = auth_manager.get_sas_token().await {
    println!("Using SAS token: {}", sas_token);
    // Use token for Service Bus operations
} else {
    println!("No valid SAS token available");
}
Source

pub async fn set_sas_token(&self, token: String, expires_in: Duration)

Stores a SAS token with its expiration time.

Caches a SAS token for future use with automatic expiration handling. The token will be considered invalid after the specified duration.

§Arguments
  • token - The SAS token string to cache
  • expires_in - Duration until the token expires
§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;
use std::time::Duration;

let auth_manager = Arc::new(AuthStateManager::new());
let token = "SharedAccessSignature sr=...".to_string();
let expires_in = Duration::from_secs(24 * 3600); // 24 hours

auth_manager.set_sas_token(token, expires_in).await;
Source

pub async fn get_connection_string(&self) -> Option<String>

Retrieves the connection string from the current authentication state.

Returns the connection string if the user is authenticated and a connection string is available in the authentication state.

§Returns
  • Some(connection_string) - Valid connection string for Service Bus
  • None - No connection string available or not authenticated
§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

if let Some(conn_str) = auth_manager.get_connection_string().await {
    println!("Using connection string: {}", conn_str);
    // Use connection string for Service Bus operations
}
Source

pub async fn get_device_code_info(&self) -> Option<DeviceCodeInfo>

Retrieves device code information if device code flow is in progress.

Returns the device code information (user code, verification URL, etc.) if a device code authentication flow is currently active.

§Returns
  • Some(DeviceCodeInfo) - Device code flow information
  • None - No device code flow is currently active
§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

if let Some(device_info) = auth_manager.get_device_code_info().await {
    println!("Go to: {}", device_info.verification_uri);
    println!("Enter code: {}", device_info.user_code);
}
Source

pub async fn set_service_bus_provider(&self, provider: Arc<dyn AuthProvider>)

Sets the authentication provider for Service Bus operations.

Configures the authentication provider that will be used for Service Bus data plane operations (sending/receiving messages).

§Arguments
  • provider - Authentication provider for Service Bus operations
§Examples
use quetty_server::auth::{AuthStateManager, AzureAdProvider};
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());
let provider = Arc::new(AzureAdProvider::new(config, client)?);

auth_manager.set_service_bus_provider(provider).await;
Source

pub async fn get_service_bus_provider(&self) -> Option<Arc<dyn AuthProvider>>

Retrieves the current Service Bus authentication provider.

Returns the authentication provider configured for Service Bus data plane operations if one has been set.

§Returns
  • Some(provider) - Configured Service Bus authentication provider
  • None - No provider has been configured
§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

if let Some(provider) = auth_manager.get_service_bus_provider().await {
    let token = provider.authenticate().await?;
    // Use token for Service Bus operations
}
Source

pub async fn set_management_provider(&self, provider: Arc<dyn AuthProvider>)

Sets the authentication provider for Service Bus management operations.

Configures the authentication provider that will be used for Service Bus management plane operations (creating queues, topics, etc.).

§Arguments
  • provider - Authentication provider for management operations
§Examples
use quetty_server::auth::{AuthStateManager, AzureAdProvider};
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());
let provider = Arc::new(AzureAdProvider::new(config, client)?);

auth_manager.set_management_provider(provider).await;
Source

pub async fn get_management_provider(&self) -> Option<Arc<dyn AuthProvider>>

Retrieves the current Service Bus management authentication provider.

Returns the authentication provider configured for Service Bus management plane operations if one has been set.

§Returns
  • Some(provider) - Configured management authentication provider
  • None - No provider has been configured
§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

if let Some(provider) = auth_manager.get_management_provider().await {
    let token = provider.authenticate().await?;
    // Use token for management operations
}
Source

pub fn get_token_cache(&self) -> &TokenCache

Gets a reference to the token cache.

§Returns

A reference to the TokenCache for manual token management

Source

pub async fn start_refresh_service(self: Arc<Self>)

Starts the automatic token refresh service.

Initiates a background service that automatically refreshes tokens before they expire, ensuring continuous authentication without user intervention.

§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

// Start automatic token refresh
auth_manager.clone().start_refresh_service().await;

// Tokens will now be refreshed automatically in the background
Source

pub async fn start_refresh_service_with_callback( self: Arc<Self>, failure_callback: Option<RefreshFailureCallback>, )

Source

pub async fn stop_refresh_service(&self)

Stops the automatic token refresh service.

Gracefully shuts down the background token refresh service, stopping automatic token renewal. Tokens will no longer be refreshed automatically after calling this method.

§Examples
use quetty_server::auth::AuthStateManager;
use std::sync::Arc;

let auth_manager = Arc::new(AuthStateManager::new());

// Start refresh service
auth_manager.clone().start_refresh_service().await;

// Later, stop the service
auth_manager.stop_refresh_service().await;

Trait Implementations§

Source§

impl Default for AuthStateManager

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

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<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<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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: 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: 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> 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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> SendBound for T
where T: Send,