Struct AuthClient

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

The main authentication client for interacting with Supabase Auth API

This client handles all authentication operations including user signup, signin, token management, and user administration.

Implementations§

Source§

impl AuthClient

Source

pub async fn soft_delete_user(&self, user_id: Uuid) -> Result<(), AuthError>

Soft deletes a user, marking them as deleted but preserving their data

This operation requires a service role key to be configured on the AuthClient. The user will be marked as deleted but their data will be retained in the database.

§Arguments
  • user_id - The UUID of the user to soft delete
§Errors

Returns AuthError::ServiceRoleKeyRequired if no service role key is configured. Returns AuthError::Http if the API request fails.

§Example
let admin_client = AuthClient::builder()
    .api_url("https://your-project.supabase.co")
    .anon_key("your-anon-key")
    .service_role_key("your-service-role-key")
    .build()?;

let user_id = Uuid::parse_str("123e4567-e89b-12d3-a456-426614174000").unwrap();
admin_client.soft_delete_user(user_id).await?;
Source

pub async fn hard_delete_user(&self, user_id: Uuid) -> Result<(), AuthError>

Permanently deletes a user and all their associated data

This operation requires a service role key to be configured on the AuthClient. The user and all their data will be permanently removed from the database. This action cannot be undone.

§Arguments
  • user_id - The UUID of the user to permanently delete
§Errors

Returns AuthError::ServiceRoleKeyRequired if no service role key is configured. Returns AuthError::Http if the API request fails.

§Example
let admin_client = AuthClient::builder()
    .api_url("https://your-project.supabase.co")
    .anon_key("your-anon-key")
    .service_role_key("your-service-role-key")
    .build()?;

let user_id = Uuid::parse_str("123e4567-e89b-12d3-a456-426614174000").unwrap();
admin_client.hard_delete_user(user_id).await?;
Source§

impl AuthClient

Source

pub async fn get_user_by_token( &self, auth_token: &str, ) -> Result<UserSchema, AuthError>

Retrieves user information using an authentication token

This method validates the provided access token and returns the associated user’s information. It’s commonly used to verify that a token is valid and to get the current user’s details.

§Arguments
  • auth_token - A valid JWT access token
§Errors

Returns AuthError::InvalidParameters if the token is empty. Returns AuthError::NotAuthorized if the token is invalid or expired. Returns AuthError::Http if the API request fails.

§Example
let client = AuthClient::new("https://your-project.supabase.co", "your-anon-key")?;

// After user signs in and you have their access token
let user = client.get_user_by_token("user-access-token").await?;
println!("User email: {:?}", user.email);
Source

pub async fn get_user_by_id( &self, user_id: Uuid, ) -> Result<Option<UserSchema>, AuthError>

Retrieves user information by user ID

This method fetches a user’s information directly from the database using their UUID. Note: This requires appropriate permissions and may need a service role key depending on your Row Level Security policies.

§Arguments
  • user_id - The UUID of the user to retrieve
§Returns

Returns Ok(Some(user)) if the user exists, Ok(None) if not found.

§Errors

Returns AuthError::Http if the database query fails.

§Example
let client = AuthClient::new("https://your-project.supabase.co", "your-anon-key")?;

let user_id = Uuid::parse_str("123e4567-e89b-12d3-a456-426614174000").unwrap();
if let Some(user) = client.get_user_by_id(user_id).await? {
    println!("Found user: {:?}", user.email);
}
Source§

impl AuthClient

Source

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

Logs out a user by invalidating their authentication token

This method revokes the provided access token, effectively logging the user out. After calling this method, the token will no longer be valid for authentication.

§Arguments
  • token - The access token to invalidate
§Errors

Returns AuthError::Http if the API request fails.

§Example
let client = AuthClient::new("https://your-project.supabase.co", "your-anon-key")?;

// After user signs in and you have their access token
let access_token = "user-access-token";
client.logout(access_token).await?;

// The token is now invalid and cannot be used for authentication
Source§

impl AuthClient

Source

pub async fn refresh_token( &self, token: &str, ) -> Result<TokenResponse, AuthError>

Refreshes an authentication token to obtain new access and refresh tokens

This method exchanges a valid refresh token for a new set of tokens, extending the user’s session without requiring them to sign in again. The new access token can be used for API authentication.

§Arguments
  • token - A valid refresh token obtained from signin or a previous refresh
§Returns

Returns a TokenResponse containing new access and refresh tokens.

§Errors

Returns AuthError::InvalidParameters if the token is empty. Returns AuthError::NotAuthorized if the refresh token is invalid or expired. Returns AuthError::Http if the API request fails.

§Example
let client = AuthClient::new("https://your-project.supabase.co", "your-anon-key")?;

// After user signs in, you have their refresh token
let refresh_token = "user-refresh-token";
let new_tokens = client.refresh_token(refresh_token).await?;

println!("New access token: {}", new_tokens.access_token);
println!("New refresh token: {}", new_tokens.refresh_token);
Source§

impl AuthClient

Source

pub async fn signin_with_password( &self, id: IdType, password: String, ) -> Result<TokenResponse, AuthError>

Signs in a user with their email/phone and password

This method authenticates a user using their credentials and returns authentication tokens that can be used for subsequent API requests.

§Arguments
  • id - The user’s identifier (email or phone number)
  • password - The user’s password
§Returns

Returns a TokenResponse containing access and refresh tokens on successful authentication.

§Errors

Returns AuthError::InvalidParameters if email/phone or password is empty. Returns AuthError::NotAuthorized if credentials are invalid. Returns AuthError::Http if the API request fails.

§Example
let client = AuthClient::new("https://your-project.supabase.co", "your-anon-key")?;

let tokens = client
    .signin_with_password(
        IdType::Email("user@example.com".to_string()),
        "secure_password".to_string(),
    )
    .await?;

println!("Access token: {}", tokens.access_token);
Source§

impl AuthClient

Source

pub async fn signup( &self, signup_id_type: IdType, password: String, _metadata: Option<HashMap<String, String>>, ) -> Result<(UserSchema, String), AuthError>

Creates a new user account

This method registers a new user with the provided credentials and optional metadata. Upon successful registration, the user is automatically signed in and authentication tokens are returned.

§Arguments
  • signup_id_type - The user’s identifier (email or phone number)
  • password - The desired password for the account
  • metadata - Optional user metadata to store with the account
§Returns

Returns a tuple containing:

  • The newly created UserSchema with user information
  • An access token string for immediate authentication
§Errors

Returns AuthError::InvalidParameters if required fields are missing. Returns AuthError::Http if the API request fails or user already exists.

§Example
let client = AuthClient::new("https://your-project.supabase.co", "your-anon-key")?;

let mut metadata = HashMap::new();
metadata.insert("first_name".to_string(), "John".to_string());
metadata.insert("last_name".to_string(), "Doe".to_string());

let (user, access_token) = client
    .signup(
        IdType::Email("newuser@example.com".to_string()),
        "secure_password".to_string(),
        Some(metadata),
    )
    .await?;

println!("User created with ID: {}", user.id);
Source§

impl AuthClient

Source

pub fn new(api_url: &str, anon_key: &str) -> Result<Self, AuthError>

Creates a new authentication client with the given API URL and anonymous key

§Arguments
  • api_url - The base URL of your Supabase instance
  • anon_key - The anonymous key for your Supabase project
§Example
use supabase_auth_redux::AuthClient;

let client = AuthClient::new("https://your-project.supabase.co", "your-anon-key")
    .expect("Failed to create auth client");
Source

pub fn builder() -> AuthClientBuilder

Creates a new builder for constructing an AuthClient with additional options

§Example
use supabase_auth_redux::AuthClient;

let client = AuthClient::builder()
    .api_url("https://your-project.supabase.co")
    .anon_key("your-anon-key")
    .service_role_key("your-service-role-key")
    .build()
    .expect("Failed to create auth client");

Trait Implementations§

Source§

impl Clone for AuthClient

Source§

fn clone(&self) -> AuthClient

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 AuthClient

Source§

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

Formats the value using the given formatter. 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> 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> 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> 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<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,