auth-web-cloudbase
CloudBase Web Authentication Quick Guide - Provides concise and practical Web frontend authentication solutions with multiple login methods and complete user management.
What this skill does
## Overview **Prerequisites**: CloudBase environment ID (`env`) **Prerequisites**: CloudBase environment Region (`region`) --- ## Core Capabilities **Use Case**: Web frontend projects using `@cloudbase/[email protected]+` for user authentication **Key Benefits**: Compatible with `supabase-js` API, supports phone, email, anonymous, username/password, and third-party login methods **`@cloudbase/js-sdk` cdn source**: `https://static.cloudbase.net/cloudbase-js-sdk/latest/cloudbase.full.js` ## Prerequisites - Automatically use `auth-tool-cloudbase` to get `publishable key` and configure login methods. - If `auth-tool-cloudbase` failed, let user go to `https://tcb.cloud.tencent.com/dev?envId={env}#/env/apikey` to get `publishable key` and `https://tcb.cloud.tencent.com/dev?envId={env}#/identity/login-manage` to set up login methods ## Quick Start ```js import cloudbase from '@cloudbase/js-sdk' const app = cloudbase.init({ env: `env`, // CloudBase environment ID region: `region`, // CloudBase environment Region, default 'ap-shanghai' accessKey: 'publishable key', // required, get from auth-tool-cloudbase auth: { detectSessionInUrl: true }, // required }) const auth = app.auth `` --- ## Login Methods **1. Phone OTP (Recommended)** - Automatically use `auth-tool-cloudbase` turn on `SMS Login` ```js const { data, error } = await auth.signInWithOtp({ phone: '13800138000' }) const { data: loginData, error: loginError } = await data.verifyOtp({ token:'123456' }) ``` **2. Email OTP** - Automatically use `auth-tool-cloudbase` turn on `Email Login` ```js const { data, error } = await auth.signInWithOtp({ email: '[email protected]' }) const { data: loginData, error: loginError } = await data.verifyOtp({ token: '654321' }) ``` **3. Password** ```js const { data, error } = await auth.signInWithPassword({ username: 'test_user', password: 'pass123' }) const { data, error } = await auth.signInWithPassword({ email: '[email protected]', password: 'pass123' }) const { data, error } = await auth.signInWithPassword({ phone: '13800138000', password: 'pass123' }) ``` **4. Registration (Smart: auto-login if exists)** - Only support email and phone otp registration - Automatically use `auth-tool-cloudbase` turn on `Email Login` or `SMS Login` ```js // Email Otp const { data, error } = await auth.signUp({ email: '[email protected]', nickname: 'User' }) const { data: loginData, error: loginError } = await data.verifyOtp({ token: '123456' }) // Phone Otp const { data, error } = await auth.signUp({ phone: '13800138000', nickname: 'User' }) const { data: loginData, error: loginError } = await data.verifyOtp({ token: '123456' }) ``` **5. Anonymous** - Automatically use `auth-tool-cloudbase` turn on `Anonymous Login` ```js const { data, error } = await auth.signInAnonymously() ``` **6. OAuth (Google/WeChat)** - Automatically use `auth-tool-cloudbase` turn on `Google Login` or `WeChat Login` ```js const { data, error } = await auth.signInWithOAuth({ provider: 'google' }) window.location.href = data.url // Auto-complete after callback ``` **7. Custom Ticket** ```js await auth.signInWithCustomTicket(async () => { const res = await fetch('/api/ticket') return (await res.json()).ticket }) ``` **8. Upgrade Anonymous** ```js const { data, error } = await auth.getSession() const { data: signUpData, error: signUpError} = await auth.signUp({ phone: '13800000000', anonymous_token: data.session.access_token, }) await signUpData.verifyOtp({ token: '123456' }) ``` --- ## User Management ```js // Sign out const { data, error } = await auth.signOut() // Get user const { data, error } = await auth.getUser() console.log(data.user.email, data.user.phone, data.user.user_metadata?.nickName) // Update user (except email, phone) const { data, error } = await auth.updateUser({ nickname: 'New Name', gender: 'MALE', avatar_url: 'url' }) // Update user (email or phone) const { data, error } = await auth.updateUser({ email: '[email protected]' }) const { data, error } = await data.verifyOtp({ email: "[email protected]", token: "123456" }); // Change password (logged in) const { data, error } = await auth.resetPasswordForOld({ old_password: 'old', new_password: 'new' }) // Reset password (forgot) const { data, error } = await auth.reauthenticate() const { data, error } = await data.updateUser({ nonce: '123456', password: 'new' }) // Link third-party const { data, error } = await auth.linkIdentity({ provider: 'google' }) // View/Unlink identities const { data, error } = await auth.getUserIdentities() const { data, error } = await auth.unlinkIdentity({ provider: data.identities[0].id }) // Delete account const { data, error } = await auth.deleteMe({ password: 'current' }) // Listen to state changes const { data, error } = auth.onAuthStateChange((event, session, info) => { // INITIAL_SESSION, SIGNED_IN, SIGNED_OUT, TOKEN_REFRESHED, USER_UPDATED, PASSWORD_RECOVERY, BIND_IDENTITY }) // Get access token const { data, error } = const { data, error } = await auth.getSession() fetch('/api/protected', { headers: { Authorization: `Bearer ${data.session?.access_token}` } }) // Refresh user const { data, error } = await auth.refreshUser() ``` --- ## User Type ```ts declare type User = { id: any aud: string role: string[] email: any email_confirmed_at: string phone: any phone_confirmed_at: string confirmed_at: string last_sign_in_at: string app_metadata: { provider: any providers: any[] } user_metadata: { name: any picture: any username: any gender: any locale: any uid: any nickName: any avatarUrl: any location: any hasPassword: any } identities: any created_at: string updated_at: string is_anonymous: boolean } ``` --- ## Complete Example ```js class PhoneLoginPage { async sendCode() { const phone = document.getElementById('phone').value if (!/^1[3-9]\d{9}$/.test(phone)) return alert('Invalid phone') const { data, error } = await auth.signInWithOtp({ phone }) if (error) return alert('Send failed: ' + error.message) this.verifyFunction = data.verify document.getElementById('codeSection').style.display = 'block' this.startCountdown(60) } async verifyCode() { const code = document.getElementById('code').value if (!code) return alert('Enter code') const { data, error } = await this.verifyFunction(code) if (error) return alert('Verification failed: ' + error.message) console.log('Login successful:', data.user) window.location.href = '/dashboard' } startCountdown(seconds) { let countdown = seconds const btn = document.getElementById('resendBtn') btn.disabled = true const timer = setInterval(() => { countdown-- btn.innerText = `Resend in ${countdown}s` if (countdown <= 0) { clearInterval(timer) btn.disabled = false btn.innerText = 'Resend' } }, 1000) } } ``` --- ## WeChat Mini Program ```js // Silent login with OpenID const { data, error } = await auth.signInWithOpenId() // WeChat Cloud mode (default) const { data, error } = await auth.signInWithOpenId({ useWxCloud: false }) // HTTP mode // Phone authorization login const { data, error } = await auth.signInWithPhoneAuth({ phoneCode: 'xxx' }) ``` ---
Related in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.