Struct AuthClient

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

Supabase Auth Client

Implementations§

Source§

impl AuthClient

Source

pub fn new( project_url: impl Into<String>, api_key: impl Into<String>, jwt_secret: impl Into<String>, ) -> Self

Create a new Auth Client You can find your project url and keys at https://supabase.com/dashboard/project/YOUR_PROJECT_ID/settings/api

§Example
let auth_client = AuthClient::new(project_url, api_key, jwt_secret).unwrap();
Source

pub fn new_from_env() -> Result<AuthClient, Error>

Create a new AuthClient from environment variables Requires SUPABASE_URL, SUPABASE_API_KEY, and SUPABASE_JWT_SECRET environment variables

§Example
let auth_client = AuthClient::new_from_env().unwrap();

assert!(auth_client.project_url == env::var("SUPABASE_URL").unwrap())
Source

pub async fn login_with_email( &self, email: &str, password: &str, ) -> Result<Session, Error>

Sign in a user with an email and password

§Example
let session = auth_client
    .login_with_email(demo_email, demo_password)
    .await
    .unwrap();

assert!(session.user.email == demo_email)
Source

pub async fn login_with_phone( &self, phone: &str, password: &str, ) -> Result<Session, Error>

Sign in a user with phone number and password

§Example
let session = auth_client
    .login_with_phone(demo_phone, demo_password)
    .await
    .unwrap();

assert!(session.user.phone == demo_phone)
Source

pub async fn sign_up_with_email_and_password( &self, email: &str, password: &str, options: Option<SignUpWithPasswordOptions>, ) -> Result<EmailSignUpResult, Error>

Sign up a new user with an email and password

§Example
let result = auth_client
    .sign_up_with_email_and_password(demo_email, demo_password)
    .await
    .unwrap();

assert!(result.session.user.email == demo_email)
Source

pub async fn sign_up_with_phone_and_password( &self, phone: &str, password: &str, options: Option<SignUpWithPasswordOptions>, ) -> Result<Session, Error>

Sign up a new user with an email and password

§Example
let session = auth_client
    .sign_up_with_phone_and_password(demo_phone, demo_password)
    .await
    .unwrap();

assert!(session.user.phone == demo_phone)
Source

pub async fn login_anonymously( &self, options: Option<LoginAnonymouslyOptions>, ) -> Result<Session, Error>

Sign in a new user anonymously. This actually signs up a user, but it’s called “sign in” by Supabase in their own client, so that’s why it’s named like this here. You can also pass in the same signup options that work for the other sign_up_* methods, but that’s not required.

This method requires anonymous sign in to be enabled in your dashboard.

§Example
let session = auth_client
    .login_anonymously(demo_options)
    .await
    .unwrap();

assert!(session.user.user_metadata.display_name == demo_options.data.display_name)

Sends a login email containing a magic link

§Example
let _response = auth_client
    .send_login_email_with_magic_link(demo_email)
   .await
   .unwrap();
Source

pub async fn send_sms_with_otp(&self, phone: &str) -> Result<OTPResponse, Error>

Send a Login OTP via SMS

§Example
let response = auth_client.send_sms_with_otp(demo_phone).await;
Source

pub async fn send_email_with_otp( &self, email: &str, options: Option<LoginEmailOtpParams>, ) -> Result<OTPResponse, Error>

Send a Login OTP via email

Returns an OTPResponse on success

§Example
let send = auth_client.send_sms_with_otp(demo_phone).await.unwrap();
Source

pub fn login_with_oauth( &self, provider: Provider, options: Option<LoginWithOAuthOptions>, ) -> Result<OAuthResponse, Error>

Sign in a user using an OAuth provider.

§Example
// You can add custom parameters using a HashMap<String, String>
let mut params = HashMap::new();
params.insert("key".to_string(), "value".to_string());

let options = LoginWithOAuthOptions {
    query_params: Some(params),
    redirect_to: Some("localhost".to_string()),
    scopes: Some("repo gist notifications".to_string()),
    skip_brower_redirect: Some(true),
};

let response = auth_client
    .login_with_oauth(supabase_auth::models::Provider::Github, Some(options))
    .unwrap();
Source

pub fn sign_up_with_oauth( &self, provider: Provider, options: Option<LoginWithOAuthOptions>, ) -> Result<OAuthResponse, Error>

Sign up a user using an OAuth provider.

§Example
// You can add custom parameters using a HashMap<String, String>
let mut params = HashMap::new();
params.insert("key".to_string(), "value".to_string());

let options = LoginWithOAuthOptions {
    query_params: Some(params),
    redirect_to: Some("localhost".to_string()),
    scopes: Some("repo gist notifications".to_string()),
    skip_brower_redirect: Some(true),
};

let response = auth_client
    .sign_up_with_oauth(supabase_auth::models::Provider::Github, Some(options))
    .unwrap();
Source

pub async fn get_user(&self, bearer_token: &str) -> Result<User, Error>

Return the signed in User

§Example
let user = auth_client
    .get_user(session.unwrap().access_token)
    .await
    .unwrap();

assert!(user.email == demo_email)
Source

pub async fn update_user( &self, updated_user: UpdatedUser, bearer_token: &str, ) -> Result<User, Error>

Update the user, such as changing email or password. Each field (email, password, and data) is optional

§Example
let updated_user_data = UpdateUserPayload {
    email: Some("demo@demo.com".to_string()),
    password: Some("demo_password".to_string()),
    data: None, // This field can hold any valid JSON value
};

let user = auth_client
    .update_user(updated_user_data, access_token)
    .await
    .unwrap();
Source

pub async fn login_with_id_token( &self, credentials: IdTokenCredentials, ) -> Result<Session, Error>

Allows signing in with an OIDC ID token. The authentication provider used should be enabled and configured.

§Example
let credentials = IdTokenCredentials {
    provider: Provider::Github,
    token: "<id-token-from-auth-provider>",
};

let session = auth_client
    .login_with_id_token(credentials)
    .await
    .unwrap();
Source

pub async fn invite_user_by_email( &self, email: &str, data: Option<Value>, bearer_token: &str, ) -> Result<User, Error>

Sends an invite link to an email address. Requires admin permissions to issue invites

The data field corresponds to the raw_user_meta_data User field

§Example
let demo_email = env::var("DEMO_INVITE").unwrap();

let user = auth_client
    .invite_user_by_email(&demo_email, None, auth_client.api_key())
    .await
    .unwrap();
Source

pub async fn verify_otp( &self, params: VerifyOtpParams, ) -> Result<Session, Error>

Verify the OTP sent to the user

§Example
let params = VerifyEmailOtpParams {
    token: "abc123",
    otp_type: OtpType::EmailChange,
    options: None,
};

let session = auth_client
    .verify_otp(params)
    .await
    .unwrap();
Source

pub async fn get_health(&self) -> Result<AuthServerHealth, Error>

Check the Health Status of the Auth Server

§Example
let health = auth_client
    .get_health()
    .await
    .unwrap();
Source

pub async fn get_settings(&self) -> Result<AuthServerSettings, Error>

Retrieve the public settings of the server

§Example
let settings = auth_client
    .get_settings()
    .await
    .unwrap();
Source

pub async fn exchange_token_for_session( &self, refresh_token: &str, ) -> Result<Session, Error>

Exchange refresh token for a new session

§Example
// When a user signs in they get a session
let original_session = auth_client
    .login_with_email_and_password(demo_email.as_ref(), demo_password)
    .await
    .unwrap();

// Exchange the refresh token from the original session to create a new session
let new_session = auth_client
    .refresh_session(original_session.refresh_token)
    .await
    .unwrap();
Source

pub async fn refresh_session( &self, refresh_token: &str, ) -> Result<Session, Error>

Source

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

Send a password recovery email. Invalid Email addresses will return Error Code 400. Valid email addresses that are not registered as users will not return an error.

§Example
let response = auth_client.reset_password_for_email(demo_email, None).await.unwrap();
Source

pub async fn resend(&self, credentials: ResendParams) -> Result<(), Error>

Resends emails for existing signup confirmation, email change, SMS OTP, or phone change OTP.

§Example
// Resend can also take MobileResendParams
let credentials = DesktopResendParams {
    otp_type: supabase_auth::models::EmailOtpType::Email,
    email: demo_email.to_owned(),
    options: None,
};

let resend = auth_client.resend(ResendParams::Desktop(credentials)).await;
Source

pub async fn logout( &self, scope: Option<LogoutScope>, bearer_token: &str, ) -> Result<(), Error>

Logs out a user with a given scope

§Example
auth_client.logout(Some(LogoutScope::Global), session.access_token).await.unwrap();
Source

pub async fn sso(&self, params: LoginWithSSO) -> Result<Url, Error>

Initiates an SSO Login Flow Returns the URL where the user must authenticate with the SSO Provider

WARNING: Requires an SSO Provider and Supabase Pro plan

§Example
let url = auth_client.sso(params).await.unwrap();

println!("{}", url.to_string());
Source

pub fn project_url(&self) -> &str

Get the project URL from an AuthClient

Source

pub fn api_key(&self) -> &str

Get the API Key from an AuthClient

Source

pub fn jwt_secret(&self) -> &str

Get the JWT Secret from an AuthClient

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,