### Set Session Implementation
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Example of manually setting a session using existing access and refresh tokens.
```javascript
const { data, error } = await auth.setSession({
access_token: "your_access_token_here",
refresh_token: "your_refresh_token_here",
});
if (error) {
console.error("会话设置失败:", error.message);
} else {
console.log("会话设置成功");
console.log("用户信息:", data.user);
console.log("会话信息:", data.session);
}
```
--------------------------------
### Implement Registration Form UI
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
This example shows how to manage the registration flow within a web page, including toggling visibility between the registration and verification sections.
```javascript
let signUpVerify = null;
async function startRegistration(email, password) {
const { data, error } = await auth.signUp({
email: email,
password: password,
});
if (error) {
console.error("发送验证码失败:", error.message);
document.getElementById("error").innerText =
"发送验证码失败: " + error.message;
return false;
} else {
console.log("验证码已发送");
signUpVerify = data.verifyOtp;
// 显示验证码输入框
document.getElementById("verificationSection").style.display = "block";
document.getElementById("registrationSection").style.display = "none";
// 更新提示信息,说明智能判断逻辑
document.getElementById("verificationHint").innerText =
"请输入验证码,系统将自动判断您是注册新用户还是登录现有账户";
return true;
}
}
async function completeRegistration(verificationCode) {
if (!signUpVerify) {
console.error("注册流程未开始");
return false;
}
const { data, error } = await signUpVerify({ token: verificationCode });
if (error) {
console.error("验证失败:", error.message);
document.getElementById("error").innerText = "验证失败: " + error.message;
return false;
} else {
// 智能判断结果反馈
if (data.user?.email) {
console.log("智能注册并登录成功");
document.getElementById("success").innerText = data.user?.created_at
? "新用户注册成功,欢迎加入!"
: "登录成功,欢迎回来!";
}
// 自动跳转到首页
setTimeout(() => {
window.location.href = "/dashboard";
}, 2000);
return true;
}
}
// 注册表单提交
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);
});
// 验证码表单提交
document
.getElementById("verificationForm")
.addEventListener("submit", async (e) => {
e.preventDefault();
const code = document.getElementById("verificationCode").value;
await completeRegistration(code);
});
```
--------------------------------
### Account Deletion with Confirmation
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
This example shows how to implement an account deletion flow that includes a user confirmation step before proceeding with the deletion. It also handles specific error codes.
```APIDOC
## POST /api/users/delete (with confirmation)
### Description
Initiates the account deletion process after user confirmation and handles specific error scenarios.
### Method
POST
### Endpoint
/api/users/delete
### Parameters
#### Request Body
- **password** (string) - Required - The user's current password.
### Request Example
```javascript
async function deleteAccount(password) {
if (!confirm("Are you sure you want to delete your account? This action is irreversible and 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 try again.");
break;
case "user_not_found":
alert("User not found.");
break;
default:
alert("Deletion failed: " + error.message);
}
return false;
} else {
alert("Account deleted successfully");
return true;
}
}
document.getElementById("deleteAccountForm").addEventListener("submit", async (e) => {
e.preventDefault();
const password = document.getElementById("password").value;
const success = await deleteAccount(password);
if (success) {
window.location.href = "/";
}
});
```
### Response
#### Success Response (200)
- **message** (string) - Indicates successful account deletion.
#### Response Example
```json
{
"message": "Account deleted successfully"
}
```
```
--------------------------------
### User Identity Management
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Examples for retrieving, displaying, and checking user-bound identity sources.
```APIDOC
## Get User Identities
### Description
Retrieves a list of identity sources currently bound to the user.
### Method
GET
### Endpoint
/auth/getUserIdentities
### Response
#### Success Response (200)
- **identities** (array) - A list of identity objects, each containing `id`, `name`, `provider`, `provider_user_id`, and `created_at`.
### Request Example
```javascript
const { data, error } = await auth.getUserIdentities();
if (error) {
console.error("Failed to get identities:", error.message);
} else if (data.identities) {
console.log("User bound identities:", data.identities);
data.identities.forEach((identity) => {
console.log(
`- ${identity.name} (${identity.provider}): ${identity.provider_user_id}`
);
console.log(
` Bound at: ${new Date(identity.created_at).toLocaleString()}`
);
});
} else {
console.log("User has not bound any identities");
}
```
## Load User Identities for Display
### Description
Loads and displays user-bound identities in a specified HTML container, with options to unbind.
### Method
GET (Implicitly called on load)
### Endpoint
(Client-side function, interacts with /auth/getUserIdentities)
### Request Example
```javascript
async function loadUserIdentities() {
const { data, error } = await auth.getUserIdentities();
if (error) {
document.getElementById("error").innerText = "Failed to get identities: " + 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 = `
${identity.name}
Platform: ${identity.provider}
Bound at: ${new Date(identity.created_at).toLocaleString()}
`;
container.appendChild(identityElement);
});
} else {
container.innerHTML = "You have not bound any third-party accounts yet
";
}
}
// Call on page load
loadUserIdentities();
```
## Check if a Specific Provider is Bound
### Description
Checks if the user has bound a specific identity provider.
### Method
GET
### Endpoint
/auth/getUserIdentities (used internally)
### Parameters
#### Query Parameters
- **provider** (string) - Required - The identifier of the identity provider to check (e.g., "wechat", "google").
### Request Example
```javascript
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 WeChat is bound
const isWechatBound = await isProviderBound("wechat");
if (isWechatBound) {
console.log("WeChat account is bound");
document.getElementById("bindWechatBtn").style.display = "none";
} else {
console.log("WeChat account is not bound");
document.getElementById("bindWechatBtn").style.display = "block";
}
```
```
--------------------------------
### Implement Password Reset UI Flow
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
A complete example showing how to manage state and DOM updates for a multi-step password reset form.
```javascript
let resetPasswordVerify = null;
async function startPasswordReset(email) {
const { data, error } = await auth.resetPasswordForEmail(email);
if (error) {
document.getElementById("error").innerText =
"发送验证码失败: " + error.message;
return false;
} else {
resetPasswordVerify = data.updateUser;
// 显示验证码输入框
document.getElementById("verificationSection").style.display = "block";
document.getElementById("emailSection").style.display = "none";
document.getElementById("status").innerText =
"验证码已发送到您的邮箱,请查收";
return true;
}
}
async function completePasswordReset(code, newPassword) {
if (!resetPasswordVerify) {
alert("请先发送验证码");
return false;
}
const { data, error } = await resetPasswordVerify({
nonce: code,
password: newPassword,
});
if (error) {
document.getElementById("error").innerText =
"重置密码失败: " + error.message;
return false;
} else {
document.getElementById("success").innerText = "密码重置成功,已自动登录";
// 跳转到首页
setTimeout(() => {
window.location.href = "/dashboard";
}, 2000);
return true;
}
}
// 表单提交事件
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);
}
});
```
--------------------------------
### Username, Email, and Phone Login
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Examples demonstrating how to log in using username, email, or phone number with a password. Includes comprehensive error handling for various login failure scenarios.
```APIDOC
## Username Login Example
### Description
Logs in a user using their username and password.
### Request Example
```javascript
const { data, error } = await auth.signInWithPassword({
username: "testuser",
password: "password123",
});
if (error) {
console.error("登录失败:", error.message);
} else {
console.log("登录成功,用户信息:", data.user);
console.log("会话信息:", data.session);
}
```
## Email Login Example
### Description
Logs in a user using their email address and password.
### Request Example
```javascript
const { data, error } = await auth.signInWithPassword({
email: "user@example.com",
password: "mypassword",
});
if (error) {
console.error("登录失败:", error.message);
} else {
console.log("登录成功,用户ID:", data.user?.id);
}
```
## Phone Number Login Example
### Description
Logs in a user using their phone number and password.
### Request Example
```javascript
const { data, error } = await auth.signInWithPassword({
phone: "13800138000",
password: "securepassword",
});
if (error) {
console.error("登录失败:", error.code, error.message);
} else {
console.log("登录成功,用户ID:", data.user?.id);
}
```
## Error Handling Example
### Description
Demonstrates comprehensive error handling for login attempts, covering various error codes like user not found, invalid password, and network issues.
### Request Example
```javascript
try {
const { data, error } = await auth.signInWithPassword({
username: "wronguser",
password: "wrongpassword",
});
if (error) {
// 根据常见错误代码进行完整错误处理
switch (error.code) {
case "not_found":
console.error("用户不存在,请检查用户名/邮箱/手机号是否正确");
break;
case "password_not_set":
console.error("当前用户未设置密码,请使用验证码登录或第三方登录方式");
break;
case "invalid_password":
console.error("密码不正确,请重新输入");
break;
case "user_pending":
console.error("该用户未激活,请联系管理员激活账户");
break;
case "user_blocked":
console.error("该用户被停用,请联系管理员");
break;
case "invalid_status":
console.error("您已经超过了密码最大重试次数,请稍后重试");
break;
case "invalid_two_factor":
console.error("二次验证码不匹配或已过时,请重新获取");
break;
case "unreachable":
console.error("网络连接失败,请检查网络设置后重试");
break;
default:
console.error("登录失败:", error.message);
}
} else {
console.log("登录成功");
}
} catch (error) {
console.error("网络错误:", error);
}
```
```
--------------------------------
### Custom Ticket Authentication
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Demonstrates how to sign in using a custom authentication ticket. Includes examples for basic usage, asynchronous ticket retrieval, and error handling.
```APIDOC
## signInWithCustomTicket
### Description
Authenticates a user using a custom-generated ticket. This function is useful for integrating with existing authentication systems.
### Method
`auth.signInWithCustomTicket(getTickFn: () => Promise | string): Promise<{ data: SignInResData | null, error: AuthError | null }> `
### Parameters
#### Request Body
- **getTickFn** (function or string) - Required - A function that returns a Promise resolving to the custom ticket string, or the ticket string directly.
### Request Example
```javascript
// Basic Usage
const getTickFn = () => Promise.resolve("custom_ticket_123456");
const { data, error } = await auth.signInWithCustomTicket(getTickFn);
if (error) {
console.error("Custom ticket sign-in failed:", error.message);
} else {
console.log("Custom ticket sign-in successful, user info:", data.user);
console.log("Session info:", data.session);
}
```
```javascript
// Asynchronous Ticket Retrieval
const getTickFn = async () => {
// Simulate fetching ticket from a 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 ticket sign-in failed:", error.message);
} else {
console.log("Custom ticket sign-in successful");
}
```
### Response
#### Success Response (200)
- **data** (SignInResData) - User and session information upon successful sign-in.
- **error** (null) - Indicates no error occurred.
#### Error Response
- **error** (AuthError) - Details about the authentication error.
### Error Handling Example
```javascript
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("Ticket is invalid or expired, please re-fetch.");
break;
case "ticket_required":
console.error("Custom login ticket is required.");
break;
case "network_error":
console.error("Network connection failed, please check your network settings and retry.");
break;
default:
console.error("Sign-in failed:", error.message);
}
} else {
console.log("Sign-in successful");
}
} catch (error) {
console.error("Network error:", error);
}
```
```
--------------------------------
### Account Deletion with Attempt Limiting
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
This example implements an account deletion manager that limits the number of deletion attempts to prevent brute-force attacks and provides feedback on remaining attempts.
```APIDOC
## POST /api/users/delete (with attempt limiting)
### Description
Manages account deletion attempts, limiting the number of retries and providing feedback on remaining attempts.
### Method
POST
### Endpoint
/api/users/delete
### Parameters
#### Request Body
- **password** (string) - Required - The user's current password.
### Request Example
```javascript
class AccountDeletionManager {
constructor() {
this.deletionAttempts = 0;
this.maxAttempts = 3;
}
async deleteAccount(password) {
if (this.deletionAttempts >= this.maxAttempts) {
alert("Too many deletion attempts. Please 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("Deletion failed: " + error.message);
}
return false;
} else {
alert("Account deleted successfully");
this.deletionAttempts = 0;
return true;
}
}
resetAttempts() {
this.deletionAttempts = 0;
}
}
const deletionManager = new AccountDeletionManager();
document.getElementById("deleteBtn").addEventListener("click", async () => {
const password = prompt("Please enter your password to confirm account deletion:");
if (password) {
await deletionManager.deleteAccount(password);
}
});
```
### Response
#### Success Response (200)
- **message** (string) - Indicates successful account deletion.
#### Response Example
```json
{
"message": "Account deleted successfully"
}
```
```
--------------------------------
### Manage Global Authentication State
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Example of using an AuthManager instance to listen for authentication state changes in a React component.
```javascript
}
destroy() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
}
// 创建全局认证管理器
const authManager = new AuthManager();
// 在不同页面中使用
function PageA() {
const [user, setUser] = useState(null);
useEffect(() => {
authManager.addListener(setUser);
return () => authManager.removeListener(setUser);
}, []);
return {user ? `欢迎,${user.email}` : "请登录"}
;
}
```
--------------------------------
### Handle Password Reset Errors
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Example of using a switch statement to handle specific error codes returned during the password reset process.
```javascript
try {
const { data, error } = await auth.resetPasswordForEmail("invalid-email");
if (error) {
switch (error.code) {
case "invalid_email":
console.error("邮箱格式错误,请检查邮箱格式");
break;
case "user_not_found":
console.error("用户不存在,请检查邮箱是否正确");
break;
case "email_not_verified":
console.error("邮箱未验证,请先验证邮箱");
break;
case "rate_limit_exceeded":
console.error("发送频率过高,请稍后再试");
break;
default:
console.error("发送验证码失败:", error.message);
}
}
} catch (error) {
console.error("网络错误:", error);
}
```
--------------------------------
### GET /auth/getUser
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Retrieves the detailed information of the currently logged-in user.
```APIDOC
## GET /auth/getUser
### Description
Retrieves the detailed information of the currently logged-in user, including identity information, metadata, and permission status. This is useful for profile display and permission verification.
### Method
GET
### Response
#### Success Response (200)
- **data** (GetUserResData) - The user's detailed information.
- **user** (User) - Object containing identity, metadata, and permissions.
- **error** (AuthError | null) - Error information, null if successful.
```
--------------------------------
### Implement Email and Phone Registration
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
These snippets demonstrate the two-step registration process: initiating sign-up to send a verification code, followed by verifying the OTP to complete the authentication.
```javascript
// 第一步:发送邮箱验证码并存储 verificationInfo
const { data, error } = await auth.signUp({
email: "newuser@example.com",
password: "securePassword123",
username: "newuser",
});
if (error) {
console.error("发送验证码失败:", error.message);
} else {
console.log("验证码已发送到邮箱,等待用户输入...");
// 第二步:等待用户输入验证码(通过 Promise 包装用户输入事件)
const verificationCode = "123456"; // 用户输入的验证码
// 第三步:智能验证流程(自动判断用户存在性)
const { data: loginData, error: loginError } = await data.verifyOtp({
token: verificationCode,
});
if (loginError) {
console.error("验证失败:", loginError.message);
} else {
// 第四步:自动完成注册或登录
console.log("操作成功,用户信息:", loginData.user);
console.log("会话信息:", loginData.session);
console.log(
"系统已自动判断:",
loginData.user?.email ? "新用户注册并登录" : "现有用户直接登录"
);
}
}
```
```javascript
// 第一步:发送手机验证码
const { data, error } = await auth.signUp({
phone: "13800138000",
password: "mypassword",
});
if (error) {
console.error("发送验证码失败:", error.message);
} else {
console.log("验证码已发送到手机,等待用户输入...");
// 第二步:等待用户输入验证码
const verificationCode = "123456"; // 用户输入的验证码
// 第三步:智能验证流程(自动判断用户存在性)
const { data: loginData, error: loginError } = await data.verifyOtp({
token: verificationCode,
});
if (loginError) {
console.error("操作失败:", loginError.message);
} else {
// 系统自动判断:如果用户已存在则直接登录,如果不存在则注册新用户
if (loginData.user?.phone) {
console.log("现有用户直接登录成功,用户信息:", loginData.user);
} else {
console.log("新用户注册并登录成功,用户ID:", loginData.user?.id);
}
console.log("会话状态:", loginData.session ? "已登录" : "未登录");
}
}
```
--------------------------------
### Execute Full OAuth Login Flow
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Demonstrates the complete lifecycle from generating an authorization link to handling the callback and verifying the result.
```javascript
// 第一步:生成授权链接
const { data, error } = await auth.signInWithOAuth({
provider: "wechat",
options: {
redirectTo: "https://example.com/oauth-callback",
state: "wx_oauth_20241204",
},
});
if (error) {
console.error("获取授权链接失败:", error.message);
return;
}
// 第二步:跳转到授权页面
window.location.href = data.url;
// 在回调页面(oauth-callback)中:
// 第三步:验证授权结果
const { data: verifyData, error: verifyError } = await auth.verifyOAuth();
if (verifyError) {
console.error("授权验证失败:", verifyError.message);
document.getElementById("error").innerText = verifyError.message;
} else {
console.log("授权成功,用户已登录");
window.location.href = "/dashboard";
}
```
--------------------------------
### GET /getUserIdentities
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Retrieves information about all third-party identity providers currently bound to the user. This requires the user to be logged in.
```APIDOC
## GET /getUserIdentities
### Description
Fetches all identity providers associated with the current logged-in user.
### Method
GET
### Endpoint
/getUserIdentities
### Parameters
No parameters required.
### Response
#### Success Response (200)
- **data** (GetUserIdentitiesRes) - An object containing the list of identities.
- **identities** (Array) - A list of identity provider objects.
- **platform** (string) - The platform identifier (e.g., 'google', 'facebook').
- **identityId** (string) - The unique ID of the identity provider.
- **boundAt** (string) - The timestamp when the identity was bound.
- **error** (AuthError | null) - An error object if the request failed, otherwise null.
#### Response Example
```json
{
"data": {
"identities": [
{
"platform": "google",
"identityId": "google-12345",
"boundAt": "2023-10-27T10:00:00Z"
}
]
},
"error": null
}
```
```
--------------------------------
### GET /auth/getUser
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Retrieves the current authenticated user's profile information, including metadata, email, and registration details.
```APIDOC
## GET /auth/getUser
### Description
Retrieves the current authenticated user's profile information. This is used for displaying user data, checking permissions, or validating session status.
### Method
GET
### Endpoint
auth.getUser()
### Response
#### Success Response (200)
- **data** (Object) - Contains the user object.
- **user** (Object) - The user profile including id, email, phone, and user_metadata (username, nickName, avatarUrl).
- **error** (null) - No error occurred.
#### Response Example
{
"data": {
"user": {
"id": "user_123",
"email": "user@example.com",
"user_metadata": {
"username": "johndoe",
"nickName": "John"
}
}
},
"error": null
}
```
--------------------------------
### Initialize CloudBase SDK
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Configure the SDK with your environment ID and Publishable Key. The detectSessionInUrl option is recommended for OAuth flows.
```javascript
import cloudbase from "@cloudbase/js-sdk";
// 初始化
const app = cloudbase.init({
env: "your-env-id", // 替换为您的环境ID
region: "ap-shanghai", // 地域,默认为上海
accessKey: "", // 填入生成的 Publishable Key,
auth: {
detectSessionInUrl: true, // 可选:自动检测 URL 中的 OAuth 参数,适用于signInWithOAuth、linkIdentity
},
});
const auth = app.auth;
```
--------------------------------
### Get Claims API
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Retrieves claims information from the current access token for debugging and permission checks. This method requires the user to be logged in.
```APIDOC
## getClaims
### Description
Retrieves claims information from the current access token for debugging and permission checks. It parses the JWT claims and returns the header, claims, and signature of the token. This is useful for debugging token information, checking permissions, and verifying token status. Requires the user to be logged in.
### Method
GET
### Endpoint
/auth/getClaims
### Parameters
No parameters.
### Request Body
None
### Response
#### Success Response (200)
- **data** (GetClaimsRes) - The response data containing token claims and header.
- **claims** (Record) - Token claims information.
- **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, optional) - avatar URL
- **email** (string, optional) - email
- **phone_number** (string, optional) - phone number
- **scope** (string) - scope
- **project_id** (string) - project ID
- **provider** (string, optional) - third-party platform identifier
- **provider_type** (string, optional) - third-party platform type
- **groups** (string[], optional) - user groups
- **meta** (Record, optional) - additional metadata
- **wxOpenId** (string, optional)
- **wxUnionId** (string, optional)
- **user_id** (string) - user ID
- **roles** (string[]) - roles
- **user_type** (string) - user type
- **client_type** (string) - client type
- **is_system_admin** (boolean) - is system administrator
- **header** (Record) - Token header information.
- **alg** (string) - encryption algorithm
- **kid** (string) - token ID
- **signature** (string) - Token signature
- **error** (AuthError | null) - Error information, null on success.
### Request Example
```javascript
const { data, error } = await auth.getClaims();
if (error) {
console.error("Failed to get claims:", error.message);
} else {
console.log("Token claims:", data.claims);
console.log("Token header:", data.header);
console.log("Token signature:", data.signature);
// Parse user information
if (data.claims) {
console.log("User ID:", data.claims.sub);
console.log("Expiration time:", new Date(data.claims.exp * 1000).toLocaleString());
console.log("Issued at:", new Date(data.claims.iat * 1000).toLocaleString());
console.log("User roles:", data.claims.role);
}
}
```
### Response Example
```json
{
"data": {
"claims": {
"iss": "https://example.com",
"sub": "user123",
"aud": "app123",
"exp": 1678886400,
"iat": 1678800000,
"at_hash": "some_hash",
"name": "John Doe",
"email": "john.doe@example.com",
"scope": "openid profile",
"project_id": "proj123",
"user_id": "user123",
"roles": ["user"],
"user_type": "customer",
"client_type": "web",
"is_system_admin": false
},
"header": {
"alg": "RS256",
"kid": "key123"
},
"signature": "some_signature"
},
"error": null
}
```
```
```APIDOC
## checkTokenPermissions
### Description
This function checks the permissions associated with the current access token by retrieving its claims. It verifies if the token has expired and checks for specific user roles.
### Method
GET (implicitly via `auth.getClaims()`)
### Endpoint
N/A (This is a client-side function using the `getClaims` API)
### Parameters
None
### Request Body
None
### Response
- **boolean**: Returns `true` if the user has permissions, `false` otherwise.
### Request Example
```javascript
async function checkTokenPermissions() {
const { data, error } = await auth.getClaims();
if (error) {
console.error("Failed to get token info:", 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 has expired");
return false;
}
// Check user roles
if (claims.role === "admin") {
console.log("Administrator privileges");
return true;
} else if (claims.role === "user") {
console.log("Regular user privileges");
return true;
} else {
console.error("Unknown user role");
return false;
}
}
return false;
}
// Check permissions and perform actions
if (await checkTokenPermissions()) {
console.log("Authorized, proceeding...");
} else {
console.log("Unauthorized, operation denied");
}
```
```
```APIDOC
## checkTokenExpiration
### Description
This function checks the expiration status of the current access token by retrieving its claims. It warns if the token is nearing expiration and handles automatic session refresh.
### Method
GET (implicitly via `auth.getClaims()`)
### Endpoint
N/A (This is a client-side function using the `getClaims` API)
### Parameters
None
### Request Body
None
### Response
- **boolean**: Returns `true` if the token is valid or nearing expiration, `false` if it has expired.
### Request Example
```javascript
async function checkTokenExpiration() {
const { data, error } = await auth.getClaims();
if (error) {
console.error("Token check failed:", 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 has expired, please log in again");
return false;
} else if (timeLeft < 300) {
console.warn(
`Token will expire in ${minutesLeft}m${secondsLeft}s, refreshing recommended`
);
return true;
} else {
console.log(`Token is valid, time remaining: ${minutesLeft}m${secondsLeft}s`);
return true;
}
}
}
return false;
}
// Periodically check token status
setInterval(async () => {
const isValid = await checkTokenExpiration();
if (!isValid) {
console.log("Token expired, auto-refreshing...");
await auth.refreshSession();
}
}, 60000); // Check every minute
```
```
--------------------------------
### Sign Up New User
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Asynchronously signs up a new user with provided parameters, utilizing a smart registration and login flow. This method is intended for creating new accounts and automatically logging them in.
```typescript
async signUp(params: SignUpReq): Promise
```
--------------------------------
### Manual OAuth Callback Handling
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Demonstrates manual handling of OAuth callbacks by parsing URL parameters and verifying the authorization code.
```javascript
// 初始化
const app = cloudbase.init({
env: "your-env-id", // 替换为您的环境ID
region: "ap-shanghai", // 地域,默认为上海
accessKey: "", // 填入生成的 Publishable Key,
});
class OAuthManager {
constructor() {
this.initEventListeners();
this.provider = "oauth";
}
// 初始化事件监听器
initEventListeners() {
// OAuth登录按钮点击事件
document.getElementById("oauth-login-btn").addEventListener("click", () => {
this.startOAuth();
});
// 页面加载时检查是否有OAuth授权回调
document.addEventListener("DOMContentLoaded", () => {
this.checkOAuthCallback();
});
}
// 开始OAuth授权流程
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授权链接生成成功,正在跳转...");
// 最佳实践:使用当前窗口跳转,保持用户体验
window.location.href = data.url;
}
} catch (error) {
this.handleOAuthError(error);
} finally {
this.showLoading(false);
}
}
// 检查OAuth授权回调
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授权回调,正在验证...");
await this.verifyOAuth(code, state);
}
}
// 验证OAuth授权
```
--------------------------------
### OAuth Login Best Practices
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Implements a robust OAuth flow with authentication state listeners and UI loading states.
```javascript
// OAuth登录最佳实践 - 完整的UI交互流程
// 初始化
const app = cloudbase.init({
env: "your-env-id", // 替换为您的环境ID
region: "ap-shanghai", // 地域,默认为上海
accessKey: "", // 填入生成的 Publishable Key,
auth: {
detectSessionInUrl: true, // 可选:自动检测 URL 中的 OAuth 参数,适用于signInWithOAuth、linkIdentity
},
});
// 修改认证状态变化监听器,添加浮窗显示
async function setupAuthStateChangeListener() {
try {
if (!app.auth) return;
// 订阅认证状态变化事件
const { data } = await app.auth.onAuthStateChange(
(event, session, info) => {
console.log("认证状态变化:", { event, session, info });
switch (event) {
case "SIGNED_IN":
if (session && session.user) {
console.log("登录成功!");
}
break;
default:
console.log("未知认证事件:", event);
}
}
);
console.log("认证状态变化监听器已设置");
} catch (error) {
console.error("设置认证状态变化监听器失败:", error);
}
}
class OAuthManager {
constructor() {
this.initEventListeners();
this.provider = "oauth";
}
// 初始化事件监听器
initEventListeners() {
// OAuth登录按钮点击事件
document.getElementById("oauth-login-btn").addEventListener("click", () => {
this.startOAuth();
});
}
// 开始OAuth授权流程
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授权链接生成成功,正在跳转...");
// 最佳实践:使用当前窗口跳转,保持用户体验
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();
// 初始化OAuth登录管理器
const oAuthManager = new OAuthManager();
```
--------------------------------
### Get User Identities - JavaScript
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Retrieves and logs the identity providers bound to the current user. Handles cases where no identities are bound or an error occurs.
```javascript
const { data, error } = await auth.getUserIdentities();
if (error) {
console.error("获取身份源失败:", error.message);
} else if (data.identities) {
console.log("用户绑定的身份源:", data.identities);
data.identities.forEach((identity) => {
console.log(
`- ${identity.name} (${identity.provider}): ${identity.provider_user_id}`
);
console.log(
` 绑定时间: ${new Date(identity.created_at).toLocaleString()}`
);
});
} else {
console.log("用户未绑定任何身份源");
}
```
--------------------------------
### GET /auth/getSession
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Retrieves the current user's session information. Used to check if a user is logged in, validate session status, or handle session-related errors.
```APIDOC
## GET /auth/getSession
### Description
Retrieves the current session data. This is used to verify if a user is authenticated and to access user metadata or tokens.
### Method
GET
### Endpoint
auth.getSession()
### Response
#### Success Response (200)
- **data** (object) - Contains session and user information.
- **error** (null) - Null when the request is successful.
#### Response Example
{
"data": {
"session": {
"access_token": "eyJ...",
"expires_in": 3600,
"user": { "id": "123", "name": "John Doe" }
}
},
"error": null
}
```
--------------------------------
### SignInWithOtpReq
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Parameters for initiating an OTP-based sign-in process.
```APIDOC
## SignInWithOtpReq
### Request Body
- **email** (string) - Optional - Email address (mutually exclusive with phone).
- **phone** (string) - Optional - Phone number (mutually exclusive with email).
- **options** (object) - Optional - Configuration options.
- **shouldCreateUser** (boolean) - Optional - Whether to create a user if they do not exist (default: true).
```
--------------------------------
### Start Countdown Timer
Source: https://docs.cloudbase.net/api-reference/webv3/authentication
Initiates and manages a countdown timer, typically used for resending verification codes. It disables the button during the countdown and re-enables it when the timer finishes.
```javascript
startCountdown(seconds) {
let countdown = seconds;
const btn = document.getElementById("resendBtn");
const originalText = btn.innerText;
btn.disabled = true;
const timer = setInterval(() => {
countdown--;
btn.innerText = `${countdown}秒后可重发`;
if (countdown <= 0) {
clearInterval(timer);
btn.disabled = false;
btn.innerText = originalText;
}
}, 1000);
}
```