pub struct Auth { /* private fields */ }
Expand description
Authentication client for handling user sessions and JWT tokens
Implementations§
Source§impl Auth
impl Auth
Sourcepub fn new(
config: Arc<SupabaseConfig>,
http_client: Arc<HttpClient>,
) -> Result<Self>
pub fn new( config: Arc<SupabaseConfig>, http_client: Arc<HttpClient>, ) -> Result<Self>
Create a new Auth instance
Sourcepub async fn sign_up_with_email_and_password(
&self,
email: &str,
password: &str,
) -> Result<AuthResponse>
pub async fn sign_up_with_email_and_password( &self, email: &str, password: &str, ) -> Result<AuthResponse>
Sign up a new user with email and password
Sourcepub async fn sign_up_with_email_password_and_data(
&self,
email: &str,
password: &str,
data: Option<Value>,
redirect_to: Option<String>,
) -> Result<AuthResponse>
pub async fn sign_up_with_email_password_and_data( &self, email: &str, password: &str, data: Option<Value>, redirect_to: Option<String>, ) -> Result<AuthResponse>
Sign up a new user with email, password, and optional metadata
Sourcepub async fn sign_in_with_email_and_password(
&self,
email: &str,
password: &str,
) -> Result<AuthResponse>
pub async fn sign_in_with_email_and_password( &self, email: &str, password: &str, ) -> Result<AuthResponse>
Sign in with email and password
Sourcepub async fn reset_password_for_email(&self, email: &str) -> Result<()>
pub async fn reset_password_for_email(&self, email: &str) -> Result<()>
Reset password via email
Sourcepub async fn reset_password_for_email_with_redirect(
&self,
email: &str,
redirect_to: Option<String>,
) -> Result<()>
pub async fn reset_password_for_email_with_redirect( &self, email: &str, redirect_to: Option<String>, ) -> Result<()>
Reset password via email with optional redirect URL
Sourcepub async fn update_user(
&self,
email: Option<String>,
password: Option<String>,
data: Option<Value>,
) -> Result<AuthResponse>
pub async fn update_user( &self, email: Option<String>, password: Option<String>, data: Option<Value>, ) -> Result<AuthResponse>
Update the current user’s information
Sourcepub async fn refresh_session(&self) -> Result<AuthResponse>
pub async fn refresh_session(&self) -> Result<AuthResponse>
Refresh the current session token
Sourcepub async fn current_user(&self) -> Result<Option<User>>
pub async fn current_user(&self) -> Result<Option<User>>
Get the current user information
Sourcepub fn get_session(&self) -> Result<Session>
pub fn get_session(&self) -> Result<Session>
Get the current session
Sourcepub async fn set_session(&self, session: Session) -> Result<()>
pub async fn set_session(&self, session: Session) -> Result<()>
Set a new session
Sourcepub async fn set_session_token(&self, token: &str) -> Result<()>
pub async fn set_session_token(&self, token: &str) -> Result<()>
Set session from JWT token
Sourcepub async fn clear_session(&self) -> Result<()>
pub async fn clear_session(&self) -> Result<()>
Clear the current session
Sourcepub fn is_authenticated(&self) -> bool
pub fn is_authenticated(&self) -> bool
Check if the user is authenticated
Sourcepub fn needs_refresh(&self) -> bool
pub fn needs_refresh(&self) -> bool
Check if the current token needs refresh
Sourcepub async fn sign_in_with_oauth(
&self,
provider: OAuthProvider,
options: Option<OAuthOptions>,
) -> Result<OAuthResponse>
pub async fn sign_in_with_oauth( &self, provider: OAuthProvider, options: Option<OAuthOptions>, ) -> Result<OAuthResponse>
Sign in with OAuth provider
Returns a URL that the user should be redirected to for authentication. After successful authentication, the user will be redirected back with the session.
§Example
use supabase::auth::{OAuthProvider, OAuthOptions};
let client = supabase::Client::new("url", "key")?;
let options = OAuthOptions {
redirect_to: Some("https://myapp.com/callback".to_string()),
scopes: Some(vec!["email".to_string(), "profile".to_string()]),
..Default::default()
};
let response = client.auth().sign_in_with_oauth(OAuthProvider::Google, Some(options)).await?;
println!("Redirect to: {}", response.url);
Sourcepub async fn sign_up_with_phone(
&self,
phone: &str,
password: &str,
data: Option<Value>,
) -> Result<AuthResponse>
pub async fn sign_up_with_phone( &self, phone: &str, password: &str, data: Option<Value>, ) -> Result<AuthResponse>
Sign up with phone number
§Example
let client = supabase::Client::new("url", "key")?;
let response = client.auth()
.sign_up_with_phone("+1234567890", "securepassword", None)
.await?;
if let Some(user) = response.user {
println!("User created: {:?}", user.phone);
}
Sourcepub async fn sign_in_with_phone(
&self,
phone: &str,
password: &str,
) -> Result<AuthResponse>
pub async fn sign_in_with_phone( &self, phone: &str, password: &str, ) -> Result<AuthResponse>
Sign in with phone number
§Example
let client = supabase::Client::new("url", "key")?;
let response = client.auth()
.sign_in_with_phone("+1234567890", "securepassword")
.await?;
if let Some(user) = response.user {
println!("User signed in: {:?}", user.phone);
}
Sourcepub async fn verify_otp(
&self,
phone: &str,
token: &str,
verification_type: &str,
) -> Result<AuthResponse>
pub async fn verify_otp( &self, phone: &str, token: &str, verification_type: &str, ) -> Result<AuthResponse>
Verify OTP token
§Example
let client = supabase::Client::new("url", "key")?;
let response = client.auth()
.verify_otp("+1234567890", "123456", "sms")
.await?;
if let Some(session) = response.session {
println!("OTP verified, user signed in");
}
Sourcepub async fn sign_in_with_magic_link(
&self,
email: &str,
redirect_to: Option<String>,
data: Option<Value>,
) -> Result<()>
pub async fn sign_in_with_magic_link( &self, email: &str, redirect_to: Option<String>, data: Option<Value>, ) -> Result<()>
Send magic link for passwordless authentication
§Example
let client = supabase::Client::new("url", "key")?;
client.auth()
.sign_in_with_magic_link("user@example.com", Some("https://myapp.com/callback".to_string()), None)
.await?;
println!("Magic link sent to email");
Sourcepub async fn sign_in_anonymously(
&self,
data: Option<Value>,
) -> Result<AuthResponse>
pub async fn sign_in_anonymously( &self, data: Option<Value>, ) -> Result<AuthResponse>
Sign in anonymously
Creates a temporary anonymous user session that can be converted to a permanent account later.
§Example
let client = supabase::Client::new("url", "key")?;
let response = client.auth()
.sign_in_anonymously(None)
.await?;
if let Some(user) = response.user {
println!("Anonymous user created: {}", user.id);
}
Sourcepub async fn reset_password_for_email_enhanced(
&self,
email: &str,
redirect_to: Option<String>,
) -> Result<()>
pub async fn reset_password_for_email_enhanced( &self, email: &str, redirect_to: Option<String>, ) -> Result<()>
Enhanced password recovery with custom redirect and options
§Example
let client = supabase::Client::new("url", "key")?;
client.auth()
.reset_password_for_email_enhanced("user@example.com", Some("https://myapp.com/reset".to_string()))
.await?;
println!("Password reset email sent");
Sourcepub fn on_auth_state_change<F>(&self, callback: F) -> AuthEventHandle
pub fn on_auth_state_change<F>(&self, callback: F) -> AuthEventHandle
Subscribe to authentication state changes
Returns a handle that can be used to remove the listener later.
§Example
use supabase::auth::AuthEvent;
let client = supabase::Client::new("url", "key")?;
let handle = client.auth().on_auth_state_change(|event, session| {
match event {
AuthEvent::SignedIn => {
if let Some(session) = session {
println!("User signed in: {}", session.user.email.unwrap_or_default());
}
}
AuthEvent::SignedOut => println!("User signed out"),
AuthEvent::TokenRefreshed => println!("Token refreshed"),
_ => {}
}
});
// Later remove the listener
handle.remove();
Sourcepub fn remove_auth_listener(&self, id: Uuid)
pub fn remove_auth_listener(&self, id: Uuid)
Remove an authentication state listener
Sourcepub async fn list_mfa_factors(&self) -> Result<Vec<MfaFactor>>
pub async fn list_mfa_factors(&self) -> Result<Vec<MfaFactor>>
List all MFA factors for the current user
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// List MFA factors
let factors = client.auth().list_mfa_factors().await?;
println!("User has {} MFA factors configured", factors.len());
Sourcepub async fn setup_totp(&self, friendly_name: &str) -> Result<TotpSetupResponse>
pub async fn setup_totp(&self, friendly_name: &str) -> Result<TotpSetupResponse>
Setup TOTP (Time-based One-Time Password) authentication
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// Setup TOTP
let totp_setup = client.auth()
.setup_totp("My Authenticator")
.await?;
println!("Scan QR code: {}", totp_setup.qr_code);
println!("Or enter secret manually: {}", totp_setup.secret);
Sourcepub async fn setup_sms_mfa(
&self,
phone: &str,
friendly_name: &str,
default_region: Option<&str>,
) -> Result<MfaFactor>
pub async fn setup_sms_mfa( &self, phone: &str, friendly_name: &str, default_region: Option<&str>, ) -> Result<MfaFactor>
Setup SMS-based MFA with international phone number support
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// Setup SMS MFA with international number
let factor = client.auth()
.setup_sms_mfa("+1-555-123-4567", "My Phone", Some("US"))
.await?;
println!("SMS MFA configured for: {}", factor.phone.unwrap());
Sourcepub async fn create_mfa_challenge(
&self,
factor_id: Uuid,
) -> Result<MfaChallenge>
pub async fn create_mfa_challenge( &self, factor_id: Uuid, ) -> Result<MfaChallenge>
Create MFA challenge for a specific factor
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// Get factors and create challenge
let factors = client.auth().list_mfa_factors().await?;
if let Some(factor) = factors.first() {
let challenge = client.auth().create_mfa_challenge(factor.id).await?;
println!("Challenge created: {}", challenge.id);
}
Sourcepub async fn verify_mfa_challenge(
&self,
factor_id: Uuid,
challenge_id: Uuid,
code: &str,
) -> Result<AuthResponse>
pub async fn verify_mfa_challenge( &self, factor_id: Uuid, challenge_id: Uuid, code: &str, ) -> Result<AuthResponse>
Verify MFA challenge with user-provided code
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// Verify MFA code
let factor_id = Uuid::new_v4(); // Your factor ID
let challenge_id = Uuid::new_v4(); // Your challenge ID
let result = client.auth()
.verify_mfa_challenge(factor_id, challenge_id, "123456")
.await?;
println!("MFA verified successfully!");
Sourcepub async fn delete_mfa_factor(&self, factor_id: Uuid) -> Result<()>
pub async fn delete_mfa_factor(&self, factor_id: Uuid) -> Result<()>
Delete an MFA factor
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// Remove MFA factor
let factor_id = Uuid::new_v4(); // Your factor ID
client.auth().delete_mfa_factor(factor_id).await?;
println!("MFA factor removed successfully!");
Sourcepub fn generate_totp_code(&self, secret: &str) -> Result<String>
pub fn generate_totp_code(&self, secret: &str) -> Result<String>
Generate TOTP code for testing purposes (development only)
This method is primarily for testing and development. In production, users should use their authenticator apps.
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// For testing - generate TOTP code from secret
let secret = "JBSWY3DPEHPK3PXP"; // Base32 encoded secret
let code = client.auth().generate_totp_code(secret)?;
println!("Generated TOTP code: {}", code);
Sourcepub fn get_token_metadata(&self) -> Result<Option<TokenMetadata>>
pub fn get_token_metadata(&self) -> Result<Option<TokenMetadata>>
Get current token metadata with advanced information
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// Get detailed token metadata
if let Some(metadata) = client.auth().get_token_metadata()? {
println!("Token expires at: {}", metadata.expires_at);
println!("Refresh count: {}", metadata.refresh_count);
println!("Scopes: {:?}", metadata.scopes);
}
Sourcepub async fn refresh_token_advanced(&self) -> Result<Session>
pub async fn refresh_token_advanced(&self) -> Result<Session>
Refresh token with advanced error handling and retry logic
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// Refresh token with advanced handling
match client.auth().refresh_token_advanced().await {
Ok(session) => {
println!("Token refreshed successfully!");
println!("New expiry: {}", session.expires_at);
}
Err(e) => {
if e.is_retryable() {
// Handle retryable error
println!("Retryable error: {}", e);
} else {
// Handle non-retryable error - require re-login
println!("Re-authentication required: {}", e);
}
}
}
Sourcepub fn needs_refresh_with_buffer(&self, buffer_seconds: i64) -> Result<bool>
pub fn needs_refresh_with_buffer(&self, buffer_seconds: i64) -> Result<bool>
Check if current token needs refresh with buffer time
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
// Check if refresh is needed with 5-minute buffer
if client.auth().needs_refresh_with_buffer(300)? {
println!("Token refresh recommended");
client.auth().refresh_token_advanced().await?;
}
Sourcepub fn time_until_expiry(&self) -> Result<Option<i64>>
pub fn time_until_expiry(&self) -> Result<Option<i64>>
Get time until token expiry in seconds
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
match client.auth().time_until_expiry()? {
Some(seconds) => {
println!("Token expires in {} seconds", seconds);
if seconds < 300 {
println!("Consider refreshing token soon!");
}
}
None => println!("No active session"),
}
Sourcepub fn validate_token_local(&self) -> Result<bool>
pub fn validate_token_local(&self) -> Result<bool>
Validate current token without making API call (local validation)
§Examples
let client = Client::new("https://example.supabase.co", "your-anon-key")?;
match client.auth().validate_token_local() {
Ok(true) => println!("Token is valid locally"),
Ok(false) => println!("Token is expired or invalid"),
Err(e) => println!("Validation error: {}", e),
}
Trait Implementations§
Auto Trait Implementations§
impl Freeze for Auth
impl !RefUnwindSafe for Auth
impl Send for Auth
impl Sync for Auth
impl Unpin for Auth
impl !UnwindSafe for Auth
Blanket Implementations§
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
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
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