### Initialize ConvexClientWithAuth in Swift Source: https://github.com/get-convex/convex-swift-auth0/blob/main/README.md Initialize `ConvexClientWithAuth` with your deployment URL and an `Auth0Provider` instance. Ensure you replace the placeholder deployment URL. ```swift let client = ConvexClientWithAuth(deploymentUrl: "$YOUR_DEPLOYMENT_URL", authProvider: Auth0Provider()) ``` -------------------------------- ### Initialize Auth0Provider Source: https://context7.com/get-convex/convex-swift-auth0/llms.txt Instantiate Auth0Provider with default or custom grace periods for token renewal. Use this to create a Convex client with Auth0 authentication. ```swift import ConvexAuth0 import ConvexMobile // Default initialization with 30-minute grace period let auth0Provider = Auth0Provider() // Custom grace period for shorter token lifetimes let auth0ProviderCustom = Auth0Provider(idTokenGracePeriod: 15 * 60) // 15-minute buffer // Create the Convex client with Auth0 authentication let client = ConvexClientWithAuth( deploymentUrl: "https://your-deployment.convex.cloud", authProvider: auth0Provider ) ``` -------------------------------- ### Sync Convex Configuration Source: https://context7.com/get-convex/convex-swift-auth0/llms.txt Run this command in your terminal to sync your Convex backend configuration, including authentication settings, to your Convex deployment. ```bash # Sync the configuration to your Convex deployment npx convex dev ``` -------------------------------- ### Perform Interactive Login Source: https://context7.com/get-convex/convex-swift-auth0/llms.txt Initiate Auth0's Universal Login flow to authenticate users. This opens a browser window and stores credentials upon successful login. ```swift import ConvexAuth0 import ConvexMobile let client = ConvexClientWithAuth( deploymentUrl: "https://your-deployment.convex.cloud", authProvider: Auth0Provider() ) // Perform interactive login - opens browser for Auth0 Universal Login do { try await client.login() // User is now authenticated // The authState publisher will emit .authenticated with credentials } catch { print("Login failed: \(error)") } ``` -------------------------------- ### Configure Convex Backend for Auth0 Source: https://context7.com/get-convex/convex-swift-auth0/llms.txt Set up the `auth.config.ts` file in your Convex backend to enable Auth0 authentication. This configuration is essential for Convex to validate tokens from your Auth0 tenant. ```typescript // convex/auth.config.ts export default { providers: [ { domain: "your-domain.us.auth0.com", applicationID: "yourclientid", }, ] }; ``` -------------------------------- ### Observe Authentication State with Combine Source: https://context7.com/get-convex/convex-swift-auth0/llms.txt Subscribe to the `authState` publisher to reactively update your UI based on authentication status changes. This is useful for showing different views for authenticated and unauthenticated users. ```swift import Combine import ConvexAuth0 import ConvexMobile import SwiftUI class AuthViewModel: ObservableObject { @Published var isAuthenticated = false @Published var userEmail: String? private var cancellables = Set() private let client: ConvexClientWithAuth init() { let auth0 = Auth0Provider() client = ConvexClientWithAuth( deploymentUrl: "https://your-deployment.convex.cloud", authProvider: auth0 ) // Subscribe to authentication state changes client.authState .receive(on: DispatchQueue.main) .sink { [weak self] state in switch state { case .authenticated(let credentials): self?.isAuthenticated = true // Access user info from credentials // credentials.idToken contains the JWT with user claims case .unauthenticated: self?.isAuthenticated = false self?.userEmail = nil case .loading: // Show loading indicator break } } .store(in: &cancellables) } func login() async { try? await client.login() } func logout() async { try? await client.logout() } } ``` -------------------------------- ### Auto Sign-In from Cache Source: https://context7.com/get-convex/convex-swift-auth0/llms.txt Enable automatic sign-in for returning users by restoring credentials from secure storage. This method checks and renews tokens if they are within the grace period. ```swift import ConvexAuth0 import ConvexMobile let client = ConvexClientWithAuth( deploymentUrl: "https://your-deployment.convex.cloud", authProvider: Auth0Provider(idTokenGracePeriod: 30 * 60) ) // Attempt auto sign-in on app launch do { try await client.loginFromCache() // User is signed in from cached credentials // Token will be renewed automatically if within grace period } catch { // No valid cached credentials - show login UI print("No cached credentials available") } ``` -------------------------------- ### Configure Auth0 Providers in Convex Source: https://github.com/get-convex/convex-swift-auth0/blob/main/README.md Define Auth0 providers in your Convex application's `convex/auth.config.ts` file. Replace placeholders with your actual Auth0 domain and client ID. ```typescript export default { providers: [ { domain: "your-domain.us.auth0.com", applicationID: "yourclientid", }, ] }; ``` -------------------------------- ### Perform Logout Source: https://context7.com/get-convex/convex-swift-auth0/llms.txt Clear the Auth0 session and locally stored credentials for a complete sign-out. This removes cached credentials and clears the browser session. ```swift import ConvexAuth0 import ConvexMobile let client = ConvexClientWithAuth( deploymentUrl: "https://your-deployment.convex.cloud", authProvider: Auth0Provider() ) // Sign out the user completely do { try await client.logout() // User is now logged out // The authState publisher will emit .unauthenticated } catch { print("Logout failed: \(error)") } ``` -------------------------------- ### Access User Identity in Convex Functions Source: https://context7.com/get-convex/convex-swift-auth0/llms.txt Secure your Convex backend functions by accessing user identity information. The `ctx.auth.getUserIdentity()` method retrieves the authenticated user's details, such as their subject ID and email. ```typescript // convex/messages.ts import { query, mutation } from "./_generated/server"; import { v } from "convex/values"; // Query that requires authentication export const getMyMessages = query({ handler: async (ctx) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) { throw new Error("Not authenticated"); } // identity.subject contains the Auth0 user ID // identity.email contains the user's email if available return await ctx.db .query("messages") .filter((q) => q.eq(q.field("userId"), identity.subject)) .collect(); }, }); // Mutation that stores user-specific data export const sendMessage = mutation({ args: { content: v.string() }, handler: async (ctx, args) => { const identity = await ctx.auth.getUserIdentity(); if (!identity) { throw new Error("Not authenticated"); } await ctx.db.insert("messages", { content: args.content, userId: identity.subject, userEmail: identity.email, createdAt: Date.now(), }); }, }); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.