### Get User by UID Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Retrieve a user record by their unique identifier. Handles 'auth/user-not-found' errors. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); try { var user = await app.auth().getUser('user-uid-123'); print('UID: ${user.uid}'); print('Email: ${user.email}'); print('Display Name: ${user.displayName}'); print('Phone: ${user.phoneNumber}'); print('Email Verified: ${user.emailVerified}'); print('Disabled: ${user.disabled}'); print('Created: ${user.metadata.creationTime}'); print('Last Sign In: ${user.metadata.lastSignInTime}'); print('Custom Claims: ${user.customClaims}'); print('Providers: ${user.providerData.map((p) => p.providerId).join(', ')}'); } on FirebaseAuthError catch (e) { if (e.code == 'auth/user-not-found') { print('User not found'); } else { print('Error: ${e.message}'); } } } ``` -------------------------------- ### Get User by Phone Number Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Retrieve a user using their phone number in E.164 format. Includes error handling for authentication failures. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); try { var user = await app.auth().getUserByPhoneNumber('+15555550123'); print('User found: ${user.uid}'); print('Phone: ${user.phoneNumber}'); } on FirebaseAuthError catch (e) { print('Error: ${e.message}'); } } ``` -------------------------------- ### Get User by Email Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Look up a user by their email address. Catches FirebaseAuthError for potential issues. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); try { var user = await app.auth().getUserByEmail('jane@example.com'); print('User found: ${user.uid}'); print('Email verified: ${user.emailVerified}'); print(user.toJson()); // Full user data as JSON } on FirebaseAuthError catch (e) { print('Error ${e.code}: ${e.message}'); } } ``` -------------------------------- ### Initialize Firebase Admin with Service Account Source: https://github.com/appsup-dart/firebase_admin/blob/master/README.md Use this method when you have a service account JSON file. Ensure the file path is correct. ```dart import 'package:firebase_admin/firebase_admin.dart'; main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), )); var link = await app.auth().generateSignInWithEmailLink('jane@doe.com', ActionCodeSettings(url: 'https://example.com')); print(link); } ``` -------------------------------- ### Create User with MFA Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Create a new user account with specified properties, including optional multi-factor authentication enrollment. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); try { var user = await app.auth().createUser( uid: 'custom-uid-123', // Optional, auto-generated if not provided email: 'newuser@example.com', emailVerified: false, password: 'secretPassword123', displayName: 'John Doe', phoneNumber: '+15555550123', photoUrl: Uri.parse('https://example.com/photo.jpg'), disabled: false, multiFactorEnrolledFactors: [ CreateMultiFactorInfoRequest.phone( displayName: 'Personal Phone', phoneNumber: '+15555550124', ), ], ); print('Created user: ${user.uid}'); print('Email: ${user.email}'); print('MFA enrolled: ${user.multiFactor.enrolledFactors.length}'); } on FirebaseAuthError catch (e) { if (e.code == 'auth/email-already-exists') { print('Email already in use'); } else if (e.code == 'auth/invalid-password') { print('Password too weak'); } else { print('Error: ${e.message}'); } } } ``` -------------------------------- ### List Users with Pagination Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Retrieve users in batches using pagination. Fetches up to 1000 users per request and continues until all users are listed. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); var auth = app.auth(); String? pageToken; var totalUsers = 0; do { // Fetch up to 1000 users per batch var result = await auth.listUsers(1000, pageToken); for (var user in result.users) { print('User: ${user.uid} - ${user.email ?? 'No email'}'); totalUsers++; } pageToken = result.pageToken; } while (pageToken != null); print('Total users: $totalUsers'); } ``` -------------------------------- ### Initialize Firebase Admin with Default Credentials Source: https://github.com/appsup-dart/firebase_admin/blob/master/README.md This method automatically finds credentials from environment variables, configuration files, or gcloud/firebase tools. It includes a fallback to login if no credentials are found. ```dart import 'package:firebase_admin/firebase_admin.dart'; import 'package:firebase_admin/src/credential.dart'; void main() async { // applicationDefault() will look for credentials in the following locations: // * the env variable GOOGLE_APPLICATION_CREDENTIALS // * a configuration file, specific for this library, stored in the user's home directory // * gcloud's application default credentials // * credentials from the firebase tools var credential = Credentials.applicationDefault(); // when no credentials found, login using openid // the credentials are store on disk for later use credential ??= await Credentials.login(); // create an app var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: credential ?? Credentials.applicationDefault(), projectId: 'some-project')); try { // get a user by email var v = await app.auth().getUserByEmail('jane@doe.com'); print(v.toJson()); } on FirebaseException catch (e) { print(e.message); } } ``` -------------------------------- ### Initialize App with Service Account Credential Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Initialize the Firebase app using a service account JSON file. This is recommended for production environments. Ensure the 'service-account.json' file is accessible and replace 'your-project-id' with your actual project ID. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { // Initialize with service account credential file var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', databaseUrl: 'https://your-project-id.firebaseio.com/', storageBucket: 'your-project-id.appspot.com', )); print('App initialized: ${app.name}'); // Output: App initialized: [DEFAULT] // Access services var auth = app.auth(); var db = app.database(); var storage = app.storage(); } ``` -------------------------------- ### Initialize App with Application Default Credentials Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Initialize the Firebase app using application default credentials. This method automatically discovers credentials from environment variables, local files, or gcloud configurations. If no credentials are found, it attempts an interactive login. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { // applicationDefault() searches for credentials in: // 1. service-account.json in package directory // 2. GOOGLE_APPLICATION_CREDENTIALS environment variable // 3. Firebase Admin credential path (~/.config/firebase_admin/) // 4. gcloud application default credentials // 5. Firebase CLI tools credentials var credential = Credentials.applicationDefault(); // If no credentials found, perform interactive login // Requires FIREBASE_CLIENT_ID and FIREBASE_CLIENT_SECRET env vars credential ??= await Credentials.login(); var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: credential, projectId: 'your-project-id', )); try { var user = await app.auth().getUserByEmail('user@example.com'); print('Found user: ${user.uid}'); } on FirebaseException catch (e) { print('Error: ${e.code} - ${e.message}'); } } ``` -------------------------------- ### Initialize Multiple Named Firebase Apps Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Initialize multiple Firebase app instances with distinct configurations for managing different projects. Apps can be accessed by their default name or a custom name provided during initialization. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { // Initialize default app var defaultApp = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('default-service-account.json'), projectId: 'default-project', )); // Initialize named app for different project var secondaryApp = FirebaseAdmin.instance.initializeApp( AppOptions( credential: ServiceAccountCredential('secondary-service-account.json'), projectId: 'secondary-project', ), 'secondary', // Custom app name ); // Access apps by name var defaultAuth = FirebaseAdmin.instance.app()!.auth(); var secondaryAuth = FirebaseAdmin.instance.app('secondary')!.auth(); // List all initialized apps var allApps = FirebaseAdmin.instance.apps; print('Initialized apps: ${allApps.map((a) => a.name).join(', ')}'); // Clean up await defaultApp.delete(); await secondaryApp.delete(); } ``` -------------------------------- ### Create Custom Authentication Token Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Generate a custom authentication token for a user, which can be used with client SDKs to sign in. Optional custom claims can be included in the token. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); // Create token with optional custom claims var customToken = await app.auth().createCustomToken( 'user-uid-123', { 'premiumAccount': true, 'subscriptionLevel': 'gold', }, ); print('Custom token: $customToken'); // Client can use: firebase.auth().signInWithCustomToken(customToken) } ``` -------------------------------- ### Create Custom Token Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Generate a custom authentication token for a user, which can be used with client SDKs to sign in. ```APIDOC ## POST /admin/auth/custom-token ### Description Generates a custom authentication token for a user. This token can be used with client SDKs to sign in the user. ### Method POST ### Endpoint /admin/auth/custom-token ### Request Body - **uid** (string) - Required - The UID of the user for whom to create the token. - **developerClaims** (object) - Optional - A JSON object containing custom claims to include in the token. ### Request Example ```json { "uid": "user-uid-123", "developerClaims": { "premiumAccount": true, "subscriptionLevel": "gold" } } ``` ### Response #### Success Response (200) - **customToken** (string) - The generated custom authentication token. #### Response Example ```json { "customToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9..." } ``` ``` -------------------------------- ### Generate Passwordless Sign-In Link Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Generates a passwordless sign-in link for a user's email address. This link can be sent via email and used to sign the user in without a password. Configure `ActionCodeSettings` to customize the redirect URL and app behavior. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); var link = await app.auth().generateSignInWithEmailLink( 'user@example.com', ActionCodeSettings( url: 'https://example.com/finishSignIn?cartId=1234', handleCodeInApp: true, iosBundleId: 'com.example.ios', androidPackageName: 'com.example.android', androidInstallApp: true, androidMinimumVersion: '12', dynamicLinkDomain: 'example.page.link', ), ); print('Sign-in link: $link'); // Send this link to user via email } ``` -------------------------------- ### Firebase Cloud Storage Operations in Dart Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Manage files within Google Cloud Storage buckets using the Dart Admin SDK. Initialize FirebaseAdmin with storageBucket option and access default or custom buckets. ```dart import 'package:firebase_admin/firebase_admin'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', storageBucket: 'your-project-id.appspot.com', )); var storage = app.storage(); // Get default bucket var bucket = storage.bucket(); // Get specific bucket var customBucket = storage.bucket('my-custom-bucket'); // List files in bucket await for (var object in bucket.list()) { print('File: ${object.name}'); } // Access specific file var file = bucket.info('path/to/file.txt'); print('File info: ${file.name}'); } ``` -------------------------------- ### Mock Credentials for Firebase Admin SDK Testing in Dart Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Utilize mock credentials for unit testing Firebase Admin SDK functionalities without requiring actual Firebase credentials. Supports basic mock and service account mock credentials, with options to check and reset call counts. ```dart import 'package:firebase_admin/firebase_admin'; import 'package:firebase_admin/testing.dart'; void main() async { // Use mock credential for testing var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: MockCredential(), projectId: 'test-project', )); // Or use service account mock for more realistic testing var appWithServiceAccount = FirebaseAdmin.instance.initializeApp( AppOptions( credential: ServiceAccountMockCredential(), projectId: 'test-project', ), 'test-app', ); // Check credential call count for testing var callCount = MockCredentialMixin.getCallCount(app); print('Credential called $callCount times'); // Reset call count between tests MockCredentialMixin.resetCallCount(app); // Custom token factory for specific test scenarios var customMockCredential = MockCredential(() => MockAccessToken( accessToken: 'custom-test-token', expiresIn: Duration(hours: 1), )); await app.delete(); } ``` -------------------------------- ### Tenant-Aware Authentication Operations Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Performs authentication operations scoped to a specific tenant in a multi-tenant Firebase project. Obtain a tenant-aware `Auth` instance using `tenantManager.authForTenant()` and use it for user management, token creation, and verification within that tenant. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); var auth = app.auth(); var tenantManager = auth.tenantManager(); // Get auth instance for specific tenant var tenantAuth = tenantManager.authForTenant('tenant-id-123'); // All operations are now scoped to this tenant try { var user = await tenantAuth.getUserByEmail('tenant-user@example.com'); print('Tenant user: ${user.uid}'); print('Tenant ID: ${user.tenantId}'); // Create user in tenant var newUser = await tenantAuth.createUser( email: 'newuser@example.com', password: 'password123', ); print('Created tenant user: ${newUser.uid}'); // Generate custom token for tenant user var token = await tenantAuth.createCustomToken('tenant-user-uid'); print('Tenant custom token: $token'); // Verify token and check tenant var decodedToken = await tenantAuth.verifyIdToken(clientIdToken); // Throws FirebaseAuthError.mismatchingTenantId if tenant doesn't match } on FirebaseAuthError catch (e) { print('Error: ${e.message}'); } } ``` -------------------------------- ### Update User Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Update an existing user's properties. Fields can be set to an empty string to remove them. ```APIDOC ## POST /admin/user/update ### Description Updates an existing user's properties. Fields can be set to an empty string to remove them. ### Method POST ### Endpoint /admin/user/update ### Request Body - **uid** (string) - Required - The UID of the user to update. - **email** (string) - Optional - The new email address for the user. - **emailVerified** (boolean) - Optional - Whether the email is verified. - **password** (string) - Optional - The new password for the user. - **displayName** (string) - Optional - The new display name for the user. - **phoneNumber** (string) - Optional - The new phone number for the user. - **photoUrl** (string) - Optional - The new photo URL for the user. - **disabled** (boolean) - Optional - Whether the user account is disabled. - **multiFactorEnrolledFactors** (array) - Optional - A list of multi-factor enrollment requests. ### Request Example ```json { "uid": "user-uid-123", "email": "newemail@example.com", "emailVerified": true, "password": "newPassword456", "displayName": "Jane Doe", "phoneNumber": "+15555559999", "photoUrl": "https://example.com/newphoto.jpg", "disabled": false, "multiFactorEnrolledFactors": [ { "displayName": "Work Phone", "phoneNumber": "+15555550125" } ] } ``` ### Response #### Success Response (200) - **uid** (string) - The updated user's UID. - **email** (string) - The updated user's email. #### Response Example ```json { "uid": "user-uid-123", "email": "newemail@example.com" } ``` ``` -------------------------------- ### Generate Email Verification Link Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Generates an email verification link for a user's email address. This link can be sent via email to verify the user's email. Configure `ActionCodeSettings` to specify the redirect URL. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); var link = await app.auth().generateEmailVerificationLink( 'user@example.com', ActionCodeSettings( url: 'https://example.com/verified', ), ); print('Verification link: $link'); // Send this link to user via email } ``` -------------------------------- ### Generate Password Reset Link Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Generates a password reset link for a user's email address. This link can be sent via email to allow the user to reset their password. Configure `ActionCodeSettings` to specify the redirect URL. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); var link = await app.auth().generatePasswordResetLink( 'user@example.com', ActionCodeSettings( url: 'https://example.com/resetComplete', handleCodeInApp: false, ), ); print('Password reset link: $link'); // Send this link to user via email } ``` -------------------------------- ### Set Custom User Claims Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Set custom claims on a user's ID token for role-based access control and custom authorization logic. ```APIDOC ## POST /admin/user/{uid}/claims ### Description Sets custom claims on a user's ID token. These claims can be used for role-based access control and custom authorization logic. ### Method POST ### Endpoint /admin/user/{uid}/claims ### Path Parameters - **uid** (string) - Required - The UID of the user to set claims for. ### Request Body - **claims** (object) - Required - An object containing the custom claims to set. An empty object `{}` will clear all custom claims. ### Request Example ```json { "claims": { "admin": true, "accessLevel": 10, "role": "superuser", "permissions": ["read", "write", "delete"] } } ``` ### Response #### Success Response (200) Indicates the custom claims were successfully set. #### Response Example (No specific response body provided for success, typically an empty 200 OK) ### Notes - After setting custom claims, it may take some time for the changes to propagate to all active user sessions. - To clear custom claims, send an empty JSON object `{}` as the claims. - The user object returned by `getUser` will contain the `customClaims` property. ``` -------------------------------- ### Update User Properties Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Update an existing user's properties like email, display name, and phone number. Set fields to an empty string to remove them. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); try { var user = await app.auth().updateUser( 'user-uid-123', email: 'newemail@example.com', emailVerified: true, password: 'newPassword456', displayName: 'Jane Doe', phoneNumber: '+15555559999', photoUrl: Uri.parse('https://example.com/newphoto.jpg'), disabled: false, multiFactorEnrolledFactors: [ UpdateMultiFactorInfoRequest.phone( displayName: 'Work Phone', phoneNumber: '+15555550125', ), ], ); print('Updated user: ${user.uid}'); print('New email: ${user.email}'); // Remove display name and photo by setting to empty string user = await app.auth().updateUser( 'user-uid-123', displayName: '', // Removes display name photoUrl: Uri.parse(''), // Removes photo URL ); } on FirebaseAuthError catch (e) { print('Error: ${e.message}'); } } ``` -------------------------------- ### Delete User Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Delete a user account by UID. ```APIDOC ## DELETE /admin/user/{uid} ### Description Deletes a user account by their UID. ### Method DELETE ### Endpoint /admin/user/{uid} ### Path Parameters - **uid** (string) - Required - The UID of the user to delete. ### Response #### Success Response (200) Indicates the user was successfully deleted. #### Response Example (No specific response body provided for success, typically an empty 200 OK) ### Error Handling - **auth/user-not-found**: If the user with the specified UID does not exist. - Other FirebaseAuthError codes for general errors. ``` -------------------------------- ### Handle Firebase Exceptions in Dart Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Use try-catch blocks to handle various Firebase exceptions like FirebaseAuthError, FirebaseAppError, FirebaseStorageError, and generic FirebaseException. Inspect the error code for specific actions. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); try { await app.auth().getUser('nonexistent-uid'); } on FirebaseAuthError catch (e) { // Auth-specific errors switch (e.code) { case 'auth/user-not-found': print('User does not exist'); break; case 'auth/invalid-uid': print('Invalid UID format'); break; case 'auth/insufficient-permission': print('Check your service account permissions'); break; default: print('Auth error: ${e.code} - ${e.message}'); } } on FirebaseAppError catch (e) { // App-level errors switch (e.code) { case 'app/invalid-credential': print('Invalid credential configuration'); break; case 'app/network-error': print('Network connection failed'); break; case 'app/no-app': print('App not initialized'); break; default: print('App error: ${e.code} - ${e.message}'); } } on FirebaseStorageError catch (e) { // Storage-specific errors print('Storage error: ${e.code} - ${e.message}'); } on FirebaseException catch (e) { // Generic Firebase error print('Firebase error: ${e.code} - ${e.message}'); print('Error JSON: ${e.toJson()}'); } } ``` -------------------------------- ### Set Custom User Claims Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Set custom claims on a user's ID token to implement role-based access control or custom authorization logic. Claims can be cleared by setting them to an empty map. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); var auth = app.auth(); // Set admin privileges await auth.setCustomUserClaims('user-uid-123', { 'admin': true, 'accessLevel': 10, 'role': 'superuser', 'permissions': ['read', 'write', 'delete'], }); // Verify claims were set var user = await auth.getUser('user-uid-123'); print('Custom claims: ${user.customClaims}'); // Output: {admin: true, accessLevel: 10, role: superuser, permissions: [read, write, delete]} // Clear custom claims await auth.setCustomUserClaims('user-uid-123', {}); user = await auth.getUser('user-uid-123'); print('Claims after clear: ${user.customClaims}'); // Output: null or {} } ``` -------------------------------- ### Firebase Realtime Database Operations in Dart Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Perform CRUD operations, listen for changes, and manage data in Firebase Realtime Database using Dart. Ensure FirebaseAdmin is initialized with appropriate credentials and database URL. ```dart import 'package:firebase_admin/firebase_admin'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', databaseUrl: 'https://your-project-id.firebaseio.com/', )); var db = app.database(); // Get reference to root var rootRef = db.ref(); // Get reference to specific path var usersRef = db.ref('users'); var userRef = db.ref('users/user-123'); // Read data var snapshot = await userRef.get(); if (snapshot.exists) { print('User data: ${snapshot.value}'); } // Write data await userRef.set({ 'name': 'John Doe', 'email': 'john@example.com', 'createdAt': DateTime.now().millisecondsSinceEpoch, }); // Update specific fields await userRef.update({ 'lastLogin': DateTime.now().millisecondsSinceEpoch, 'loginCount': ServerValue.increment(1), }); // Push new item to list var messagesRef = db.ref('messages'); var newMessageRef = messagesRef.push(); await newMessageRef.set({ 'text': 'Hello, World!', 'timestamp': ServerValue.timestamp, }); print('New message key: ${newMessageRef.key}'); // Delete data await db.ref('users/old-user').remove(); // Listen for changes userRef.onValue.listen((event) { print('User changed: ${event.snapshot.value}'); }); // Clean up await app.delete(); } ``` -------------------------------- ### Verify ID Token Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Verify a Firebase ID token from a client and optionally check if it has been revoked. ```APIDOC ## POST /admin/auth/verify-id-token ### Description Verifies a Firebase ID token received from a client. Optionally checks if the token has been revoked. ### Method POST ### Endpoint /admin/auth/verify-id-token ### Request Body - **idToken** (string) - Required - The ID token string to verify. - **checkRevoked** (boolean) - Optional - If true, checks if the ID token has been revoked. Defaults to false. ### Request Example ```json { "idToken": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...", "checkRevoked": true } ``` ### Response #### Success Response (200) - **decodedToken** (object) - An object containing the decoded token claims. - **uid** (string) - The user's UID. - **authTime** (number) - The authentication time of the user. - ... other standard JWT claims #### Response Example ```json { "decodedToken": { "uid": "user-uid-123", "authTime": 1678886400, "iss": "https://securetoken.google.com/your-project-id", "aud": "your-project-id", "exp": 1678890000, "iat": 1678886400, "firebase": { "identities": { "email": ["user@example.com"] }, "sign_in_provider": "password" } } } ``` ### Error Handling - **auth/id-token-expired**: If the ID token has expired. - **auth/id-token-revoked**: If `checkRevoked` is true and the token has been revoked. - **auth/invalid-id-token**: If the ID token is invalid. ``` -------------------------------- ### Revoke User Refresh Tokens Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Revokes all refresh tokens for a given user UID, effectively invalidating all their active sessions. After revocation, you can verify ID tokens with `checkRevoked=true` to detect if the user needs to re-authenticate. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); var auth = app.auth(); // Revoke all tokens await auth.revokeRefreshTokens('user-uid-123'); // Get user to see the tokensValidAfterTime var user = await auth.getUser('user-uid-123'); print('Tokens valid after: ${user.tokensValidAfterTime}'); // When verifying tokens, use checkRevoked=true try { await auth.verifyIdToken(idTokenFromClient, true); } on FirebaseAuthError catch (e) { if (e.code == 'auth/id-token-revoked') { print('User needs to re-authenticate'); } } } ``` -------------------------------- ### Verify Firebase ID Token Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Verify a Firebase ID token received from a client. Optionally, check if the token has been revoked. Handles expired, revoked, and invalid token errors. ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); var idTokenFromClient = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...'; try { // Basic verification var decodedToken = await app.auth().verifyIdToken(idTokenFromClient); print('Verified UID: ${decodedToken.claims.subject}'); print('Auth time: ${decodedToken.claims.authTime}'); // Verify with revocation check (recommended for sensitive operations) decodedToken = await app.auth().verifyIdToken(idTokenFromClient, true); print('Token is valid and not revoked'); } on FirebaseAuthError catch (e) { if (e.code == 'auth/id-token-expired') { print('Token has expired'); } else if (e.code == 'auth/id-token-revoked') { print('Token has been revoked'); } else if (e.code == 'auth/invalid-id-token') { print('Token is invalid'); } else { print('Verification error: ${e.message}'); } } } ``` -------------------------------- ### Delete User Account Source: https://context7.com/appsup-dart/firebase_admin/llms.txt Delete a user account from Firebase Authentication using their unique user ID (UID). ```dart import 'package:firebase_admin/firebase_admin.dart'; void main() async { var app = FirebaseAdmin.instance.initializeApp(AppOptions( credential: ServiceAccountCredential('service-account.json'), projectId: 'your-project-id', )); try { await app.auth().deleteUser('user-uid-to-delete'); print('User deleted successfully'); } on FirebaseAuthError catch (e) { if (e.code == 'auth/user-not-found') { print('User does not exist'); } else { print('Error: ${e.message}'); } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.