Overview
The Auth Api provides a complete set of authentication-related features, supporting various log-in methods, user management, and session management. The Auth Api is divided into 7 categories by purpose. Each category contains related Api methods, helping developers quickly find suitable APIs depending on specific needs.
v3 version uses the open capability of Identity Verification HTTP API when calling relevant API for identity verification.
- Authentication Login: API methods for user registration and login, supporting various login methods.
- Session Management: API method to manage user session status and token.
- User Management: API methods to get, update and manage user information.
- Identity Source Management: API method to manage binding and unbinding of third-party identity sources.
- Password Management: API methods for password reset and modification.
- Verification Management: API methods for verification code sending, verify and resend.
- Other Tools: API methods for auxiliary features.
Basic Usage Examples
Publishable Key can go to Cloud Development Platform/API Key Configuration to generate
auth.detectSessionInUrl is an optional parameter for initialization. After configuration, it can automatically detect OAuth parameters (code, state) in the URL, suitable for usage scenarios such as signInWithOAuth and linkIdentity.
import cloudbase from "@cloudbase/js-sdk";
// Initialize it.
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
auth: {
detectSessionInUrl: true, // Option: automatically detect OAuth parameters in the URL, suitable for signInWithOAuth, linkIdentity
},
});
const auth = app.auth;
Check login status
async function checkAuthStatus() {
const { data, error } = await auth.getSession();
if (error) {
console.error("Check login status failed:", error.message);
return false;
}
if (data.session) {
console.log("user logged in:", data.session.user);
return true;
} else {
console.log("user not logged in");
return false;
}
}
// User registration example (four-step verification process)
async function registerUser(email, password, verificationCode) {
Step 1: Send verification.
const { data, error } = await auth.signUp({
email: email,
password: password,
});
if (error) {
console.error("send Captcha failed:", error.message);
return false;
} else {
console.log("Captcha has been sent, validating...");
Step 2: Verify the Captcha and complete registration
const { data: loginData, error: loginError } = await data.verifyOtp({
token: verificationCode,
});
if (loginError) {
console.error("verification failed:", loginError.message);
return false;
} else {
console.log("register successfully:", loginData.user?.email);
return true;
}
}
}
// User logout example
async function logoutUser() {
const { data, error } = await auth.signOut();
if (error) {
console.error("logout failed:", error.message);
return false;
} else {
console.log("logout successful, session purged");
return true;
}
}
// Password login example
async function loginWithPassword(email, password) {
const { data, error } = await auth.signInWithPassword({
email: email,
password: password,
});
if (error) {
console.error("login failed:", error.message);
return false;
} else {
console.log("login successful:", data.user?.email);
return true;
}
}
// Listen to authentication status transition
auth.onAuthStateChange((event, session, info) => {
console.log("Authentication Status Transition:", event);
switch (event) {
case "INITIAL_SESSION":
console.log("initial session established");
if (session) {
console.log("user logged in:", session.user);
} else {
console.log("user not logged in");
}
break;
case "SIGNED_IN":
console.log("user login successful:", session.user);
break;
case "SIGNED_OUT":
console.log("user logged out");
break;
case "PASSWORD_RECOVERY":
console.log("password reset");
break;
case "TOKEN_REFRESHED":
console.log("Token refreshed");
break;
case "USER_UPDATED":
console.log("user information updated");
break;
case "BIND_IDENTITY":
console.log("identity source binding result");
break;
}
});
Complete mobile captcha login page implementation
class PhoneLoginPage {
constructor() {
this.setupEventListeners();
}
// Set up event listening
setupEventListeners() {
document.getElementById("sendCodeBtn").addEventListener("click", (e) => {
e.preventDefault();
this.sendVerificationCode();
});
document.getElementById("verifyCodeBtn").addEventListener("click", (e) => {
e.preventDefault();
this.verifyCodeAndLogin();
});
}
// Send verification code
async sendVerificationCode() {
const phone = document.getElementById("phone").value;
if (!phone) {
alert("Enter your phone number");
return;
}
// Verify phone number format
if (!this.validatePhone(phone)) {
alert("Enter a valid mobile number format");
return;
}
// Display loading...
this.showLoading(true);
this.hideError();
try {
const { data, error } = await auth.signInWithOtp({
phone: phone,
});
if (error) {
this.handleSendCodeError(error);
} else {
this.handleSendCodeSuccess(data);
}
} catch (error) {
this.handleNetworkError(error);
} finally {
this.showLoading(false);
}
}
// Verify the Captcha and log in
async verifyCodeAndLogin() {
const code = document.getElementById("code").value;
if (!code) {
alert("Please enter Captcha");
return;
}
if (!this.verifyFunction) {
alert("Please first send Captcha");
return;
}
this.showLoading(true);
this.hideError();
try {
const { data, error } = await this.verifyFunction({ token: code });
if (error) {
this.handleVerifyError(error);
} else {
this.handleLoginSuccess(data);
}
} catch (error) {
this.handleNetworkError(error);
} finally {
this.showLoading(false);
}
}
// Verify phone number format
validatePhone(phone) {
const phoneRegex = /^1[3-9]\d{9}$/;
return phoneRegex.test(phone);
}
// Handle send verification code success
handleSendCodeSuccess(data) {
this.verifyFunction = data.verifyOtp;
// Display the Captcha input area
document.getElementById("verificationSection").style.display = "block";
document.getElementById("phoneSection").style.display = "none";
// Countdown starts
this.startCountdown(60);
document.getElementById("success").innerText =
The Captcha has been sent to your mobile phone. Please check your inbox.
document.getElementById("success").style.display = "block";
}
// Handle send verification error
handleSendCodeError(error) {
switch (error.code) {
case "invalid_phone":
document.getElementById("error").innerText =
Incorrect phone number format, please check and retry.
break;
case "user_not_found":
document.getElementById("error").innerText =
This phone number is unregistered. Please first register or use another mobile number.
break;
case "resource_exhausted":
document.getElementById("error").innerText = "Sending frequency too high, try again later";
break;
case "unreachable":
document.getElementById("error").innerText =
network connection failed, check the network settings
break;
default:
document.getElementById("error").innerText =
"send Captcha failed: " + error.message;
}
document.getElementById("error").style.display = "block";
}
// Handle verification error
handleVerifyError(error) {
switch (error.code) {
case "invalid_code":
document.getElementById("error").innerText = "Captcha error, please enter again";
break;
case "code_expired":
document.getElementById("error").innerText = "Captcha expired, please obtain again";
// Display the resend button
document.getElementById("resendBtn").style.display = "block";
break;
case "max_attempts_exceeded":
document.getElementById("error").innerText = "Too many verification attempts, try again later";
break;
default:
document.getElementById("error").innerText =
"verification failed: " + error.message;
}
document.getElementById("error").style.display = "block";
}
handle successful login
handleLoginSuccess(data) {
document.getElementById("success").innerText = "Login successful. Welcome back";
document.getElementById("success").style.display = "block";
console.log("user information:", data.user);
console.log("session information:", data.session);
Navigate to the homepage after a delay
setTimeout(() => {
window.location.href = "/dashboard";
}, 2000);
}
// Handle network error
handleNetworkError(error) {
document.getElementById("error").innerText =
Network error, check the network connection and try again.
document.getElementById("error").style.display = "block";
console.error("network error:", error);
}
// Show/Hide loading...
showLoading(show) {
document.getElementById("loading").style.display = show ? "block" : "none";
document.getElementById("sendCodeBtn").disabled = show;
document.getElementById("verifyCodeBtn").disabled = show;
}
// Hide error info
hideError() {
document.getElementById("error").style.display = "none";
}
// Countdown starts
startCountdown(seconds) {
let countdown = seconds;
const btn = document.getElementById("resendBtn");
const originalText = btn.innerText;
btn.disabled = true;
const timer = setInterval(() => {
countdown--;
btn.innerText = `${countdown}s to resend`;
if (countdown <= 0) {
clearInterval(timer);
btn.disabled = false;
btn.innerText = originalText;
}
}, 1000);
}
}
// Initialize upon page loading completion
window.addEventListener("DOMContentLoaded", () => {
new PhoneLoginPage();
});
Authentication login
signUp
async signUp(params: SignUpReq): Promise<SignUpRes>
Register a new user account, implement intelligent registration and login process.
Phone number verification code registration is only supported in the Shanghai region
-Create a new user account -Implement intelligent registration and login process: send verification code → wait for user input → intelligently determine user existence → automatically log in or register and sign in. -If the user already exists, log in directly. If the user does not exist, register a new user and automatically log in.
参数
返回
示例
Step 1: Send a mailbox verification code and store verificationInfo.
const { data, error } = await auth.signUp({
email: "newuser@example.com",
password: "securePassword123",
username: "newuser",
});
if (error) {
console.error("send Captcha failed:", error.message);
} else {
console.log("Captcha has been sent to email, waiting for user input...");
Step 2: Wait for user input of Captcha (using Promise to package the user input event)
const verificationCode = "123456"; // user input
Step 3: Intelligent verification process (automatically determine user existence)
const { data: loginData, error: loginError } = await data.verifyOtp({
token: verificationCode,
});
if (loginError) {
console.error("verification failed:", loginError.message);
} else {
Step 4: Automatically complete registration or log in
console.log("operation successful, user information:", loginData.user);
console.log("session information:", loginData.session);
console.log(
The system has automatically determined:
loginData.user?.email ? "New user registration and log in" : "Existing users log in directly"
);
}
}
Step 1: Send mobile verification code
const { data, error } = await auth.signUp({
phone: "13800138000",
password: "mypassword",
});
if (error) {
console.error("send Captcha failed:", error.message);
} else {
console.log("Captcha has been sent to the mobile phone, waiting for user input...");
Step 2: Wait for user input of the verification code.
const verificationCode = "123456"; // user input
Step 3: Intelligent verification process (automatically determine user existence)
const { data: loginData, error: loginError } = await data.verifyOtp({
token: verificationCode,
});
if (loginError) {
console.error("operation failed:", loginError.message);
} else {
// System automation judges: if the user already exists, log in directly. If not present, register a new user.
if (loginData.user?.phone) {
console.log("Existing user logged in directly, user information:", loginData.user);
} else {
console.log("New user registration and login successful, uid:", loginData.user?.ID);
}
console.log("session status:", loginData.session ? "logged in" : "not logged in");
}
}
let signUpVerify = null;
async function startRegistration(email, password) {
const { data, error } = await auth.signUp({
email: email,
password: password,
});
if (error) {
console.error("send Captcha failed:", error.message);
document.getElementById("error").innerText =
"send Captcha failed: " + error.message;
return false;
} else {
console.log("Captcha has been sent");
signUpVerify = data.verifyOtp;
// Display the Captcha input box
document.getElementById("verificationSection").style.display = "block";
document.getElementById("registrationSection").style.display = "none";
// Refresh the prompt message to explain the intelligent judgment logic
document.getElementById("verificationHint").innerText =
Enter the Captcha, and the system will automatically determine whether to register a new user or log in to an existing account.
return true;
}
}
async function completeRegistration(verificationCode) {
if (!signUpVerify) {
console.error("sign-up process not started");
return false;
}
const { data, error } = await signUpVerify({ token: verificationCode });
if (error) {
console.error("verification failed:", error.message);
document.getElementById("error").innerText = "verification failed: " + error.message;
return false;
} else {
// Intelligent judgment result feedback
if (data.user?.email) {
console.log("Intelligent registration and login successful");
document.getElementById("success").innerText = data.user?.created_at
"New user registration successful. Welcome to join!"
"Login successful. Welcome back";
}
Navigate to the homepage
setTimeout(() => {
window.location.href = "/dashboard";
}, 2000);
return true;
}
}
// Registration form submission
document
.getElementById("registerForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;
const nickname = document.getElementById("nickname").value;
await startRegistration(email, password, nickname);
});
// Captcha form submission
document
.getElementById("verificationForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const code = document.getElementById("verificationCode").value;
await completeRegistration(code);
});
try {
const { data, error } = await auth.signUp({
email: "existing@example.com",
password: "password123",
});
if (error) {
switch (error.code) {
case "email_already_exists":
console.error(
"Mailbox already registered, please use other mailbox or log in directly"
);
document.getElementById("error").innerText = "Email already registered";
break;
case "phone_already_exists":
console.error(
"The mobile number has been registered, please use another mobile number"
);
document.getElementById("error").innerText =
"This phone number has been registered";
break;
case "password_too_weak":
console.error(
"password strength is insufficient, please use a more complex password"
);
document.getElementById("error").innerText =
"password strength is insufficient";
break;
case "invalid_email":
console.error("Incorrect email format, please check email format");
document.getElementById("error").innerText = "Incorrect email format";
break;
case "invalid_phone":
console.error(
"Incorrect phone number format, please check phone number format"
);
document.getElementById("error").innerText =
"Incorrect phone number format";
break;
case "username_already_exists":
console.error(
"The username is already used, please select another username"
);
document.getElementById("error").innerText =
"The username is already used";
break;
case "resource_exhausted":
console.error("Registration frequency too high, please retry later");
document.getElementById("error").innerText =
"Registration frequency too high, try again later";
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
document.getElementById("error").innerText =
"network connection failure";
break;
default:
console.error("registration failed:", error.message);
document.getElementById("error").innerText =
"registration failed: " + error.message;
}
} else {
console.log("Captcha sending successful");
}
} catch (error) {
console.error("network error:", error);
document.getElementById("error").innerText =
"Network error, please try again";
}
async function verifyRegistrationCode(code) {
try {
const { data, error } = await signUpCallback(code);
if (error) {
switch (error.code) {
case "invalid_code":
console.error("Captcha incorrect, please enter again");
document.getElementById("error").innerText = "Captcha incorrect";
break;
case "code_expired":
console.error("Captcha expired, please obtain again");
document.getElementById("error").innerText = "Captcha expired";
// Display the resend button
document.getElementById("resendBtn").style.display = "block";
break;
case "max_attempts_exceeded":
console.error("Too many verification attempts, please retry later");
document.getElementById("error").innerText =
"Too many verification attempts";
break;
case "verification_not_found":
console.error(
"Verification information not found, please restart the sign-up process"
);
document.getElementById("error").innerText =
"Verification information not found";
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
document.getElementById("error").innerText =
"network connection failure";
break;
default:
console.error("verification failed:", error.message);
document.getElementById("error").innerText =
"verification failed: " + error.message;
}
return false;
} else {
console.log("Register successfully");
return true;
}
} catch (error) {
console.error("network error:", error);
document.getElementById("error").innerText = "network error, please retry";
return false;
}
}
signInAnonymously
async signInAnonymously(params?: SignInAnonymouslyReq): Promise<SignInRes>
Anonymous login, create a temporary anonymous user account.
-Create a temporary anonymous user account -No need to provide any authentication information
- Suitable for scenarios where temporary access permission is required -Before using, please confirm that anonymous login (enabled by default) is enabled in Cloud Development Platform/Identity Verification/Registration Configuration.
参数
返回
示例
// Create an anonymous user
const { data, error } = await auth.signInAnonymously();
if (error) {
console.error("anonymous login failed:", error.message);
console.error("error code:", error.code);
} else {
console.log("anonymous login success");
console.log("anonymous user ID:", data.user?.ID);
console.log("session information:", data.session);
console.log("whether anonymous user:", data.user?.is_anonymous);
}
async function safeAnonymousLogin() {
try {
const { data, error } = await auth.signInAnonymously();
if (error) {
switch (error.code) {
case "rate_limit_exceeded":
console.error("Request frequency too high, try again later");
break;
case "invalid_provider_token":
console.error(
"Third-party platform token invalid, please check token format"
);
break;
case "provider_not_supported":
console.error(
"Unsupported third-party platform, check the platform identifier"
);
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "permission_denied":
console.error(
"Insufficient permissions, please check secure domain configuration"
);
break;
default:
console.error("anonymous login failed:", error.message);
}
return null;
} else {
console.log("anonymous login success");
return data;
}
} catch (error) {
console.error("network error:", error);
return null;
}
}
// Use the secure login function
const result = await safeAnonymousLogin();
if (result) {
console.log("login successful, user information:", result.user);
}
// Step 1: Anonymous login
const { data: anonymousData, error: anonymousError } =
await auth.signInAnonymously();
if (anonymousError) {
console.error("anonymous login failed:", anonymousError.message);
} else {
console.log("anonymous login success, prepare to upgrade to official user");
Step 2: Bind an email or phone number (example: bind email)
const { data: upgradeData, error: upgradeError } = await auth.signUp({
email: "user@example.com",
password: "securePassword123",
anonymous_token: anonymousData.session?.access_token,
});
if (upgradeError) {
console.error("upgrade failed:", upgradeError.message);
} else {
console.log("upgrade successful, enter Captcha to complete the authentication process");
// Step 3: Verify the Captcha.
const verificationCode = "123456";
const { data: finalData, error: finalError } = await upgradeData.verifyOtp({
token: verificationCode,
});
if (finalError) {
console.error("verification failed:", finalError.message);
} else {
console.log("anonymous user successfully upgraded to official user");
console.log("new user information:", finalData.user);
console.log("whether anonymous user:", finalData.user?.is_anonymous);
}
}
}
signInWithPassword
async signInWithPassword(params: SignInWithPasswordReq): Promise<SignInRes>
Log in with username, email, or mobile number and password.
-Support username, mailbox, or mobile number in conjunction with password as login methods (choose one). -Before using, please confirm that username and password login (enabled by default) is enabled in Cloud Development Platform/Identity Verification/Regular Login.
参数
返回
示例
const { data, error } = await auth.signInWithPassword({
username: "testuser",
password: "password123",
});
if (error) {
console.error("login failed:", error.message);
} else {
console.log("login successful, user information:", data.user);
console.log("session information:", data.session);
}
const { data, error } = await auth.signInWithPassword({
email: "user@example.com",
password: "mypassword",
});
if (error) {
console.error("login failed:", error.message);
} else {
console.log("login successful, uid:", data.user?.ID);
}
const { data, error } = await auth.signInWithPassword({
phone: "13800138000",
password: "securepassword",
});
if (error) {
console.error("login failed:", error.code, error.message);
} else {
console.log("login successful, uid:", data.user?.ID);
}
try {
const { data, error } = await auth.signInWithPassword({
username: "wronguser",
password: "wrongpassword",
});
if (error) {
// Perform complete error handling based on common error codes
switch (error.code) {
case "not_found":
console.error(
"user does not exist, please check whether the username/email/phone number is correct"
);
break;
case "password_not_set":
console.error(
"current user not set, please use Captcha or third-party login method"
);
break;
case "invalid_password":
console.error("incorrect password, please enter again");
break;
case "user_pending":
console.error(
"user not activated, contact the admin to activate account"
);
break;
case "user_blocked":
console.error("user disabled, contact the admin");
break;
case "invalid_status":
console.error("password retry limit exceeded, try again later");
break;
case "invalid_two_factor":
console.error("MFA code mismatched or outdated, please obtain again");
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
default:
console.error("login failed:", error.message);
}
} else {
console.log("login successful");
}
} catch (error) {
console.error("network error:", error);
}
signInWithOtp
async signInWithOtp(params: SignInWithOtpReq): Promise<SignInWithOtpRes>
Use one-time password (OTP) for login validation, supporting mailbox and SMS verification.
SMS verification code is only supported in the Shanghai region
-Log in with one-time verification code sent to your mailbox or mobile number -Support the complete verification process: send verification code → wait for user input → verify and log in. -Suitable for passwordless login scenarios, offering higher security -Before using, please confirm that mailbox/SMS Captcha login is enabled in Cloud Development Platform/Identity Verification/Log-in Methods/Regular Login.
参数
返回
示例
const { data, error } = await auth.signInWithOtp({
phone: "13800138000",
});
if (error) {
console.error("send Captcha failed:", error.message);
} else {
console.log("Captcha has been sent, waiting for user input...");
// Verify the Captcha after user input
const { data: loginData, error: loginError } = await data.verifyOtp({
token: "123456",
});
if (loginError) {
console.error("verification failed:", loginError.message);
} else {
console.log("login successful:", loginData.user);
console.log("session information:", loginData.session);
}
}
// Send mailbox verification code
const { data, error } = await auth.signInWithOtp({
email: "user@example.com",
});
if (error) {
console.error("send Captcha failed:", error.message);
} else {
console.log("Mailbox verification code sent, please check your mail...");
// Verify the Captcha after the user retrieves it from the mailbox
const { data: loginData, error: loginError } = await data.verifyOtp({
token: "654321",
});
if (loginError) {
console.error("verification failed:", loginError.message);
} else {
console.log("login successful:", loginData.user?.email);
}
}
try {
const { data, error } = await auth.signInWithOtp({
phone: "13800138000",
});
if (error) {
switch (error.code) {
case "resource_exhausted":
console.error("Sending frequency too high, try again later");
break;
case "invalid_argument":
console.error(
"Incorrect phone number or email format, please check and retry"
);
break;
case "failed_precondition":
console.error(
"failed to obtain user information from third party, retry"
);
break;
case "aborted":
console.error(
"Too many attempts, go back to the first page and try again later"
);
break;
case "permission_denied":
console.error("Your current session expired, please return and retry");
break;
case "captcha_required":
console.error("Captcha is required, according to robot service access");
break;
case "captcha_invalid":
console.error(
"Captcha is incorrect, according to robot service access"
);
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
default:
console.error("send Captcha failed:", error.message);
}
return;
}
// Verify verification code
const { data: loginData, error: loginError } = await data.verifyOtp({
token: "123456",
});
if (loginError) {
console.error("verification failed:", loginError.message);
} else {
console.log("login successful");
}
} catch (error) {
console.error("network error:", error);
}
signInWithOAuth
async signInWithOAuth(params: SignInWithOAuthReq): Promise<SignInOAuthRes>
Generate authorization links for third-party platforms, supporting mainstream platforms such as WeChat and Google.
-Generate the authorization page URL for third-party platforms such as WeChat and Google. -Store status information in the browser session so that it can be verified subsequently -Support custom callback address and status parameter -Before using, please confirm that the corresponding OAuth identity source is enabled in Cloud Development Platform/Identity Verification/Log-in Methods.
Notes
-After calling this method, the status information is automatically saved to the browser session. When auth.detectSessionInUrl is set to true in cloudbase.init, verifyOAuth is automatically called for verification upon returning from a third-party callback, otherwise manually verify via the verifyOAuth method subsequently.
- If no state parameter is provided, the system automatically generates a status parameter in the format
prd-{provider}-{random string}. -The callback URL needs to be configured in the protected domains of the Cloud Development Platform, otherwise it will return a permission error.
参数
返回
示例
// Initialize it.
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
auth: {
detectSessionInUrl: true, // Option: automatically detect OAuth parameters in the URL
},
});
const { data, error } = await auth.signInWithOAuth({
provider: "wechat",
options: {
redirectTo: "https://example.com/callback",
state: "wx_auth_123456",
},
});
if (error) {
console.error("failed to obtain authorization link:", error.message);
} else {
console.log("Weixin authorization url:", data.url);
console.log("third-party platform:", data.provider);
navigate to the Weixin authorization page
window.location.href = data.url;
}
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
auth: {
detectSessionInUrl: true, // Option: automatically detect OAuth parameters in the URL
},
});
const auth = app.auth;
const { data, error } = await auth.signInWithOAuth({
provider: "google",
});
if (error) {
console.error("failed to obtain authorization link:", error.message);
} else {
console.log("Google authorization link generated, prepare to redirect...");
console.log("authorization URL:", data.URL);
open the authorization page in new window
window.open(data.url, "_blank");
}
// OAuth sign-in best practice - fully UI interaction process
// Initialize it.
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
auth: {
detectSessionInUrl: true, // Option: automatically detect OAuth parameters in the URL, suitable for signInWithOAuth, linkIdentity
},
});
// Modify the authentication status transition listener, enable floating window
async function setupAuthStateChangeListener() {
try {
if (!app.auth) return;
// Subscribe to authentication status change events
const { data } = await app.auth.onAuthStateChange(
(event, session, info) => {
console.log("Authentication Status Transition:", { event, session, info });
switch (event) {
case "SIGNED_IN":
if (session && session.user) {
console.log("login successful");
}
break;
default:
console.log("Unknown authentication event:", event);
}
}
);
console.log("Authentication Status Transition Listener Set");
} catch (error) {
console.error("Failed to set authentication status transition listener:", error);
}
}
class OAuthManager {
constructor() {
this.initEventListeners();
this.provider = "oauth";
}
// Initialize event listeners
initEventListeners() {
// OAuth login button click event
document.getElementById("oauth-login-btn").addEventListener("click", () => {
this.startOAuth();
});
}
Start the OAuth 2.0 authorization process
async startOAuth() {
try {
this.showLoading(true);
this.hideError();
const { data, error } = await auth.signInWithOAuth({
provider: this.provider,
});
if (error) {
this.handleOAuthError(error);
} else {
console.log("OAuth authorization link successfully generated, redirecting...");
// Best practice: Use redirection in the current window to maintain user experience
window.location.href = data.url;
}
} catch (error) {
this.handleOAuthError(error);
} finally {
this.showLoading(false);
}
}
showLoading(show) {
document.getElementById("loading").style.display = show ? "block" : "none";
}
}
setupAuthStateChangeListener();
// Initialize the OAuth login manager
const oAuthManager = new OAuthManager();
// Initialize it.
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
});
class OAuthManager {
constructor() {
this.initEventListeners();
this.provider = "oauth";
}
// Initialize event listeners
initEventListeners() {
// OAuth login button click event
document.getElementById("oauth-login-btn").addEventListener("click", () => {
this.startOAuth();
});
// Check whether there is an OAuth authorization callback during page loading
document.addEventListener("DOMContentLoaded", () => {
this.checkOAuthCallback();
});
}
Start the OAuth 2.0 authorization process
async startOAuth() {
try {
this.showLoading(true);
this.hideError();
const { data, error } = await auth.signInWithOAuth({
provider: this.provider,
});
if (error) {
this.handleOAuthError(error);
} else {
console.log("OAuth authorization link successfully generated, redirecting...");
// Best practice: Use redirection in the current window to maintain user experience
window.location.href = data.url;
}
} catch (error) {
this.handleOAuthError(error);
} finally {
this.showLoading(false);
}
}
// Check the OAuth authorization callback
async checkOAuthCallback() {
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get("code");
const state = urlParams.get("state");
if (code && state) {
console.log("OAuth callback detected, verifying...");
await this.verifyOAuth(code, state);
}
}
Verify OAuth authorization
async verifyOAuth(code, state) {
try {
this.showLoading(true);
const result = await auth.verifyOAuth({
code: code,
state: state,
provider: this.provider,
});
if (result.error) {
this.handleOAuthError(result.error);
} else {
console.log("OAuth login successful");
this.showSuccess("OAuth login successful");
}
} catch (error) {
this.handleOAuthError(error);
} finally {
this.showLoading(false);
}
}
// Error Handling
handleOAuthError(error) {
console.error("OAuth login error:", error);
switch (error.code) {
case "provider_not_supported":
this.showError("Unsupported third-party platform, please check whether the platform identifier is correct");
break;
case "invalid_redirect_uri":
this.showError("Callback address format error, please check URL format");
break;
case "failed_precondition":
this.showError("Failed to obtain user information from OAuth, please check platform configuration");
break;
case "permission_denied":
this.showError("Insufficient permissions, please check secure domain configuration");
break;
case "resource_exhausted":
this.showError("Request frequency too high, please retry later");
break;
case "unreachable":
this.showError("network connection failed, check the network and retry after setting");
break;
case "invalid_code":
this.showError("Authorization code invalid or expired, please reauthorize");
break;
case "state_mismatch":
this.showError("State parameter mismatch, may pose security risks, please reauthorize");
break;
default:
this.showError("OAuth login failure: " + (error.message || "unknown error"));
}
}
showLoading(show) {
document.getElementById("loading").style.display = show ? "block" : "none";
}
showError(message) {
const errorElement = document.getElementById("error-message");
errorElement.textContent = message;
errorElement.style.display = "block";
}
hideError() {
document.getElementById("error-message").style.display = "none";
}
showSuccess(message) {
const successElement = document.getElementById("success-message");
successElement.textContent = message;
successElement.style.display = "block";
}
}
signInWithIdToken
async signInWithIdToken(params: SignInWithIdTokenReq): Promise<SignInRes>
Log in using a third-party platform identity token, supporting mainstream platforms such as WeChat and Google.
-Log in using a third-party platform identity token, such as WeChat and Google.
- Support specifying third-party platform flags. Third-party platforms must first be configured in Cloud Development Platform/Identity Verification/Log-in Methods.
- Token is a required parameter
参数
返回
示例
const { data, error } = await auth.signInWithIdToken({
provider: "wechat",
token: "wx_token_1234567890",
});
if (error) {
console.error("WeChat login failed:", error.message);
} else {
console.log("WeChat login successful, user information:", data.user);
console.log("session information:", data.session);
}
const { data, error } = await auth.signInWithIdToken({
provider: "google",
token: "google_token_abcdefg",
});
if (error) {
console.error("Google login failed:", error.message);
} else {
console.log(
"Google login successful, user nickname:",
data.user?.user_metadata?.nickName
);
}
const { data, error } = await auth.signInWithIdToken({
token: "generic_token_xyz",
});
if (error) {
console.error("token login failed:", error.message);
} else {
console.log("Token login succeeded, uid:", data.user?.ID);
}
try {
const { data, error } = await auth.signInWithIdToken({
provider: "wechat",
token: "invalid_token",
});
if (error) {
switch (error.code) {
case "invalid_token":
console.error("Token invalid or expired, please obtain again");
break;
case "provider_not_supported":
console.error(
"Unsupported third-party platform, use other login methods"
);
break;
case "failed_precondition":
console.error(
"failed to obtain user information from third party, retry"
);
break;
case "resource_exhausted":
console.error("Too frequent attempts, please retry later");
break;
case "permission_denied":
console.error(
"insufficient permissions, please check token permission scope"
);
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
default:
console.error("login failed:", error.message);
}
} else {
console.log("login successful");
}
} catch (error) {
console.error("network error:", error);
}
signInWithCustomTicket
async signInWithCustomTicket(getTickFn: GetCustomSignTicketFn): Promise<SignInRes>
Use custom login invoice to log in, support completely custom login process.
-Use custom login ticket to authenticate, login ticket creation can be performed on the server side using Create Custom Login Ticket API -Support passing functions to obtain custom login invoice -Suitable for scenarios where a fully custom login process is required
- The detailed process of issuing a Ticket can be found in Custom Login
参数
functions to obtain custom login invoice, return Promise<string>
返回
示例
functions to obtain custom login invoice
const getTickFn = () => Promise.resolve("custom_ticket_123456");
const { data, error } = await auth.signInWithCustomTicket(getTickFn);
if (error) {
console.error("custom login failed:", error.message);
} else {
console.log("custom login successful, user information:", data.user);
console.log("session information:", data.session);
}
// asynchronously fetch custom login invoice
const getTickFn = async () => {
// Simulate retrieving an invoice from the backend API
const response = await fetch("/api/get-custom-ticket");
const data = await response.json();
return data.ticket;
};
const { data, error } = await auth.signInWithCustomTicket(getTickFn);
if (error) {
console.error("custom login failed:", error.message);
} else {
console.log("custom login successful");
}
try {
const getTickFn = () => Promise.resolve("custom_ticket_123456");
const { data, error } = await auth.signInWithCustomTicket(getTickFn);
if (error) {
switch (error.code) {
case "invalid_ticket":
console.error("Invoice invalid or expired, please obtain again");
break;
case "ticket_required":
console.error("custom login invoice is required");
break;
case "network_error":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
default:
console.error("login failed:", error.message);
}
} else {
console.log("login successful");
}
} catch (error) {
console.error("network error:", error);
}
signInWithOpenId
async signInWithOpenId(params?: SignInWithOpenIdReq): Promise<SignInRes>
WeChat mini program OpenID silent sign-in. If the user does not exist, it will determine whether to automatically register based on the login mode configuration of the corresponding identity source in the Cloud Development Platform login methods (https://tcb.cloud.tencent.com/dev?envId=#/identity/login-manage).
Only supported for use in WeChat mini program
参数
Login parameters
返回
示例
const { data, error } = await auth.signInWithOpenId();
const { data, error } = await auth.signInWithOpenId({ useWxCloud: false });
signInWithPhoneAuth
async signInWithPhoneAuth(params: SignInWithPhoneAuthReq): Promise<SignInRes>
WeChat mini program mobile phone authorization sign-in. If the user does not exist, it will determine whether to automatically register based on the login mode configuration of the corresponding identity source in the Cloud Development Platform login methods (https://tcb.cloud.tencent.com/dev?envId=#/identity/login-manage).
Only supported for use in WeChat mini program
参数
Login parameters
返回
示例
const { data, error } = await auth.signInWithPhoneAuth({ phoneCode: "xxx" });
Session Management
getSession
async getSession(): Promise<SignInRes>
Get current session info and check user login status.
-Get current user session information, including access token and user information. -Check whether the user is logged in, return empty conversation if not logged in
参数
无参数
返回
示例
const { data, error } = await auth.getSession();
if (error) {
console.error("failed to get conversation:", error.message);
} else if (data.session) {
console.log("user logged in:", data.session.user);
console.log("Access token:", data.session.access_token);
console.log("Expiration time:", data.session.expires_in, "seconds");
} else {
console.log("user not logged in, please log in first");
Display the login button
document.getElementById("loginBtn").style.display = "block";
}
document.addEventListener("DOMContentLoaded", async () => {
const { data, error } = await auth.getSession();
if (error) {
console.error("Check login status failed:", error.message);
return;
}
if (data.session) {
// User logged in, display user information
document.getElementById("userInfo").innerHTML = `
<p>Welcome, ${data.session.user?.name || data.session.user?.username}</p>
`;
document.getElementById("loginBtn").style.display = "none";
document.getElementById("logoutBtn").style.display = "block";
} else {
// User not logged in, display login UI
document.getElementById("loginForm").style.display = "block";
}
});
// Regularly check session status and automatically refresh token
function setupSessionMonitor() {
setInterval(async () => {
const { data, error } = await auth.getSession();
if (error) {
console.error("session check failed:", error.message);
} else if (data.session) {
const expiresIn = data.session.expires_in;
// If the token will expire in 5 minutes, automatically refresh it
if (expiresIn < 300) {
console.log("Token about to expire, automatically refresh...");
await auth.refreshSession();
}
}
}, 60000); // check once per minute
}
// Start up session monitoring
setupSessionMonitor();
try {
const { data, error } = await auth.getSession();
if (error) {
switch (error.code) {
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "token_expired":
console.error("Access token expired, log in again");
// Automatically refresh token
await auth.refreshSession();
break;
case "invalid_refresh_token":
console.error("Refresh token invalid, log in again");
break;
case "refresh_token_expired":
console.error("Refresh token expired, log in again");
break;
case "user_not_found":
console.error("user does not exist, log in again");
break;
case "permission_denied":
console.error(
"Insufficient permissions, please check secure domain configuration"
);
break;
default:
console.error("failed to get conversation:", error.message);
}
} else {
console.log("Session acquisition successful");
}
} catch (error) {
console.error("unknown error:", error);
}
refreshSession
async refreshSession(refresh_token?: string): Promise<SignInRes>
Refresh the session token, extend the user login status, support auto-renewal and error recovery.
-Use a refresh token to get a new access token -Extend the valid period of user sessions -Supports the use of designated refresh token or default token
参数
返回
示例
const { data, error } = await auth.refreshSession();
if (error) {
console.error("refresh session fails:", error.message);
// refresh fails, may need to log in again
window.location.href = "/login";
} else {
console.log(
"Session refreshed successfully, new token:",
data.session?.access_token
);
console.log("New expiration time:", data.session?.expires_in, "seconds");
}
const savedRefreshToken = "refresh_token";
if (savedRefreshToken) {
const { data, error } = await auth.refreshSession(savedRefreshToken);
if (error) {
console.error("Refresh with saved token fails:", error.message);
} else {
console.log("Refresh with saved token succeed");
}
} else {
console.log("No saved refresh token, refresh with default method");
const { data, error } = await auth.refreshSession();
if (error) {
console.error("refresh fails:", error.message);
}
}
// Set a timer to automatically refresh token before expiration
function setupTokenRefresh() {
setInterval(async () => {
const { data, error } = await auth.getSession();
if (data.session) {
const expiresIn = data.session.expires_in;
// If the token will expire in 5 minutes, refresh it
if (expiresIn < 300) {
console.log("Token about to expire, automatically refresh...");
const { data: refreshData, error: refreshError } =
await auth.refreshSession();
if (refreshError) {
console.error("automatically refresh fails:", refreshError.message);
} else {
console.log("Auto refresh successful");
}
}
}
}, 60000); // check once per minute
}
// Start scheduled refresh
setupTokenRefresh();
try {
const { data, error } = await auth.refreshSession();
if (error) {
switch (error.code) {
case "invalid_refresh_token":
console.error("Refresh token invalid, log in again");
// Log in again is required
window.location.href = "/login";
break;
case "refresh_token_expired":
console.error("Refresh token expired, log in again");
// Log in again is required
window.location.href = "/login";
break;
case "user_not_found":
console.error("user does not exist, re-register");
//Clear local conversation
localStorage.removeItem("refresh_token");
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "permission_denied":
console.error(
"Insufficient permissions, please check secure domain configuration"
);
break;
case "resource_exhausted":
console.error("Refresh frequency too high, try again later");
break;
default:
console.error("refresh fails:", error.message);
}
} else {
console.log("Refresh successful");
}
} catch (error) {
console.error("network error:", error);
}
setSession
async setSession(params: SetSessionReq): Promise<SignInRes>
Use existing access token and refresh token to set user session, support external system integration and manual session management.
-Use existing access_token and refresh_token to set user session -Suitable for scenarios where tokens are obtained from an external system and sessions are set manually. -Set session successfully to trigger SIGNED_IN event
参数
返回
示例
const { data, error } = await auth.setSession({
access_token: "your_access_token_here",
refresh_token: "your_refresh_token_here",
});
if (error) {
console.error("session setting failed:", error.message);
} else {
console.log("Session setting successful");
console.log("user information:", data.user);
console.log("session information:", data.session);
}
signOut
async signOut(params?: SignOutReq): Promise<SignOutRes>
User logout, purge current session and local storage.
-Log out current user login status securely -Purge server-side session and local storage -Support redirect to specified page
- Trigger authentication status change events
参数
返回
示例
const { data, error } = await auth.signOut();
if (error) {
console.error("logout failed:", error.message);
} else {
console.log("logout successful");
Log out from IM and navigate to the login page
window.location.href = "/login";
}
const { data, error } = await auth.signOut({
options: {
redirectTo: "/login",
clearStorage: true,
},
});
if (error) {
console.error("logout failed:", error.message);
} else {
console.log("logout successful, redirecting to login page...");
// Auto-redirect to login page
window.location.href = "/login";
}
async function safeSignOut() {
// Display the confirmation dialog box
if (!confirm("Are you sure you want to logout?")) {
return;
}
// Display loading...
document.getElementById("logoutBtn").disabled = true;
document.getElementById("logoutBtn").innerText = "Logging out...";
const { data, error } = await auth.signOut();
if (error) {
console.error("logout failed:", error.message);
alert("logout failed: " + error.message);
// Restore button status
document.getElementById("logoutBtn").disabled = false;
document.getElementById("logoutBtn").innerText = "Logout";
} else {
console.log("logout successful");
//Clear local storage
localStorage.removeItem("user_session");
sessionStorage.clear();
// Display success message
alert("Logged out safely");
Navigate to the login page
window.location.href = "/login";
}
}
// Logout button click event
document.getElementById("logoutBtn").addEventListener("click", safeSignOut);
try {
const { data, error } = await auth.signOut();
if (error) {
switch (error.code) {
case "network_error":
console.error("network connection failed, check the network and retry after setting");
alert("network connection failed, try again later");
break;
case "session_not_found":
console.error("session not found, may have logged out");
//Clear local storage and redirect
localStorage.clear();
window.location.href = "/login";
break;
case "token_invalid":
console.error("Token invalid, log in again");
//Force clear and redirect
localStorage.clear();
window.location.href = "/login";
break;
case "permission_denied":
console.error("Insufficient permissions, cannot perform log out operation");
alert("Insufficient permissions, unable to log out");
break;
case "unreachable":
console.error("server connection failed, check the network settings");
alert("server connection failed, check the network");
break;
default:
console.error("logout failed:", error.message);
alert("logout failed: " + error.message);
}
} else {
console.log("logout successful");
// Display success message
alert("Logged out safely");
Navigate to the login page
window.location.href = "/login";
}
} catch (error) {
console.error("unknown error:", error);
alert("unknown error occurs, retry");
}
User Management
getUser
async getUser(): Promise<GetUserRes>
Obtain currently logged in user detailed information, including identity information, metadata and permission status, support users material show and access verification.
-Obtain currently logged in user complete information -including basic user information, metadata and identity information Users are advised to be logged in to obtain the complete information -Support user check, permission and status verification
参数
无参数
返回
示例
const { data, error } = await auth.getUser();
if (error) {
console.error("failed to obtain user information:", error.message);
} else if (data.user) {
const user = data.user;
console.log("uid:", user.ID);
console.log("mailbox:", user.email);
console.log("phone number:", user.phone);
console.log("userName:", user.user_metadata?.username);
console.log("Nickname:", user.user_metadata?.nickName);
console.log("avatar:", user.user_metadata?.avatarUrl);
console.log("registration time:", user.created_at);
} else {
console.log("user not logged in");
}
// Display detailed information on the user profile page
async function loadUserProfile() {
const { data, error } = await auth.getUser();
if (error) {
document.getElementById("error").innerText =
"failed to obtain user information: " + error.message;
return;
}
if (data.user) {
const user = data.user;
// Update page display
document.getElementById("userEmail").innerText = user.email || "not set";
document.getElementById("userPhone").innerText = user.phone || "not set";
document.getElementById("userName").innerText =
user.user_metadata?.name || "not set";
document.getElementById("userNickname").innerText =
user.user_metadata?.nickName || "not set";
document.getElementById("userAvatar").src =
user.user_metadata?.avatarUrl || "/default-avatar.png";
document.getElementById("regTime").innerText = new Date(
user.created_at
).toLocaleString();
} else {
document.getElementById("error").innerText = "User not logged in";
}
}
Call on page loading
loadUserProfile();
async function checkUserPermissions() {
const { data, error } = await auth.getUser();
if (error) {
console.error("failed to obtain user information:", error.message);
return false;
}
if (data.user) {
const user = data.user;
// Check whether the mailbox is verified
if (!user.email_confirmed_at) {
console.log("Mailbox not verified, verify email is required");
return false;
}
Check user role
if (user.role?.includes("administrator")) {
console.log("admin user, full permissions");
return true;
} else if (!!user.role?.length) {
console.log("regular user, basic permissions");
return true;
} else {
console.log("unknown user role");
return false;
}
} else {
console.log("user not logged in, permission denied");
return false;
}
}
// Check permissions and perform operation
if (await checkUserPermissions()) {
// Authorized, perform operation
console.log("authorized, continue execution...");
} else {
// Unauthorized, display error
console.log("unauthorized, operation denied");
}
try {
const { data, error } = await auth.getUser();
if (error) {
switch (error.code) {
case "user_not_found":
console.error("user does not exist, log in again");
// The session might be expired, log in again is required
window.location.href = "/login";
break;
case "token_expired":
console.error("Access token expired, try to refresh token");
// Try to refresh token
await auth.refreshSession();
// Retrieve user information again
await auth.getUser();
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "permission_denied":
console.error(
"Insufficient permissions, please check secure domain configuration"
);
break;
case "invalid_refresh_token":
console.error("Refresh token invalid, log in again");
window.location.href = "/login";
break;
case "refresh_token_expired":
console.error("Refresh token expired, log in again");
window.location.href = "/login";
break;
default:
console.error("failed to obtain user information:", error.message);
}
} else {
console.log("user information retrieval successful");
}
} catch (error) {
console.error("unknown error:", error);
}
refreshUser
async refreshUser(): Promise<CommonRes>
Refresh current logged-in user information.
-Refresh current logged-in user complete information
- Re-fetch the latest user data from the server
- Suitable for scenarios where user information may be updated but local cache remains unsynced User must be logged in to refresh information
参数
无参数
返回
示例
const { data, error } = await auth.refreshUser();
if (error) {
console.error("failed to refresh user information:", error.message);
} else {
console.log("user information refreshed");
console.log("latest user information:", data.user);
console.log("latest session information:", data.session);
}
// Refresh page display after user modifies information
async function refreshUserProfile() {
const { data, error } = await auth.refreshUser();
if (error) {
console.error("refresh fails:", error.message);
return false;
}
if (data.user) {
const user = data.user;
// Update page display
document.getElementById("userEmail").innerText = user.email || "not set";
document.getElementById("userPhone").innerText = user.phone || "not set";
document.getElementById("name").innerText =
user.user_metadata?.name || "not set";
document.getElementById("userNickname").innerText =
user.user_metadata?.nickName || "not set";
document.getElementById("userAvatar").src =
user.user_metadata?.avatarUrl || "/default-avatar.png";
console.log("user information refreshed and update display");
return true;
}
return false;
}
// Call after user modifies information
await refreshUserProfile();
async function safeRefreshUser() {
try {
const { data, error } = await auth.refreshUser();
if (error) {
switch (error.code) {
case "user_not_found":
console.error("user does not exist, log in again");
break;
case "token_expired":
console.error("Access token expired, try to refresh session");
await auth.refreshSession();
// Refresh user information
return await auth.refreshUser();
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
default:
console.error("failed to refresh user information:", error.message);
}
return null;
}
return data;
} catch (error) {
console.error("unknown error occurs during the refresh process:", error);
return null;
}
}
// Securely refresh user information
const refreshedData = await safeRefreshUser();
if (refreshedData) {
console.log("user information refreshed successfully");
}
updateUser
async updateUser(params: UpdateUserReq): Promise<GetUserRes>
Update current logged-in user information.
-Update password not supported. Please use resetPasswordForEmail, resetPasswordForOld or reauthenticate to update password. -Update current logged-in user basic info and metadata -Support updating mailbox, mobile number, username, Nickname, avatar, etc. -User must be logged in to update information Return upon success with updated user information
参数
返回
示例
const { data, error } = await auth.updateUser({
nickname: "new nickname",
gender: "MALE",
});
if (error) {
console.error("failed to update user information:", error.message);
} else {
console.log("user information updated:", data.user);
console.log("new email:", data.user?.email);
console.log("New nickname:", data.user?.user_metadata?.nickName);
}
// Update email or phone (approval required)
const { data } = await app.auth.updateUser({
email: "new@example.com",
});
Call the verifyOtp callback to verify
await data.verifyOtp({ email: "new@example.com", token: "123456" });
async function saveUserProfile(formData) {
const { data, error } = await auth.updateUser({
username: formData.username,
nickname: formData.nickname,
gender: formData.gender,
description: formData.description,
avatar_url: formData.avatarUrl,
});
if (error) {
document.getElementById("error").innerText =
"Saving failed: " + error.message;
return false;
} else {
document.getElementById("success").innerText =
"Material saved successfully";
return true;
}
}
// Form submission event
document.getElementById("profileForm").addEventListener("submit", async (e) => {
e.preventDefault();
const formData = {
username: document.getElementById("username").value,
nickname: document.getElementById("nickname").value,
gender: document.getElementById("gender").value,
description: document.getElementById("description").value,
avatarUrl: document.getElementById("avatar").value,
};
await saveUserProfile(formData);
});
try {
const { data, error } = await auth.updateUser({
email: "invalid-email",
phone: "123456",
});
if (error) {
switch (error.code) {
case "failed_precondition":
console.error(
"The mailbox or mobile number has been used by another user, please use another number"
);
break;
case "invalid_email":
console.error("Incorrect email format, please check email format");
break;
case "invalid_phone":
console.error(
"Incorrect phone number format, please check phone number format"
);
break;
case "password_too_weak":
console.error(
"password strength is insufficient, please use a more complex password"
);
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "permission_denied":
console.error(
"Insufficient permissions, please check secure domain configuration"
);
break;
case "resource_exhausted":
console.error("Update frequency too high, try again later");
break;
case "user_not_found":
console.error("user does not exist, log in again");
break;
default:
console.error("failed to update:", error.message);
}
} else {
console.log("update succeeded");
}
} catch (error) {
console.error("network error:", error);
}
deleteUser
async deleteUser(params: DeleteMeReq): Promise<CommonRes>
Delete the account of the current logged-in user.
-Permanently delete the account of the current logged-in user. -Verify user password to confirm identity. -Once deleted, ALL user data will be permanently removed. -This operation is irreversible. Use with caution.
参数
返回
示例
const { data, error } = await auth.deleteUser({
password: "userPassword123",
});
if (error) {
console.error("account deletion failed:", error.message);
} else {
console.log("account deleted successfully");
// User logged out, redirect to homepage
window.location.href = "/";
}
async function deleteAccount(password) {
if (
!confirm(
"Confirm deletion of the account? This action is irreversible. All data will be permanently deleted."
)
) {
return false;
}
const { data, error } = await auth.deleteUser({ password });
if (error) {
switch (error.code) {
case "invalid_password":
alert("incorrect password, please enter again");
break;
case "user_not_found":
alert("user does not exist");
break;
default:
alert("delete failed: " + error.message);
}
return false;
} else {
alert("account deleted successfully");
return true;
}
}
// Delete account form submission
document
.getElementById("deleteAccountForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const password = document.getElementById("password").value;
const success = await deleteAccount(password);
if (success) {
// Redirect to homepage
window.location.href = "/";
}
});
async function deleteAccountWithVerification(password, verificationCode) {
// Step 1: Verify password
const { data: verifyData, error: verifyError } = await auth.reauthenticate();
if (verifyError) {
alert("failed authentication: " + verifyError.message);
return false;
}
Step 2: Validating Captcha input.
const { data: updateData, error: updateError } = await verifyData.updateUser({
nonce: verificationCode,
password,
});
if (updateError) {
alert("Captcha error: " + updateError.message);
return false;
}
// Step 3: Delete account
const { data, error } = await auth.deleteUser({ password });
if (error) {
alert("delete failed: " + error.message);
return false;
} else {
alert("account deleted successfully");
return true;
}
}
class AccountDeletionManager {
constructor() {
this.deletionAttempts = 0;
this.maxAttempts = 3;
}
async deleteAccount(password) {
if (this.deletionAttempts >= this.maxAttempts) {
alert("Too many deletion attempts, try again later");
return false;
}
this.deletionAttempts++;
const { data, error } = await auth.deleteUser({ password });
if (error) {
if (error.code === "invalid_password") {
const remainingAttempts = this.maxAttempts - this.deletionAttempts;
alert(`incorrect password, remaining attempts: ${remainingAttempts}`);
} else {
alert("delete failed: " + error.message);
}
return false;
} else {
alert("account deleted successfully");
this.deletionAttempts = 0;
return true;
}
}
resetAttempts() {
this.deletionAttempts = 0;
}
}
// Use the account deletion manager
const deletionManager = new AccountDeletionManager();
// Deleting Account
document.getElementById("deleteBtn").addEventListener("click", async () => {
const password = prompt("enter password confirm delete account:");
if (password) {
await deletionManager.deleteAccount(password);
}
});
Identity Source Management
getUserIdentities
async getUserIdentities(): Promise<GetUserIdentitiesRes>
Retrieve all identity sources bound to the current user.
- Retrieve all third-party identity sources. Related identity sources can be configured in Cloud Development Platform/Identity Verification/Log-in Methods. -Return detailed information of the identity source, including platform identifier, identity source ID and binding time. -User logged in status is required to retrieve identity source information.
参数
无参数
返回
示例
const { data, error } = await auth.getUserIdentities();
if (error) {
console.error("failed to retrieve identity source:", error.message);
} else if (data.identities) {
console.log("identity source bound to user:", data.identities);
data.identities.forEach((identity) => {
console.log(
`- ${identity.name} (${identity.provider}): ${identity.provider_user_id}`
);
console.log(
` Binding time: ${new Date(identity.created_at).toLocaleString()}`
);
});
} else {
console.log("user not bound to any identity source");
}
async function loadUserIdentities() {
const { data, error } = await auth.getUserIdentities();
if (error) {
document.getElementById("error").innerText =
"failed to retrieve identity source: " + error.message;
return;
}
const container = document.getElementById("identitiesContainer");
container.innerHTML = "";
if (data.identities && data.identities.length > 0) {
data.identities.forEach((identity) => {
const identityElement = document.createElement("div");
identityElement.className = "identity-item";
identityElement.innerHTML = `
<h3>${identity.name}</h3>
<p>Platform: ${identity.provider}</p>
<p>Binding time: ${new Date(identity.created_at).toLocaleString()}</p>
<button onclick="unbindIdentity('${identity.id}')">Unbind</button>
`;
container.appendChild(identityElement);
});
} else {
container.innerHTML = "<p>You have not bound any third-party account</p>";
}
}
Call on page loading
loadUserIdentities();
async function isProviderBound(provider) {
const { data, error } = await auth.getUserIdentities();
if (error) {
console.error("failed to check identity source:", error.message);
return false;
}
if (data.identities) {
return data.identities.some((identity) => identity.provider === provider);
}
return false;
}
// Check if it is bound to WeChat
const isWechatBound = await isProviderBound("wechat");
if (isWechatBound) {
console.log("WeChat account bound");
document.getElementById("bindWechatBtn").style.display = "none";
} else {
console.log("WeChat account not bound");
document.getElementById("bindWechatBtn").style.display = "block";
}
linkIdentity
async linkIdentity(params: LinkIdentityReq): Promise<LinkIdentityRes>
Bind a new identity source to the current user, and it will automatically redirect to the third-party OAuth authorization page.
- Bind a new third-party identity source to the current logged-in user. It supports binding third-party platforms such as WeChat, Google, and GitHub. The identity source must first be configured in Cloud Development Platform/Identity Verification/Login Methods.
- After binding succeeded, the identity source is usable by users to log in.
- User logged in status is required to bind an identity source
-Set
auth.detectSessionInUrltotruein cloudbase.init, and verifyOAuth will automatically verify after returning from a third-party callback, otherwise manually call the verifyOAuth method subsequently.
参数
返回
示例
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
auth: {
detectSessionInUrl: true, // Option: automatically detect OAuth parameters in the URL
},
});
// Listen to the identity source bind event
auth.onAuthStateChange((event, session, info) => {
console.log("Authentication Status Transition:", { event, session, info });
switch (event) {
case "BIND_IDENTITY":
if (!!info.error) {
console.error("failed to bind identity source:", info.error);
Here you can add UI error prompts
} else {
console.log("identity source bound");
// Reload the identity source list
await auth.getUserIdentities();
}
break;
default:
return;
}
});
try {
const { data, error } = await auth.linkIdentity({
provider: "google",
});
if (error) {
console.error("failed to bind identity source:", error.message);
// handle bind failure logic
return;
}
console.log("identity source binding request sent, wait for user authorization...");
Binding request successful, waiting for user to complete the OAuth 2.0 authorization process
} catch (error) {
console.error("error occurs when calling the linkIdentity method:", error);
// Handle network error or other exceptions
}
const app = cloudbase.init({
env: "your-env-id", // Replace this value with your environment ID
region: "ap-shanghai", // Region, defaults to Shanghai
accessKey: "", // Fill in the generated Publishable Key
auth: {
detectSessionInUrl: true, // Option: automatically detect OAuth parameters in the URL
},
});
const auth = app.auth;
async function bindProvider(provider) {
try {
// Display loading...
document.getElementById("bindBtn").disabled = true;
document.getElementById("status").innerText = "binding...";
const { data, error } = await auth.linkIdentity({ provider });
if (error) {
console.error("failed to bind identity source:", error);
document.getElementById("status").innerText =
"bind failure: " + error.message;
document.getElementById("bindBtn").disabled = false;
// Provide more specific notifications based on error type
if (error.message.includes("already bound")) {
document.getElementById("status").innerText =
The identity source is already bound, no need to repeat binding.
} else if (error.message.includes("not logged in")) {
document.getElementById("status").innerText = "please log in first to bind identity source";
} else if (error.message.includes("provider not found")) {
document.getElementById("status").innerText = "unsupported identity source kind";
}
} else {
console.log("identity source binding request sent, wait for user authorization...");
document.getElementById("status").innerText = "redirecting to authorization webpage...";
Binding request successful, waiting for user to complete OAuth 2.0 authorization process
// The actual binding result will be through onAuthStateChange event notification
}
} catch (error) {
console.error("exception occurs when binding identity source:", error);
document.getElementById("status").innerText = "exception occurs in binding process, retry";
document.getElementById("bindBtn").disabled = false;
}
}
// Listen to the identity source binding result
auth.onAuthStateChange((event, session, info) => {
if (event === "BIND_IDENTITY") {
if (info.error) {
console.error("failed to bind identity source:", info.error);
document.getElementById("status").innerText =
"Authorization failed: " + info.error.message;
document.getElementById("bindBtn").disabled = false;
} else {
console.log("identity source binding succeeded");
document.getElementById("status").innerText = "binding succeeded";
document.getElementById("bindBtn").style.display = "none";
// Refresh the identity source list
loadUserIdentities();
}
}
});
// Bind button click event
document.getElementById("bindWechatBtn").addEventListener("click", () => {
bindProvider("wechat");
});
unlinkIdentity
async unlinkIdentity(params: UnlinkIdentityReq): Promise<CommonRes>
Unbind the identity source bound to the current user.
- Unbind the third-party identity source bound to the current logged-in user. Related identity sources can be configured in Cloud Development Platform/Identity Verification/Log-in Methods.
- Unbinding is successful. Reload the identity source list.
- Use the identity source flag (provider) instead of the identity source ID (identity_id) to proceed with unbinding.
参数
返回
示例
const { data, error } = await auth.unlinkIdentity({
provider: "wechat",
});
if (error) {
console.error("failed to unbind identity source:", error.message);
} else {
console.log("identity source unbinding succeeded");
// Reload the identity source list
await auth.getUserIdentities();
}
async function unbindIdentity(provider) {
if (!confirm("Are you sure you want to unbind this account?")) {
return;
}
const { data, error } = await auth.unlinkIdentity({ provider });
if (error) {
alert("failed to unbind: " + error.message);
} else {
alert("unbinding is successful");
// Reload the identity source list
await loadUserIdentities();
}
}
// Unbind button click event
document.querySelectorAll(".unbind-btn").forEach((btn) => {
btn.addEventListener("click", (e) => {
const provider = e.target.dataset.provider;
unbindIdentity(provider);
});
});
async function unbindMultipleProviders(providers) {
const results = [];
for (const provider of providers) {
const result = await auth.unlinkIdentity({ provider });
results.push({ provider, result });
if (result.error) {
console.error(`failed to unbind ${provider}:`, result.error.message);
} else {
console.log(`Unbinding ${provider} succeeded`);
}
}
return results;
}
// Unbind multiple identity sources
const providers = ["wechat", "google", "github"];
const unbindResults = await unbindMultipleProviders(providers);
// Count unbinding results
const successCount = unbindResults.filter((r) => !r.result.error).length;
console.log(
Successfully unbound ${successCount} identity sources, failed ${
providers.length - successCount
}
);
try {
const { data, error } = await auth.unlinkIdentity({
provider: "invalid_provider",
});
if (error) {
switch (error.code) {
case "provider_not_found":
console.error(
"identity source not found, please check whether the identity source flag is correct"
);
break;
case "last_identity_cannot_unlink":
console.error(
"cannot unbound the last identity source, please keep at least one login method"
);
break;
case "permission_denied":
console.error(
"no permission to unbind this identity source, check permission settings"
);
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "resource_exhausted":
console.error("Unbinding frequency too high, please retry later");
break;
case "user_not_found":
console.error("user does not exist, log in again");
break;
case "token_expired":
console.error("session expired, log in again");
break;
default:
console.error("failed to unbind:", error.message);
}
} else {
console.log("unbinding is successful");
}
} catch (error) {
console.error("network error:", error);
}
Password Management
resetPasswordForEmail
async resetPasswordForEmail(email: string): Promise<ResetPasswordForEmailRes>
Reset user password via mailbox using a four-step verification process.
-Send verification code via mailbox to reset user password -Use a four-step verification process: send verification code → wait for user input → verify verification code → set new password. -The user email must be registered and verified.
参数
User registration email address
返回
示例
// Step 1: Send verification to mailbox
const { data, error } = await auth.resetPasswordForEmail("user@example.com");
if (error) {
console.error("send Captcha failed:", error.message);
} else {
console.log("Captcha has been sent to email, waiting for user input...");
Step 2: Wait for user input of Captcha and new password.
const verificationCode = "123456"; // user input
const newPassword = "newSecurePassword123"; // user-entered new password
// Step 3: Verify the verification code and set new password
const { data: loginData, error: loginError } = await data.updateUser({
nonce: verificationCode,
password: newPassword,
});
if (loginError) {
console.error("password resetting failed:", loginError.message);
} else {
console.log("password reset successful, user automatically logged in");
console.log("user information:", loginData.user);
}
}
let resetPasswordVerify = null;
async function startPasswordReset(email) {
const { data, error } = await auth.resetPasswordForEmail(email);
if (error) {
document.getElementById("error").innerText =
"send Captcha failed: " + error.message;
return false;
} else {
resetPasswordVerify = data.updateUser;
// Display the Captcha input box
document.getElementById("verificationSection").style.display = "block";
document.getElementById("emailSection").style.display = "none";
document.getElementById("status").innerText =
Captcha has been sent to your email, please check.
return true;
}
}
async function completePasswordReset(code, newPassword) {
if (!resetPasswordVerify) {
alert("Please first send Captcha");
return false;
}
const { data, error } = await resetPasswordVerify({
nonce: code,
password: newPassword,
});
if (error) {
document.getElementById("error").innerText =
"password resetting failed: " + error.message;
return false;
} else {
document.getElementById("success").innerText = "password reset successful, automatically logged in";
Navigate to the homepage
setTimeout(() => {
window.location.href = "/dashboard";
}, 2000);
return true;
}
}
// Form submission event
document.getElementById("resetForm").addEventListener("submit", async (e) => {
e.preventDefault();
const email = document.getElementById("email").value;
const code = document.getElementById("code").value;
const newPassword = document.getElementById("newPassword").value;
if (!resetPasswordVerify) {
await startPasswordReset(email);
} else {
await completePasswordReset(code, newPassword);
}
});
try {
const { data, error } = await auth.resetPasswordForEmail("invalid-email");
if (error) {
switch (error.code) {
case "invalid_email":
console.error("Incorrect email format, please check email format");
break;
case "user_not_found":
console.error(
"User does not exist, please check whether the mailbox is correct"
);
break;
case "email_not_verified":
console.error("Mailbox not verified, please first verify email");
break;
case "rate_limit_exceeded":
console.error("Sending frequency too high, try again later");
break;
default:
console.error("send Captcha failed:", error.message);
}
}
} catch (error) {
console.error("network error:", error);
}
resetPasswordForOld
async resetPasswordForOld(params: ResetPasswordForOldReq): Promise<SignInRes>
Reset the password of the current logged-in user with the old password.
-Reset the password of the current logged-in user by verifying the old password. -User must be logged in. -Suitable for scenarios where users remember the old password
参数
返回
示例
const { data, error } = await auth.resetPasswordForOld({
new_password: "newSecurePassword123",
old_password: "oldPassword123",
});
if (error) {
console.error("password reset failed:", error.message);
} else {
console.log("password reset successful");
console.log("user information:", data.user);
console.log("session information:", data.session);
}
async function changePassword(oldPassword, newPassword) {
const { data, error } = await auth.resetPasswordForOld({
new_password: newPassword,
old_password: oldPassword,
});
if (error) {
switch (error.code) {
case "invalid_password":
alert("old password incorrect");
break;
case "password_too_weak":
alert("new password strength insufficient, please use complex password");
break;
default:
alert("password reset failed: " + error.message);
}
return false;
} else {
alert("password reset successful");
return true;
}
}
// Form submission event
document
.getElementById("passwordForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const oldPassword = document.getElementById("oldPassword").value;
const newPassword = document.getElementById("newPassword").value;
const confirmPassword = document.getElementById("confirmPassword").value;
if (newPassword !== confirmPassword) {
alert("new password and confirm password do not match");
return;
}
const success = await changePassword(oldPassword, newPassword);
if (success) {
Navigate to the homepage or user center
window.location.href = "/dashboard";
}
});
function validatePassword(password) {
const minLength = 8;
const hasUpperCase = /[A-Z]/.test(password);
const hasLowerCase = /[a-z]/.test(password);
const hasNumbers = /\d/.test(password);
const hasSpecialChar = /[!@#$%^&*(),.?":{}|<>]/.test(password);
return (
password.length >= minLength &&
hasUpperCase &&
hasLowerCase &&
hasNumbers &&
hasSpecialChar
);
}
async function resetPasswordWithValidation(oldPassword, newPassword) {
if (!validatePassword(newPassword)) {
alert(
"Password must include uppercase and lowercase letters, digits and special characters, and be at least 8 characters long"
);
return false;
}
const { data, error } = await auth.resetPasswordForOld({
new_password: newPassword,
old_password: oldPassword,
});
if (error) {
alert("password reset failed: " + error.message);
return false;
}
alert("password reset successful");
return true;
}
try {
const { data, error } = await auth.resetPasswordForOld({
new_password: "newPassword123",
old_password: "wrongOldPassword",
});
if (error) {
switch (error.code) {
case "invalid_password":
console.error("old password incorrect, please enter again");
document.getElementById("oldPassword").classList.add("error");
break;
case "password_too_weak":
console.error(
"password strength is insufficient, please use a more complex password"
);
document.getElementById("newPassword").classList.add("error");
break;
case "user_not_found":
console.error("user does not exist, log in again");
window.location.href = "/login";
break;
case "token_expired":
console.error("session expired, log in again");
window.location.href = "/login";
break;
case "permission_denied":
console.error("insufficient permissions, cannot modify password");
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "resource_exhausted":
console.error("Reset frequency too high, try again later");
break;
default:
console.error("password reset failed:", error.message);
}
} else {
console.log("password reset successful");
}
} catch (error) {
console.error("network error:", error);
}
reauthenticate
async reauthenticate(): Promise<ReauthenticateRes>
Re-authenticate the current logged-in user identity, verify with Captcha and allow password change.
SMS verification code is only supported in the Shanghai region
-Re-authenticate the present logged-in user identity and support password update. -Verify by sending a verification code to the user's registered mailbox or mobile number, giving priority to the mailbox. If the user has not set a mailbox, use the mobile number. -Applicable to identity verification before security-sensitive operations
参数
无参数
返回
示例
// Step 1: Send Captcha (use current user information)
const { data, error } = await auth.reauthenticate();
if (error) {
console.error("send Captcha failed:", error.message);
} else {
console.log("Captcha has been sent, waiting for user input...");
Step 2: Wait for user input of Captcha and new password.
const verificationCode = "123456"; // user input
const newPassword = "newSecurePassword123"; // user-entered new password
// Step 3: Verify the verification code and set new password
const { data: loginData, error: loginError } = await data.updateUser({
nonce: verificationCode,
password: newPassword,
});
if (loginError) {
console.error("authentication fail again:", loginError.message);
} else {
console.log("Re-authenticate successful, password updated");
console.log("user information:", loginData.user);
}
}
async function verifyIdentityBeforeSensitiveOperation() {
Re-authenticate the user before executing sensitive operations
const { data, error } = await auth.reauthenticate();
if (error) {
console.error("failed authentication:", error.message);
return false;
}
console.log("Captcha has been sent to your mailbox/mobile phone, please enter the verification code to proceed");
// Display the Captcha input interface
document.getElementById("verificationModal").style.display = "block";
return new Promise((resolve) => {
// Wait for user input Captcha
document.getElementById("verifyBtn").addEventListener("click", async () => {
const code = document.getElementById("code").value;
const newPassword = document.getElementById("newPassword").value;
const { data: verifyData, error: verifyError } = await data.updateUser({
nonce: code,
password: newPassword,
});
if (verifyError) {
console.error("verification failed:", verifyError.message);
resolve(false);
} else {
console.log("Identity verification successful, proceed with sensitive operations");
document.getElementById("verificationModal").style.display = "none";
resolve(true);
}
});
});
}
// Verify identity before executing sensitive operations
if (await verifyIdentityBeforeSensitiveOperation()) {
// Execute sensitive operations
performSensitiveOperation();
}
try {
const { data, error } = await auth.reauthenticate();
if (error) {
switch (error.code) {
case "user_not_found":
console.error("user not logged in, please log in first");
window.location.href = "/login";
break;
case "email_not_set":
console.error("Mailbox not set by the user, unable to send Captcha");
document.getElementById("error").innerText = "Set email address first";
break;
case "phone_not_set":
console.error(
"Mobile number not set by the user, unable to send Captcha"
);
document.getElementById("error").innerText = "Set first phone number";
break;
case "rate_limit_exceeded":
console.error("Sending frequency too high, try again later");
document.getElementById("resendBtn").disabled = true;
setTimeout(() => {
document.getElementById("resendBtn").disabled = false;
}, 60000);
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "permission_denied":
console.error(
"Insufficient permissions, please check secure domain configuration"
);
break;
default:
console.error("send Captcha failed:", error.message);
document.getElementById("error").innerText =
"send failed: " + error.message;
}
}
} catch (error) {
console.error("network error:", error);
document.getElementById("error").innerText =
"Network error, please try again";
}
async function verifyReauthenticationCode(code, newPassword) {
try {
const { data, error } = await auth.reauthenticate();
if (error) {
console.error("send Captcha failed:", error.message);
return false;
}
const { data: verifyData, error: verifyError } = await data.updateUser({
nonce: code,
password: newPassword,
});
if (verifyError) {
switch (verifyError.code) {
case "invalid_code":
console.error("Captcha incorrect, please enter again");
document.getElementById("code").classList.add("error");
break;
case "code_expired":
console.error("Captcha expired, please obtain again");
document.getElementById("resendBtn").style.display = "block";
break;
case "max_attempts_exceeded":
console.error("Too many verification attempts, please retry later");
document.getElementById("verifyBtn").disabled = true;
break;
case "password_too_weak":
console.error(
"password strength is insufficient, please use a more complex password"
);
document.getElementById("newPassword").classList.add("error");
break;
default:
console.error("verification failed:", verifyError.message);
}
return false;
} else {
console.log("Re-authenticate successful");
return true;
}
} catch (error) {
console.error("network error:", error);
return false;
}
}
Verification Management
verifyOAuth
async verifyOAuth(params?: VerifyOAuthReq): Promise<SignInRes>
Verify the third-party platform authorization callback and complete the OAuth login process.
-Verify the third-party platform authorization callback, retrieve user information, complete login, and use in conjunction with signInWithOAuth. -Support auto retrieval of authorization code and status parameter from URL parameter -Provide a complete security verification mechanism to prevent CSRF attacks
参数
返回
示例
// Call on the callback page to automatically obtain URL parameters
const { data, error } = await auth.verifyOAuth();
if (error) {
console.error("authorization verification failed:", error.message);
} else {
console.log("authorization successful, user information:", data.user);
console.log("session information:", data.session);
Navigate to the homepage after successful verification
window.location.href = "/home";
}
// Manually obtain URL parameters and verify
const urlParams = new URLSearchParams(window.location.search);
const code = urlParams.get("code");
const state = urlParams.get("state");
const { data, error } = await auth.verifyOAuth({
code: code,
state: state,
provider: "wechat",
});
if (error) {
console.error("Weixin authorization verification failed:", error.message);
} else {
console.log(
"Weixin authorization successful, user nickname:",
data.user?.user_metadata?.nickName
);
}
Step one: generate an authorization link
const { data, error } = await auth.signInWithOAuth({
provider: "wechat",
options: {
redirectTo: "https://example.com/oauth-callback",
state: "wx_oauth_20241204",
},
});
if (error) {
console.error("failed to obtain authorization link:", error.message);
return;
}
step 2: navigate to the authorization page
window.location.href = data.url;
// In the callback page (oauth-callback):
Step 3: Verify the authorization result
const { data: verifyData, error: verifyError } = await auth.verifyOAuth();
if (verifyError) {
console.error("authorization verification failed:", verifyError.message);
document.getElementById("error").innerText = verifyError.message;
} else {
console.log("authorization successful, user logged in");
window.location.href = "/dashboard";
}
try {
const { data, error } = await auth.verifyOAuth();
if (error) {
switch (error.code) {
case "invalid_code":
console.error(
"authorization code invalid or expired, please reauthorize"
);
break;
case "state_mismatch":
console.error(
"State parameter mismatch, may pose security risks, please reauthorize"
);
break;
case "provider_mismatch":
console.error(
"Third-party platform flag mismatch, please check platform configuration"
);
break;
case "failed_precondition":
console.error(
"failed to obtain user information from third party, please check platform configuration"
);
break;
case "resource_exhausted":
console.error("Request frequency too high, please retry later");
break;
case "permission_denied":
console.error(
"Insufficient permissions, please check secure domain configuration"
);
break;
case "unreachable":
console.error(
"network connection failed, check the network and retry after setting"
);
break;
case "invalid_code":
console.error(
"authorization code invalid or expired, please reauthorize"
);
break;
case "state_mismatch":
console.error(
"State parameter mismatch, may pose security risks, please reauthorize"
);
break;
default:
console.error("authorization verification failed:", error.message);
}
document.getElementById("error").innerText =
"Authorization failure, please try again";
} else {
console.log("Authorization verification successful");
}
} catch (error) {
console.error("network error:", error);
}
verifyOtp
async verifyOtp(params: VerifyOtpReq): Promise<SignInRes>
Verify the one-time password (OTP) to complete login or sign-up process.
SMS verification code is only supported in the Shanghai region
-Verify the one-time password (OTP) sent to your mailbox or mobile number. -Support two verification methods: mailbox or mobile number (choose one)
- Automatically log in the user and return session information after successful verification
- Suitable for registration, login, and password reset scenarios
参数
返回
示例
const phone = "13800138000";
// 1. Get a Captcha
const { data } = await auth.resend({ phone });
// 2. Verify the Captcha
const { data: verifyData, error } = await auth.verifyOtp({
phone: "13800138000",
token: "123456",
messageId: data.messageId,
});
if (error) {
console.error("verification failed:", error.message);
} else {
console.log("verification successful, user information:", data: verifyData.user);
console.log("session information:", data: verifyData.session);
}
const email = "user@example.com";
// 1. Get a Captcha
const verificationInfo = await auth.getVerification({
email,
});
// 2. Verify the Captcha
const { data, error } = await auth.verifyOtp({
email,
token: "654321",
verificationInfo,
});
if (error) {
console.error("Mailbox verification failed:", error.message);
} else {
console.log(
"Mailbox verification is successful, user email:",
data.user?.email
);
}
async function completeRegistration(email, verificationCode) {
const { data, error } = await auth.verifyOtp({
email: email,
token: verificationCode,
});
if (error) {
document.getElementById("error").innerText =
"verification failed: " + error.message;
return false;
} else {
document.getElementById("success").innerText =
"Register successfully. Welcome to join";
// Automatically log in the user
window.location.href = "/dashboard";
return true;
}
}
// Registration form submission
document
.getElementById("registerForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const email = document.getElementById("email").value;
const code = document.getElementById("code").value;
await completeRegistration(email, code);
});
try {
const { data, error } = await auth.verifyOtp({
phone: "13800138000",
token: "wrong_code",
});
if (error) {
switch (error.code) {
case "invalid_code":
console.error("Captcha error, please enter again");
document.getElementById("code").classList.add("error");
break;
case "code_expired":
console.error("Captcha expired, please obtain again");
document.getElementById("resendBtn").style.display = "block";
break;
case "max_attempts_exceeded":
console.error("Too many verification attempts, try again later");
document.getElementById("verifyBtn").disabled = true;
break;
default:
console.error("verification failed:", error.message);
}
} else {
console.log("Verification successful");
}
} catch (error) {
console.error("network error:", error);
}
resend
async resend(params: ResendReq): Promise<ResendRes>
Resend Captcha to mailbox or phone number.
SMS verification code is only supported in the Shanghai region
-Resend verification code to user's mailbox or mobile number -Support registration, mailbox update, mobile number change, and other scenarios. -Resend to get a new message ID for verification process -Provide rate limit protection to prevent malicious resend
参数
返回
示例
// Send verification code for the first time
const { data, error } = await auth.signInWithOtp({ phone: "13800138000" });
// Captcha verification callback
let signUpVerify = data.verifyOtp;
// Resend Captcha to get a new messageId
const { data: resendData, error: resendError } = await auth.resend({
phone: "13800138000",
type: "signup",
});
if (resendError) {
console.error("resend verification code failed:", resendError.message);
console.error("error code:", resendError.code);
} else {
console.log("verification code resent, message ID:", resendData.messageId);
// Pass the new messageId to the callback parameter of signInWithOtp() or signUp()
const verificationCode = "123456"; // user input
const messageId = resendData.messageId; // new messageId
// Use the new messageId to verify
const { data: loginData, error: loginError } = await signUpVerify({
token: verificationCode,
messageId,
});
if (loginError) {
console.error("verification failed:", loginError.message);
} else {
console.log("Verification successful");
}
// Countdown starts
startCountdown(60);
}
const { data, error } = await auth.resend({
email: "user@example.com",
type: "email_change",
});
if (error) {
console.error("Resend Mailbox Captcha failed:", error.message);
} else {
console.log("Mailbox Captcha resent");
// Display prompt message
document.getElementById("resendStatus").innerText =
The verification code has been resent to your mailbox.
}
let countdown = 0;
let countdownInterval;
function startCountdown(seconds) {
countdown = seconds;
const resendBtn = document.getElementById("resendBtn");
resendBtn.disabled = true;
resendBtn.innerText = `${countdown}s to resend`;
countdownInterval = setInterval(() => {
countdown--;
resendBtn.innerText = `${countdown}s to resend`;
if (countdown <= 0) {
clearInterval(countdownInterval);
resendBtn.disabled = false;
resendBtn.innerText = "Resend Captcha";
}
}, 1000);
}
async function resendVerificationCode() {
const email = document.getElementById("email").value;
if (!email) {
alert("Enter email address");
return;
}
const { data, error } = await auth.resend({
email: email,
type: "signup",
});
if (error) {
alert("resend failed: " + error.message);
} else {
alert("Verification code has been resent to your mailbox");
startCountdown(60); // 60-second countdown
}
}
// Resend button click event
document
.getElementById("resendBtn")
.addEventListener("click", resendVerificationCode);
try {
const { data, error } = await auth.resend({
phone: "13800138000",
type: "signup",
});
if (error) {
switch (error.code) {
case "rate_limit_exceeded":
console.error("Sending frequency too high, try again later");
document.getElementById("resendBtn").disabled = true;
setTimeout(() => {
document.getElementById("resendBtn").disabled = false;
}, 60000); // Retry after 1 minute
break;
case "invalid_phone":
console.error("Incorrect phone number format");
break;
case "invalid_email":
console.error("Incorrect email format");
break;
default:
console.error("resend failed:", error.message);
}
} else {
console.log("resend successful");
}
} catch (error) {
console.error("network error:", error);
}
Other tools
onAuthStateChange
onAuthStateChange(callback: OnAuthStateChangeCallback): OnAuthStateChangeResult
Listen to authentication status changes and respond to events such as logon, logout, and token refresh in real time.
-Listen to user authentication status change events -Support various event types: logon, log out, token refresh, user information update, identity source bind. -Return the subscription object for cancel listening
- Suitable to build responsive UI and status management
参数
Status change callback function
返回
示例
const { data } = auth.onAuthStateChange((event, session, info) => {
console.log("Authentication Status Transition:", event, session, info);
switch (event) {
case "INITIAL_SESSION":
console.log("initial session established");
if (session) {
console.log("user logged in:", session.user?.email);
} else {
console.log("user not logged in");
}
break;
case "SIGNED_IN":
console.log("user login successful:", session.user?.email);
// Update UI display
document.getElementById("loginBtn").style.display = "none";
document.getElementById("userInfo").style.display = "block";
document.getElementById("userEmail").innerText =
session.user?.email || "";
break;
case "SIGNED_OUT":
console.log("user logged out");
// Update UI display
document.getElementById("loginBtn").style.display = "block";
document.getElementById("userInfo").style.display = "none";
break;
case "PASSWORD_RECOVERY":
console.log("password reset");
// Show the password reset interface
document.getElementById("passwordResetForm").style.display = "block";
break;
case "TOKEN_REFRESHED":
console.log("Token refreshed");
break;
case "USER_UPDATED":
console.log("user information updated");
// Update user information display
if (session) {
document.getElementById("userEmail").innerText =
session.user?.email || "";
document.getElementById("userAvatar").src =
session.user?.user_metadata?.avatarUrl || "";
}
break;
case "BIND_IDENTITY":
console.log("identity source binding result");
if (!!info.error) {
console.log("identity source binding failed");
} else {
console.log("identity source bound");
}
break;
}
});
// Cancel listening (called during component uninstallation)
// data.subscription.unsubscribe();
import { useEffect, useState } from "react";
function AuthStatus() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const { data } = auth.onAuthStateChange((event, session, info) => {
setLoading(false);
if (event === "SIGNED_IN" || event === "INITIAL_SESSION") {
setUser(session?.user || null);
} else if (event === "SIGNED_OUT") {
setUser(null);
}
});
// cleanup function
return () => {
data.subscription.unsubscribe();
};
}, []);
if (loading) {
return <div>loading...</div>;
}
return (
<div>
{user ? (
<div>
<p>Welcome, {user.email}</p>
<button onClick={() => auth.signOut()}>Logout</button>
</div>
) : (
<div>
<p>please log in first</p>
<button
onClick={() =>
auth.signInWithPassword({
/* Login parameters */
})
}
>
Log in.
</button>
</div>
)}
</div>
);
}
// Route guard component
function RouteGuard({ children }) {
const [authenticated, setAuthenticated] = useState(false);
const [loading, setLoading] = useState(true);
useEffect(() => {
const { data } = auth.onAuthStateChange((event, session, info) => {
setLoading(false);
if (event === "SIGNED_IN" || event === "INITIAL_SESSION") {
if (session) {
setAuthenticated(true);
} else {
setAuthenticated(false);
}
} else if (event === "SIGNED_OUT") {
setAuthenticated(false);
}
});
return () => {
data.subscription.unsubscribe();
};
}, []);
if (loading) {
return <div>Check login status...</div>;
}
if (!authenticated) {
// Not logged in, redirect to login page
window.location.href = "/login";
return <div>Redirect to login page...</div>;
}
return children;
}
// Use route guard
function App() {
return (
<div>
<RouteGuard>
<Dashboard />
</RouteGuard>
</div>
);
}
Global authentication status management
class AuthManager {
constructor() {
this.currentUser = null;
this.listeners = [];
this.setupAuthListener();
}
setupAuthListener() {
const { data } = auth.onAuthStateChange((event, session, info) => {
switch (event) {
case "SIGNED_IN":
case "INITIAL_SESSION":
this.currentUser = session?.user || null;
this.notifyListeners();
break;
case "SIGNED_OUT":
this.currentUser = null;
this.notifyListeners();
break;
}
});
this.unsubscribe = data.subscription.unsubscribe;
}
addListener(listener) {
this.listeners.push(listener);
}
removeListener(listener) {
this.listeners = this.listeners.filter((l) => l !== listener);
}
notifyListeners() {
this.listeners.forEach((listener) => listener(this.currentUser));
}
destroy() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
}
// Create a global authentication manager
const authManager = new AuthManager();
// for use in different page
function PageA() {
const [user, setUser] = useState(null);
useEffect(() => {
authManager.addListener(setUser);
return () => authManager.removeListener(setUser);
}, []);
return <div>{user ? `Welcome, ${user.email}` : "Log in"}</div>;
}
getClaims
async getClaims(): Promise<GetClaimsRes>
Retrieve the claim info from the current access token for debug and permission check.
-Parse the JWT claim info from the current access token. -Return the header, declaration, and signature of the token. -Debug token info, check permissions, and verify token status. -Users are advised to be logged in to obtain token info
参数
无参数
返回
示例
const { data, error } = await auth.getClaims();
if (error) {
console.error("failed to retrieve declaration:", error.message);
} else {
console.log("Token claim information:", data.claims);
console.log("Token header information:", data.header);
console.log("Token signature:", data.signature);
// Parse user information
if (data.claims) {
console.log("uid:", data.claims.sub);
console.log(
"Expiration time:",
new Date(data.claims.exp * 1000).toLocaleString()
);
console.log(
"Issuance time:",
new Date(data.claims.iat * 1000).toLocaleString()
);
console.log("user role:", data.claims.role);
}
}
async function checkTokenPermissions() {
const { data, error } = await auth.getClaims();
if (error) {
console.error("failed to obtain token information:", error.message);
return false;
}
if (data.claims) {
const claims = data.claims;
// Check if token is expired
const now = Math.floor(Date.now() / 1000);
if (claims.exp && claims.exp < now) {
console.error("Token expired");
return false;
}
Check user role
if (claims.role === "admin") {
console.log("admin permission");
return true;
} else if (claims.role === "user") {
console.log("ordinary user privilege");
return true;
} else {
console.error("unknown user role");
return false;
}
}
return false;
}
// Check permissions and perform operation
if (await checkTokenPermissions()) {
console.log("authorized, continue execution...");
} else {
console.log("unauthorized, operation denied");
}
async function checkTokenExpiration() {
const { data, error } = await auth.getClaims();
if (error) {
console.error("failed to check token:", error.message);
return false;
}
if (data.claims) {
const claims = data.claims;
const now = Math.floor(Date.now() / 1000);
const expiresAt = claims.exp;
if (expiresAt) {
const timeLeft = expiresAt - now;
const minutesLeft = Math.floor(timeLeft / 60);
const secondsLeft = timeLeft % 60;
if (timeLeft <= 0) {
console.error("Token expired, log in again");
return false;
} else if (timeLeft < 300) {
console.warn(
`The token will expire in ${minutesLeft} minutes and ${secondsLeft} seconds. It is advisable to refresh the token.`
);
return true;
} else {
console.log(
`Token valid, remaining time: ${minutesLeft} minutes ${secondsLeft} seconds`
);
return true;
}
}
}
return false;
}
// Check token status periodically
setInterval(async () => {
const isValid = await checkTokenExpiration();
if (!isValid) {
console.log("Token expired, automatically refresh...");
await auth.refreshSession();
}
}, 60000); // check once per minute
toDefaultLoginPage
async toDefaultLoginPage(params: authModels.ToDefaultLoginPage): Promise<void>
Redirect to the default login page, fully compatible with web and WeChat mini program.
-Support redirection to the system default login page -Compatible with Web and WeChat mini program.
- Configurable login page version and redirect address -Support redirect with custom parameters
Debug locally
If you develop a Web application, since the static resources of the __auth login page are stored in Website Hosting, you need to configure a proxy during local debugging to successfully redirect to the __auth login page.
Recommended to use the Whistle tool to configure proxy. The access domain of the __auth login page can be viewed in Static Website Hosting - Configuration Message - Default Domain Name.
Assuming the access address of the locally started application is http://localhost:3000 and the access domain of the __auth login page is lowcode-xxx-xxx.tcloudbaseapp.com, the Rules configuration of the Whistle proxy is as follows:
https://lowcode-xxx-xxx.tcloudbaseapp.com http://localhost:3000
# Configure proxy for other application paths
After running the application, it can be accessed via https://lowcode-xxx-xxx.tcloudbaseapp.com
参数
返回
示例
const app = cloudbase.init({
env: "xxxx-yyy",
region: "ap-shanghai", // Defaults to Shanghai region if not specified
});
const auth = app.auth();
await auth.toDefaultLoginPage({
config_version: "env",
app_id: "app-xxx",
redirect_uri: "xxx",
});
Error Code
Login error
| Error Code | Description |
|---|---|
| not_found | user does not exist |
| password_not_set | The current user has not set a password. Please use Captcha to log in or third-party login method |
| invalid_password | Incorrect Password |
| user_pending | user not activated |
| user_blocked | user disabled |
| invalid_status | Exceeds the maximum number of retries for password, try again later |
| invalid_two_factor | Captcha mismatch or outdated |
Registration error
| Error Code | Description |
|---|---|
| failed_precondition | The phone number or mailbox you input has been registered, please use another number |
Captcha-related errors
| Error Code | Description |
|---|---|
| failed_precondition | failed to obtain user information from third party |
| resource_exhausted | Your attempts are too frequent, try again later |
| invalid_argument | The input verification code is incorrect or expired |
| aborted | Too many attempts, go back to the first page and try again later |
| permission_denied | Your current session expired, return and retry |
| captcha_required | Captcha is required, based on robot service access |
| captcha_invalid | Incorrect Captcha, based on robot service access |
Other Errors
| Error Code | Description |
|---|---|
| unreachable | Network error, check your network connection and try again later |
Error Description
| Error Code | Error Description | Description |
|---|---|---|
| permission_denied | cors permission denied, check if {url} is in your client {env} domains | please check whether it has been configured in "cloud Development Platform/Environment Configuration/Secure source/Protected domains" (https://tcb.cloud.tencent.com/dev?envId=#/env/safety-source) for the corresponding {env} environment. It will take effect 10 minutes after configuration. |
Complete type definition
SignInAnonymouslyReq
// Anonymous login parameters
interface SignInAnonymouslyReq {
provider_token?: string; // token (optional)
}
User
interface User {
id: any; // User ID
aud: string; // Audience
role: string[]; // user role
email: any; // Email
email_confirmed_at: string; // Email confirmation time
phone: any; // Phone number
phone_confirmed_at: string; // Mobile number confirmation time
confirmed_at: string; // Confirmation time
last_sign_in_at: string; // Last login time
app_metadata: {
app_metadata: {
provider: any; // Provider
providers: any[]; // Provider list
};
user_metadata: {
user_metadata: {
name: any; // Name
picture: any; // Avatar
username: any; // Username
gender: any; // Gender
locale: any; // Region
uid: any; // User ID
nickName: any; // Nickname
avatarUrl: any; // Avatar URL
location: any; // Location
hasPassword: any; // Whether there is a password
};
identities: any; // Identity information
created_at: string; // Creation time
updated_at: string; // Update time
is_anonymous: boolean; // Whether the user is anonymous
// Add a field.
recovery_sent_at?: string; // Password reset send time
email_change_sent_at?: string; // Email change send time
phone_change_sent_at?: string; // Phone number change send time
new_email?: string; // New email address
new_phone?: string; // New phone number
}
Session
interface Session {
access_token: string; // Access token
refresh_token: string; // Refresh token
expires_in: number; // Expiration time (seconds)
token_type: string; // Token type
user: User; // User information
// Add a field.
provider_token?: string; // Third-party platform token
provider_refresh_token?: string; // Third-party platform refresh token
expires_at?: number; // Expiry timestamp
issued_at?: number; // Issuance timestamp
scope?: string; // Authorization scope
token_id?: string; // Token ID
}
AuthError
// Authentication error type
interface AuthError extends Error {
code: (string & {}) | undefined; // Error code
status: number | undefined; // HTTP Status Code
// Common error codes
// 400: Client Error
// - invalid_email: Incorrect email format
// - invalid_phone: Incorrect phone number format
// - invalid_password: Invalid password format
// - user_not_found: user does not exist
// - email_already_exists: Email already exists
// - phone_already_exists: Phone number already exists
// - username_already_exists: Username already exists
// - invalid_code: Invalid verification code
// - code_expired: Captcha expired
// - max_attempts_exceeded: Too many verification attempts
// - password_too_weak: Password strength is insufficient
// - invalid_token: Token invalid
// - token_expired: Token expired
// - state_mismatch: State parameter mismatch
// - provider_not_supported: Unsupported third-party platform
// - provider_mismatch: Third-party platform flag mismatch
// - failed_precondition: Prerequisite failed
// - permission_denied: Insufficient permissions
// - resource_exhausted: Resource exhaustion
// - unreachable: Network connection failed
// 500: Server Error
// - internal_error: Internal Server Error
// - service_unavailable: Service unavailable
}
CommonRes
// Common response parameters
interface CommonRes {
data: {}; // An empty object when successful
error: AuthError | null; // error information, null if successful
}
SignUpReq
// User registration parameters (four-step verification process)
interface SignUpReq {
email?: string; // Email address (optional, choose either this or a phone number)
phone?: string; // Mobile number (optional, choose either this or a mailbox)
password: string; // Password (required)
username?: string; // Username (optional), length 5-24 characters, supports Chinese and English letters, digits, and special characters (only _- allowed). Chinese characters are not allowed.
nickname?: string; // Nickname (optional)
avatar_url?: string; // Avatar URL (optional)
gender?: "MALE" | "FEMALE"; // Gender (optional)
}
SignOutReq
// User logout parameters
interface SignOutReq {
options?: {
// Configuration options (optional)
redirectTo?: string; // Redirection address after log out
clearStorage?: boolean; // Whether to clear local storage (default true)
};
}
SignInWithPasswordReq
// Password login parameters
interface SignInWithPasswordReq {
username?: string; // Username (optional, selectable with mailbox or phone number), length 5-24 characters, supports Chinese and English letters, digits, and special characters (only _- allowed). Chinese characters are not allowed.
email?: string; // Email address (optional, choose either this, a username, or a phone number)
phone?: string; // Mobile number (optional, choose either this, a username, or a mailbox)
password: string; // Password (required)
is_encrypt?: boolean; // Encrypted or not; default false
}
SignInWithIdTokenReq
// ID-token login parameters
interface SignInWithIdTokenReq {
provider?: string; // Third-party platform flag (optional)
token: string; // Third-party platform identity token (required)
// Add a field.
provider?: string; // Third-party platform flag (optional, duplicate parameter with provider, reserved for compatibility)
}
SignInWithOtpReq
// OTP login parameters
interface SignInWithOtpReq {
email?: string; // Email address (optional, choose either this or a phone number)
phone?: string; // Mobile number (optional, choose either this or a mailbox)
}
SignInWithOAuthReq
// OAuth authorization parameter
interface SignInWithOAuthReq {
provider: string; // Third-party platform flag (required)
options?: {
// Configuration options (optional)
redirectTo?: string; // Callback URL, defaults to current page
skipBrowserRedirect?: boolean; // Whether to navigate to the authorization page, false by default
state?: string; // Status parameter, used for security verification, defaults to a random string (format: prd-{provider}-{random string})
queryParams?: Record<string, string>; // Additional query parameters, merged into the authorization URI
type?: "sign_in" | "bind_identity"; // Type (optional), defaults to 'sign_in', sign_in: sign in, bind_identity: bind identity
};
}
SetSessionReq
// Session setting parameters
interface SetSessionReq {
access_token: string; // Access token (required)
refresh_token: string; // Refresh token (required)
}
VerifyOAuthReq
// OAuth verification parameter
interface VerifyOAuthReq {
code?: string; // Authorization code (optional, default from URL parameter access)
state?: string; // Status parameter (optional, default from URL parameter access)
provider?: string; // Third-party platform flag (optional, default from session retrieval)
}
VerifyOtpReq
// OTP verification parameters
interface VerifyOtpReq {
type?:
| "sms"
| "phone_change"
| "signup"
| "invite"
| "magiclink"
| "recovery"
| "email_change";
email; // Validation type (optional)
email?: string; // Email address (optional, choose either this or a phone number)
phone?: string; // Mobile number (optional, choose either this or a mailbox)
token: string; // Captcha (required)
messageId: string; // ID corresponding to the verification code (required)
}
UpdateUserReq
// User information update parameter
interface UpdateUserReq {
email?: string; // Email address
phone?: string; // Phone number
username?: string; // Username (optional), length 5-24 characters, supports Chinese and English letters, digits, and special characters (only _- allowed). Chinese characters are not allowed.
description?: string; // Description (optional)
avatar_url?: string; // Avatar URL (optional)
nickname?: string; // Nickname (optional)
gender?: "MALE" | "FEMALE"; // Gender (optional)
}
LinkIdentityReq
// Identity source bind parameter
interface LinkIdentityReq {
provider: string; // Identity source flag (required)
}
UnlinkIdentityReq
// Identity source unbind parameter
interface UnlinkIdentityReq {
provider: string; // Identity source flag (required)
}
ReauthenticateReq
// Re-authenticate parameter
interface ReauthenticateReq {
// No input parameters, use the current logged-in user's info
}
ResendReq
// Resend verification code parameter
interface ResendReq {
email?: string; // Email address (optional, choose either this or a phone number)
phone?: string; // Mobile number (optional, choose either this or a mailbox)
type?: "signup" | "email_change" | "phone_change" | "sms"; // Type (optional)
}
ResendRes
// Resend verification code response parameter
interface ResendRes {
data: {
messageId?: string; // message ID (verification code ID)
};
error: AuthError | null; // error information, null if successful
}
SignInWithOtpRes
// OTP login response parameters
interface SignInWithOtpRes {
data: {
verifyOtp?: (params: {
token: string;
messageId?: string;
}) => Promise<SignInRes>; // Captcha callback function, supports messageId parameter
};
error: AuthError | null; // error information, null if successful
}
SignUpRes
// User registration response parameters
interface SignUpRes {
data: {
verifyOtp?: (params: {
token: string;
messageId?: string;
}) => Promise<SignInRes>; // Captcha callback function, supports messageId parameter
};
error: AuthError | null;
}
SignInOAuthRes
// OAuth authorization response parameters
interface SignInOAuthRes {
data: {
url?: string; // Authorization page URL
provider?: string; // Third-party platform flag
scopes?: string; // Authorization scope
};
error: AuthError | null; // error information, null if successful
}
LinkIdentityRes
// Identity source bind response parameter
interface LinkIdentityRes {
data: {
provider?: string; // Bound identity source flag
type?: "sign_in" | "bind_identity" | ""; // Type (optional), defaults to 'sign_in', sign_in: sign in, bind_identity: bind identity
};
error: AuthError | null; // error information, null if successful
}
Identity
interface Identity {
id: string; // Identity source flag
name: string; // Identity source name
picture: string; // Avatar URL
}
GetUserIdentitiesRes
// User identity source retrieval response parameter
interface GetUserIdentitiesRes {
data: {
identities?: Array<{
id: string; // Identity source flag
name: string; // Identity source name
picture: string; // Avatar URL
}>;
};
error: AuthError | null; // error information, null if successful
}
GetClaimsRes
// Declaration information acquisition response parameter
interface GetClaimsRes {
data: {
// token declaration info
claims?: {
iss: string; // issuer
sub: string; // subject
aud: string; // audience
exp: number; // expiration time
iat: number; // issued at
at_hash: string; // access token hash
name: string; // Name
picture?: string; // Avatar URL
email?: string; // Email
phone_number?: string; // Phone number
scope: string; // Authorization scope
project_id: string; // Project ID
provider?: string; // Third-party platform flag
provider_type?: string; // Third-party platform type
groups?: string[]; // User group
meta?: {
wxOpenId?: string;
wxUnionId?: string;
};
user_id: string; // uid
roles: string[]; // role
user_type: string; // Type of user
client_type: string; // Client type
is_system_admin: boolean; // System admin
};
// token header information
header?: {
alg: string; // Encryption algorithm
kid: string; // Token ID
};
signature?: string; // Token signature
};
error: AuthError | null; // error information, null if successful
}
ResetPasswordForOldReq
// Reset the password parameter with the old password
interface ResetPasswordForOldReq {
new_password: string; // New password (required)
old_password: string; // Old password (required)
}
DeleteMeReq
// Delete current user parameters
interface DeleteMeReq {
password: string; // User password (required)
}
SignInRes
// Login response parameters
interface SignInRes {
data: {
user?: User; // User information
session?: Session; // Session information
};
error: AuthError | null; // error information, null if successful
}
GetUserRes
// User information retrieval response parameter
interface GetUserRes {
data: {
user?: User; // User details
};
error: AuthError | null; // error information, null if successful
}
OnAuthStateChangeEvent
// Authentication status change event type
type OnAuthStateChangeEvent =
| "SIGNED_OUT" // User logged out
| "SIGNED_IN" // User login successful
| "INITIAL_SESSION" // Initial session established
| "PASSWORD_RECOVERY" // Password reset
| "TOKEN_REFRESHED" // Token refreshed
| "USER_UPDATED" // User information updated
| "BIND_IDENTITY"; // Identity source binding result
OnAuthStateChangeCallback
// Authentication status change callback function type
type OnAuthStateChangeCallback = (
event: OnAuthStateChangeEvent,
session: Session
) => void;
ResetPasswordForEmailRes
// Mailbox password reset response parameter
interface ResetPasswordForEmailRes {
data: {
updateUser?: (attributes: UpdateUserAttributes) => Promise<SignInRes>; // Captcha callback function, supports new password parameter
};
error: AuthError | null; // error information, null if successful
}
UpdateUserAttributes
// User attribute update parameter
interface UpdateUserAttributes {
nonce: string; // Captcha
password: string; // New password
}
ReauthenticateRes
// Re-authenticate response parameter
interface ReauthenticateRes {
data: {
updateUser?: (attributes: UpdateUserAttributes) => Promise<SignInRes>; // Captcha callback function, supports new password parameter
};
error: AuthError | null; // error information, null if successful
}