Authentication
Este conteúdo não está disponível em sua língua ainda.
Overview
Section titled “Overview”The client.auth module handles user authentication, token management, and session persistence. Once a user signs in, all subsequent data requests automatically include the JWT.
The SDK persists sessions to localStorage by default and automatically refreshes tokens before they expire.
Email / Password
Section titled “Email / Password”Sign In
Section titled “Sign In”const { user, accessToken, refreshToken } = await client.auth.signInWithEmail( "user@example.com", "password");console.log(user.uid, user.email);Sign Up
Section titled “Sign Up”const { user } = await client.auth.signUp( "user@example.com", "password", "Jane Doe" // optional displayName);OAuth Providers
Section titled “OAuth Providers”The SDK includes dedicated methods for popular OAuth providers, plus a generic signInWithOAuth() for any custom provider.
Supports three invocation styles:
// ID-token flow (One Tap / Sign In With Google button)await client.auth.signInWithGoogle({ idToken: googleIdToken });
// Access-token flow (popup)await client.auth.signInWithGoogle({ accessToken: googleAccessToken });
// Authorization code flow (most secure, server-side exchange)await client.auth.signInWithGoogle({ code: authCode, redirectUri: "https://..." });Other Providers
Section titled “Other Providers”Each provider follows the authorization code flow with (code, redirectUri):
await client.auth.signInWithGitHub(code, redirectUri);await client.auth.signInWithMicrosoft(code, redirectUri);await client.auth.signInWithFacebook(code, redirectUri);await client.auth.signInWithLinkedin(code, redirectUri);await client.auth.signInWithDiscord(code, redirectUri);await client.auth.signInWithGitLab(code, redirectUri);await client.auth.signInWithBitbucket(code, redirectUri);await client.auth.signInWithSlack(code, redirectUri);await client.auth.signInWithSpotify(code, redirectUri);Apple and Twitter require additional parameters:
// Apple — optional user info from first sign-inawait client.auth.signInWithApple(code, redirectUri, { name: { firstName: "Jane", lastName: "Doe" }, email: "jane@example.com"});
// Twitter — requires PKCE code verifierawait client.auth.signInWithTwitter(code, redirectUri, codeVerifier);Generic OAuth
Section titled “Generic OAuth”For any provider registered on the backend:
await client.auth.signInWithOAuth("custom-provider", { code: authCode, redirectUri: "https://myapp.com/callback"});Sign Out
Section titled “Sign Out”await client.auth.signOut();This revokes the refresh token on the server, clears the local session, and emits a SIGNED_OUT event.
Session Management
Section titled “Session Management”Get Current Session
Section titled “Get Current Session”const session = client.auth.getSession();// { accessToken, refreshToken, expiresAt, user } | nullGet Current User (Server-Verified)
Section titled “Get Current User (Server-Verified)”const user = await client.auth.getUser();// Fetches the user from the backend (GET /auth/me)Update User Profile
Section titled “Update User Profile”const updatedUser = await client.auth.updateUser({ displayName: "Jane Doe", photoURL: "https://example.com/avatar.jpg"});Refresh Token
Section titled “Refresh Token”Token refresh happens automatically, but you can trigger it manually:
const session = await client.auth.refreshSession();Auth State Listener
Section titled “Auth State Listener”React to authentication changes across your application:
const unsubscribe = client.auth.onAuthStateChange((event, session) => { // event: "SIGNED_IN" | "SIGNED_OUT" | "TOKEN_REFRESHED" | "USER_UPDATED" console.log("Auth event:", event); console.log("Session:", session?.user?.email);});
// Stop listeningunsubscribe();Password Management
Section titled “Password Management”Forgot Password
Section titled “Forgot Password”const { success, message } = await client.auth.resetPasswordForEmail( "user@example.com");Reset Password (with Token)
Section titled “Reset Password (with Token)”const { success, message } = await client.auth.resetPassword( resetToken, "newSecurePassword");Change Password (Authenticated)
Section titled “Change Password (Authenticated)”const { success, message } = await client.auth.changePassword( "oldPassword", "newPassword");Email Verification
Section titled “Email Verification”// Send verification email to the current userawait client.auth.sendVerificationEmail();
// Verify with the token from the email linkawait client.auth.verifyEmail(token);Session Management (Multi-Device)
Section titled “Session Management (Multi-Device)”// List all active sessionsconst sessions = await client.auth.getSessions();
// Revoke a specific sessionawait client.auth.revokeSession(sessionId);
// Revoke ALL sessions (logs out everywhere)await client.auth.revokeAllSessions();Auth Configuration
Section titled “Auth Configuration”Query the backend’s authentication configuration:
const config = await client.auth.getAuthConfig();// {// needsSetup: boolean,// registrationEnabled: boolean,// emailServiceEnabled?: boolean,// passwordReset?: boolean,// emailVerification?: boolean,// enabledProviders: string[]// }Custom Session Storage
Section titled “Custom Session Storage”By default, sessions are stored in localStorage. You can customize this with the auth option:
import { createRebaseClient, createCookieStorage } from "@rebasepro/client";
// Use cookies instead of localStorageconst client = createRebaseClient({ baseUrl: "http://localhost:3001", auth: { storage: createCookieStorage({ path: "/", sameSite: "Lax", secure: true }), autoRefresh: true, // default: true persistSession: true // default: true }});User Object Shape
Section titled “User Object Shape”interface RebaseUser { uid: string; email: string | null; displayName: string | null; photoURL: string | null; emailVerified?: boolean; roles?: string[]; // text[] from the users table providerId: string; isAnonymous: boolean;}Next Steps
Section titled “Next Steps”- Querying Data — CRUD operations and query builder
- Realtime Subscriptions — Live data with WebSockets
- Authentication Backend — Server-side auth configuration