Struct Auth

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

Authentication client for handling user sessions and JWT tokens

Implementations§

Source§

impl Auth

Source

pub fn new( config: Arc<SupabaseConfig>, http_client: Arc<HttpClient>, ) -> Result<Self>

Create a new Auth instance

Source

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

Source

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

Source

pub async fn sign_in_with_email_and_password( &self, email: &str, password: &str, ) -> Result<AuthResponse>

Sign in with email and password

Source

pub async fn sign_out(&self) -> Result<()>

Sign out the current user

Source

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

Reset password via email

Source

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

Source

pub async fn update_user( &self, email: Option<String>, password: Option<String>, data: Option<Value>, ) -> Result<AuthResponse>

Update the current user’s information

Source

pub async fn refresh_session(&self) -> Result<AuthResponse>

Refresh the current session token

Source

pub async fn current_user(&self) -> Result<Option<User>>

Get the current user information

Source

pub fn get_session(&self) -> Result<Session>

Get the current session

Source

pub async fn set_session(&self, session: Session) -> Result<()>

Set a new session

Source

pub async fn set_session_token(&self, token: &str) -> Result<()>

Set session from JWT token

Source

pub async fn clear_session(&self) -> Result<()>

Clear the current session

Source

pub fn is_authenticated(&self) -> bool

Check if the user is authenticated

Source

pub fn needs_refresh(&self) -> bool

Check if the current token needs refresh

Source

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

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

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

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");
}

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

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

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

pub fn on_auth_state_change<F>(&self, callback: F) -> AuthEventHandle
where F: Fn(AuthEvent, Option<Session>) + Send + Sync + 'static,

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

pub fn remove_auth_listener(&self, id: Uuid)

Remove an authentication state listener

Source

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

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

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

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

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

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

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

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

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

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

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

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§

Source§

impl Clone for Auth

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Auth

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

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> 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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. 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> 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> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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: 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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
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,