supabase_auth/client.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
/*!
The `client` module provides a comprehensive interface for interacting with Supabase Authentication services.
This module enables user authentication, session management, user administration, and server health monitoring
through the [`AuthClient`] struct.
# Notes
- Some features require Supabase Pro plan subscription
- OAuth and SSO require configuration in Supabase dashboard
- Rate limiting may apply to authentication operations
- Always use HTTPS in production environments
- Properly handle token expiration and refresh cycles
*/
use std::env;
use reqwest::{
header::{self, HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE},
Client, Url,
};
use serde_json::{from_str, Value};
use crate::{
error::Error::{self, AuthError},
models::{
AuthClient, AuthServerHealth, AuthServerSettings, IdTokenCredentials, InviteParams,
LoginAnonymouslyPayload, LoginEmailOtpParams, LoginWithEmailAndPasswordPayload,
LoginWithEmailOtpPayload, LoginWithOAuthOptions, LoginWithPhoneAndPasswordPayload,
LoginWithSSO, LogoutScope, OAuthResponse, OTPResponse, Provider, RefreshSessionPayload,
RequestMagicLinkPayload, ResendParams, ResetPasswordForEmailPayload, SendSMSOtpPayload,
Session, SignUpWithEmailAndPasswordPayload, SignUpWithPasswordOptions,
SignUpWithPhoneAndPasswordPayload, UpdatedUser, User, VerifyOtpParams, AUTH_V1,
},
};
impl AuthClient {
/// 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();
/// ```
pub fn new(
project_url: impl Into<String>,
api_key: impl Into<String>,
jwt_secret: impl Into<String>,
) -> Self {
AuthClient {
client: Client::new(),
project_url: project_url.into(),
api_key: api_key.into(),
jwt_secret: jwt_secret.into(),
}
}
/// 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())
/// ```
pub fn new_from_env() -> Result<AuthClient, Error> {
let project_url = env::var("SUPABASE_URL")?;
let api_key = env::var("SUPABASE_API_KEY")?;
let jwt_secret = env::var("SUPABASE_JWT_SECRET")?;
Ok(AuthClient {
client: Client::new(),
project_url,
api_key,
jwt_secret,
})
}
/// 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)
/// ```
pub async fn login_with_email(&self, email: &str, password: &str) -> Result<Session, Error> {
let payload = LoginWithEmailAndPasswordPayload { email, password };
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&payload)?;
let response = self
.client
.post(format!(
"{}{}/token?grant_type=password",
self.project_url, AUTH_V1
))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let session: Session = from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(session)
}
/// 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)
/// ```
pub async fn login_with_phone(&self, phone: &str, password: &str) -> Result<Session, Error> {
let payload = LoginWithPhoneAndPasswordPayload { phone, password };
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&payload)?;
let response = self
.client
.post(format!(
"{}{}/token?grant_type=password",
self.project_url, AUTH_V1
))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let session: Session = from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(session)
}
/// Sign up a new user with an email and password
/// # Example
/// ```
/// let session = auth_client
/// .sign_up_with_email_and_password(demo_email, demo_password)
/// .await
/// .unwrap();
///
/// assert!(session.user.email == demo_email)
///```
pub async fn sign_up_with_email_and_password(
&self,
email: &str,
password: &str,
options: Option<SignUpWithPasswordOptions>,
) -> Result<Session, Error> {
let payload = SignUpWithEmailAndPasswordPayload {
email,
password,
options,
};
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&payload)?;
let response = self
.client
.post(format!("{}{}/signup", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let session: Session = from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(session)
}
/// 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)
///```
pub async fn sign_up_with_phone_and_password(
&self,
phone: &str,
password: &str,
options: Option<SignUpWithPasswordOptions>,
) -> Result<Session, Error> {
let payload = SignUpWithPhoneAndPasswordPayload {
phone,
password,
options,
};
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&payload)?;
let response = self
.client
.post(format!("{}{}/signup", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let session: Session = from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(session)
}
/// 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)
/// ```
pub async fn login_anonymously(
&self,
options: Option<SignUpWithPasswordOptions>,
) -> Result<Session, Error> {
let payload = LoginAnonymouslyPayload { options };
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&payload)?;
let response = self
.client
.post(format!("{}{}/signup", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let session: Session = from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(session)
}
/// Sends a login email containing a magic link
/// # Example
/// ```
/// let _response = auth_client
/// .send_login_email_with_magic_link(demo_email)
/// .await
/// .unwrap();
///```
pub async fn send_login_email_with_magic_link(&self, email: &str) -> Result<(), Error> {
let payload = RequestMagicLinkPayload { email };
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&payload)?;
let response = self
.client
.post(format!("{}{}/magiclink", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
if res_status.is_success() {
Ok(())
} else {
Err(AuthError {
status: res_status,
message: res_body,
})
}
}
/// Send a Login OTP via SMS
///
/// # Example
/// ```
/// let response = auth_client.send_sms_with_otp(demo_phone).await;
/// ```
pub async fn send_sms_with_otp(&self, phone: &str) -> Result<OTPResponse, Error> {
let payload = SendSMSOtpPayload { phone };
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&payload)?;
let response = self
.client
.post(format!("{}{}/otp", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
if res_status.is_success() {
let message = serde_json::from_str(&res_body)?;
Ok(message)
} else {
Err(AuthError {
status: res_status,
message: res_body,
})
}
}
/// Send a Login OTP via email
///
/// Returns an OTPResponse on success
/// # Example
/// ```
/// let send = auth_client.send_sms_with_otp(demo_phone).await.unwrap();
/// ```
pub async fn send_email_with_otp(
&self,
email: &str,
options: Option<LoginEmailOtpParams>,
) -> Result<OTPResponse, Error> {
let payload = LoginWithEmailOtpPayload { email, options };
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&payload)?;
let response = self
.client
.post(format!("{}{}/otp", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
if res_status.is_success() {
let message = serde_json::from_str(&res_body)?;
Ok(message)
} else {
Err(AuthError {
status: res_status,
message: res_body,
})
}
}
/// 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))
/// .await
/// .unwrap();
/// ```
pub async fn login_with_oauth(
&self,
provider: Provider,
options: Option<LoginWithOAuthOptions>,
) -> Result<OAuthResponse, Error> {
let mut headers = header::HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string(&options)?;
let response = self
.client
.get(format!(
"{}{}/authorize?provider={}",
self.project_url, AUTH_V1, provider
))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let url = response.url().to_owned();
let res_body = response.text().await?;
if res_status.is_success() {
Ok(OAuthResponse { url, provider })
} else {
Err(AuthError {
status: res_status,
message: res_body,
})
}
}
/// 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))
/// .await
/// .unwrap();
/// ```
pub async fn sign_up_with_oauth(
&self,
provider: Provider,
options: Option<LoginWithOAuthOptions>,
) -> Result<OAuthResponse, Error> {
self.login_with_oauth(provider, options).await
}
/// Return the signed in User
/// # Example
/// ```
/// let user = auth_client
/// .get_user(session.unwrap().access_token)
/// .await
/// .unwrap();
///
/// assert!(user.email == demo_email)
/// ```
pub async fn get_user(&self, bearer_token: &str) -> Result<User, Error> {
let mut headers = header::HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", bearer_token))?,
);
let response = self
.client
.get(format!("{}{}/user", self.project_url, AUTH_V1))
.headers(headers)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let user: User = serde_json::from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(user)
}
/// 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();
/// ```
pub async fn update_user(
&self,
updated_user: UpdatedUser,
bearer_token: &str,
) -> Result<User, Error> {
let mut headers = header::HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", bearer_token))?,
);
let body = serde_json::to_string::<UpdatedUser>(&updated_user)?;
let response = self
.client
.put(format!("{}{}/user", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let user: User = serde_json::from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(user)
}
/// 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();
/// ```
pub async fn login_with_id_token(
&self,
credentials: IdTokenCredentials,
) -> Result<Session, Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
let body = serde_json::to_string(&credentials)?;
let response = self
.client
.post(format!(
"{}{}/token?grant_type=id_token",
self.project_url, AUTH_V1
))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let session: Session = serde_json::from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(session)
}
/// 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();
///```
pub async fn invite_user_by_email(
&self,
email: &str,
data: Option<Value>,
bearer_token: &str,
) -> Result<User, Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", bearer_token))?,
);
let invite_payload = InviteParams {
email: email.into(),
data,
};
let body = serde_json::to_string(&invite_payload)?;
let response = self
.client
.post(format!("{}{}/invite", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let user: User = serde_json::from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(user)
}
/// 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();
///```
pub async fn verify_otp(&self, params: VerifyOtpParams) -> Result<Session, Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
let body = serde_json::to_string(¶ms)?;
let response = self
.client
.post(&format!("{}{}/verify", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let session: Session = serde_json::from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(session)
}
/// Check the Health Status of the Auth Server
/// # Example
/// ```
/// let health = auth_client
/// .get_health()
/// .await
/// .unwrap();
/// ```
pub async fn get_health(&self) -> Result<AuthServerHealth, Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let response = self
.client
.get(&format!("{}{}/health", self.project_url, AUTH_V1))
.headers(headers)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let health: AuthServerHealth = serde_json::from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(health)
}
/// Retrieve the public settings of the server
/// # Example
/// ```
/// let settings = auth_client
/// .get_settings()
/// .await
/// .unwrap();
/// ```
pub async fn get_settings(&self) -> Result<AuthServerSettings, Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let response = self
.client
.get(&format!("{}{}/settings", self.project_url, AUTH_V1))
.headers(headers)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let settings: AuthServerSettings =
serde_json::from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(settings)
}
/// 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();
/// ```
pub async fn exchange_token_for_session(&self, refresh_token: &str) -> Result<Session, Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
let body = serde_json::to_string(&RefreshSessionPayload { refresh_token })?;
let response = self
.client
.post(&format!(
"{}{}/token?grant_type=refresh_token",
self.project_url, AUTH_V1
))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
let session: Session = from_str(&res_body).map_err(|_| AuthError {
status: res_status,
message: res_body,
})?;
Ok(session)
}
pub async fn refresh_session(&self, refresh_token: &str) -> Result<Session, Error> {
self.exchange_token_for_session(refresh_token).await
}
/// 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).await.unwrap();
/// ```
pub async fn reset_password_for_email(&self, email: &str) -> Result<(), Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
let body = serde_json::to_string(&ResetPasswordForEmailPayload {
email: email.into(),
})?;
let response = self
.client
.post(&format!("{}{}/recover", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
if res_status.is_success() {
Ok(())
} else {
Err(Error::AuthError {
status: res_status,
message: res_body,
})
}
}
/// 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;
/// ```
pub async fn resend(&self, credentials: ResendParams) -> Result<(), Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
let body = serde_json::to_string(&credentials)?;
let response = self
.client
.post(&format!("{}{}/resend", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
if res_status.is_success() {
Ok(())
} else {
Err(Error::AuthError {
status: res_status,
message: res_body,
})
}
}
/// Logs out a user with a given scope
/// # Example
/// ```
/// auth_client.logout(Some(LogoutScope::Global), session.access_token).await.unwrap();
/// ```
pub async fn logout(
&self,
scope: Option<LogoutScope>,
bearer_token: &str,
) -> Result<(), Error> {
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_str("application/json")?);
headers.insert(
AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {}", bearer_token))?,
);
let body = serde_json::to_string(&scope)?;
let response = self
.client
.post(&format!("{}{}/logout", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let res_body = response.text().await?;
if res_status.is_success() {
Ok(())
} else {
Err(Error::AuthError {
status: res_status,
message: res_body,
})
}
}
/// 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());
/// ```
pub async fn sso(&self, params: LoginWithSSO) -> Result<Url, Error> {
let mut headers = HeaderMap::new();
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
headers.insert("apikey", HeaderValue::from_str(&self.api_key)?);
let body = serde_json::to_string::<crate::models::LoginWithSSO>(¶ms)?;
let response = self
.client
.post(&format!("{}{}/sso", self.project_url, AUTH_V1))
.headers(headers)
.body(body)
.send()
.await?;
let res_status = response.status();
let url = response.url().clone();
let res_body = response.text().await?;
if res_status.is_server_error() || res_status.is_client_error() {
return Err(AuthError {
status: res_status,
message: res_body,
});
}
Ok(url)
}
/// Get the project URL from an AuthClient
pub fn project_url(&self) -> &str {
&self.project_url
}
/// Get the API Key from an AuthClient
pub fn api_key(&self) -> &str {
&self.api_key
}
/// Get the JWT Secret from an AuthClient
pub fn jwt_secret(&self) -> &str {
&self.jwt_secret
}
}