Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/dart_firebase_admin/example/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ firebase.json
.firebaserc
firestore.indexes.json
firestore.rules
serviceAccountKey.json

# Logs
logs
Expand Down
82 changes: 50 additions & 32 deletions packages/dart_firebase_admin/example/lib/main.dart
Original file line number Diff line number Diff line change
@@ -1,44 +1,62 @@
import 'package:dart_firebase_admin/auth.dart';
import 'package:dart_firebase_admin/dart_firebase_admin.dart';
import 'package:dart_firebase_admin/firestore.dart';
import 'package:dart_firebase_admin/messaging.dart';

Future<void> main() async {
final admin = FirebaseAdminApp.initializeApp(
'dart-firebase-admin',
Credential.fromApplicationDefaultCredentials(),
);

// // admin.useEmulator();
final admin = FirebaseApp.initializeApp();
await authExample(admin);
await firestoreExample(admin);
await admin.close();
}

final messaging = Messaging(admin);
Future<void> authExample(FirebaseApp admin) async {
print('\n### Auth Example ###\n');

final auth = Auth(admin);

UserRecord? user;
try {
print('> Check if user with email exists: [email protected]\n');
user = await auth.getUserByEmail('[email protected]');
print('> User found by email\n');
} on FirebaseAuthAdminException catch (e) {
if (e.errorCode == AuthClientErrorCode.userNotFound) {
print('> User not found, creating new user\n');
user = await auth.createUser(
CreateRequest(
email: '[email protected]',
password: 'Test@123',
),
);
} else {
print('> Auth error: ${e.errorCode} - ${e.message}');
}
} catch (e, stackTrace) {
print('> Unexpected error: $e');
print('Stack trace: $stackTrace');
}

final result = await messaging.send(
TokenMessage(
token:
'e8Ap1n9UTQenyB-UEjNQt9:APA91bHhgc9RZYDcCKb7U1scQo1K0ZTSMItop8IqctrOcgvmN__oBo4vgbFX-ji4atr1PVw3Loug-eOCBmj4HVZjUE0aQBA0mGry7uL-7JuMaojhtl13MpvQtbZptvX_8f6vDcqei88O',
notification: Notification(
title: 'Hello',
body: 'World',
),
),
);
if (user != null) {
print('Fetched user email: ${user.email}');
}
}

print(result);
Future<void> firestoreExample(FirebaseApp admin) async {
print('\n### Firestore Example ###\n');

final firestore = Firestore(admin);

final collection = firestore.collection('users');

await collection.doc('123').set({
'name': 'John Doe',
'age': 30,
});

final snapshot = await collection.get();

for (final doc in snapshot.docs) {
print(doc.data());
try {
final collection = firestore.collection('users');
await collection.doc('123').set({
'name': 'John Doe',
'age': 27,
});
final snapshot = await collection.get();
for (final doc in snapshot.docs) {
print('> Document data: ${doc.data()}');
}
} catch (e) {
print('> Error setting document: $e');
}

await admin.close();
}
9 changes: 9 additions & 0 deletions packages/dart_firebase_admin/example/run_with_emulator.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#!/bin/bash

# Set environment variables for emulator
export FIRESTORE_EMULATOR_HOST=localhost:8080
export FIREBASE_AUTH_EMULATOR_HOST=localhost:9099
export GOOGLE_CLOUD_PROJECT=dart-firebase-admin

# Run the example
dart run lib/main.dart
35 changes: 35 additions & 0 deletions packages/dart_firebase_admin/example/run_with_prod.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/bin/bash

# Run example against Firebase production
#
# Authentication Options:
#
# Option 1: Service Account Key (used by this script)
# 1. Download your service account key from Firebase Console:
# - Go to Project Settings > Service Accounts
# - Click "Generate New Private Key"
# - Save as serviceAccountKey.json in this directory
# 2. Set GOOGLE_APPLICATION_CREDENTIALS below (already configured)
#
# Option 2: Application Default Credentials (alternative)
# 1. Run: gcloud auth application-default login
# 2. Set GOOGLE_CLOUD_PROJECT or GCLOUD_PROJECT (uncomment below)
# 3. Comment out GOOGLE_APPLICATION_CREDENTIALS
#
# For available environment variables, see:
# ../lib/src/app/environment.dart

# Service account credentials file path
# See: Environment.googleApplicationCredentials
export GOOGLE_APPLICATION_CREDENTIALS=serviceAccountKey.json

# (Optional) Explicit project ID - uncomment if needed
# See: Environment.googleCloudProject
# export GOOGLE_CLOUD_PROJECT=your-project-id

# (Optional) Legacy gcloud project ID - uncomment if needed
# See: Environment.gcloudProject
# export GCLOUD_PROJECT=your-project-id

# Run the example
dart run lib/main.dart
3 changes: 2 additions & 1 deletion packages/dart_firebase_admin/lib/app_check.dart
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export 'src/app_check/app_check.dart';
export 'src/app_check/app_check.dart'
hide AppCheckRequestHandler, AppCheckHttpClient;
export 'src/app_check/app_check_api.dart';
3 changes: 2 additions & 1 deletion packages/dart_firebase_admin/lib/auth.dart
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export 'src/auth.dart' hide UserMetadataToJson;
export 'src/auth.dart'
hide UserMetadataToJson, AuthRequestHandler, AuthHttpClient;
3 changes: 2 additions & 1 deletion packages/dart_firebase_admin/lib/dart_firebase_admin.dart
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export 'src/app.dart' hide envSymbol;
export 'src/app.dart'
hide envSymbol, ApplicationDefaultCredential, ServiceAccountCredential;
6 changes: 5 additions & 1 deletion packages/dart_firebase_admin/lib/firestore.dart
Original file line number Diff line number Diff line change
@@ -1,2 +1,6 @@
export 'src/google_cloud_firestore/firestore.dart'
hide $SettingsCopyWith, ApiMapValue;
hide
$SettingsCopyWith,
ApiMapValue,
AggregateFieldInternal,
FirestoreHttpClient;
3 changes: 2 additions & 1 deletion packages/dart_firebase_admin/lib/messaging.dart
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export 'src/messaging.dart' hide FirebaseMessagingRequestHandler;
export 'src/messaging/messaging.dart'
hide FirebaseMessagingRequestHandler, FirebaseMessagingHttpClient;
6 changes: 2 additions & 4 deletions packages/dart_firebase_admin/lib/security_rules.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,2 @@
export 'src/security_rules/security_rules.dart';
export 'src/security_rules/security_rules_api_internals.dart'
hide SecurityRulesApiClient;
export 'src/security_rules/security_rules_internals.dart';
export 'src/security_rules/security_rules.dart'
hide SecurityRulesRequestHandler, SecurityRulesHttpClient;
21 changes: 18 additions & 3 deletions packages/dart_firebase_admin/lib/src/app.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,27 @@ import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:equatable/equatable.dart';
import 'package:googleapis/identitytoolkit/v3.dart' as auth3;
import 'package:googleapis_auth/auth_io.dart' as auth;
import 'package:googleapis_auth/googleapis_auth.dart';
import 'package:googleapis_auth/auth_io.dart' as googleapis_auth;
import 'package:http/http.dart' as http;
import 'package:http/http.dart';
import 'package:meta/meta.dart';

import '../app_check.dart';
import '../auth.dart';
import '../firestore.dart';
import '../messaging.dart';
import '../security_rules.dart';

part 'app/app_exception.dart';
part 'app/app_options.dart';
part 'app/app_registry.dart';
part 'app/credential.dart';
part 'app/emulator_client.dart';
part 'app/environment.dart';
part 'app/exception.dart';
part 'app/firebase_admin.dart';
part 'app/firebase_app.dart';
part 'app/firebase_service.dart';

final _defaultAppRegistry = AppRegistry();
107 changes: 107 additions & 0 deletions packages/dart_firebase_admin/lib/src/app/app_exception.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
part of '../app.dart';

/// Exception thrown for Firebase app initialization and lifecycle errors.
class FirebaseAppException implements Exception {
FirebaseAppException(
this.errorCode, [
String? message,
]) : code = errorCode.code,
_message = message;

/// The error code object containing code and default message.
final AppErrorCode errorCode;

/// The error code string.
final String code;

/// Custom error message, if provided.
final String? _message;

/// The error message. Returns custom message if provided, otherwise default.
String get message => _message ?? errorCode.message;

@override
String toString() => 'FirebaseAppException($code): $message';
}

/// Firebase App error codes with their default messages.
///
/// These error codes match the Node.js SDK's AppErrorCodes for consistency.
enum AppErrorCode {
/// Firebase app with the given name has already been deleted.
appDeleted(
code: 'app-deleted',
message: 'The specified Firebase app has already been deleted.',
),

/// Firebase app with the same name already exists.
duplicateApp(
code: 'duplicate-app',
message: 'A Firebase app with the given name already exists.',
),

/// Invalid argument provided to a Firebase App method.
invalidArgument(
code: 'invalid-argument',
message: 'Invalid argument provided.',
),

/// An internal error occurred within the Firebase SDK.
internalError(
code: 'internal-error',
message: 'An internal error has occurred.',
),

/// Invalid Firebase app name provided.
invalidAppName(
code: 'invalid-app-name',
message: 'Invalid Firebase app name provided.',
),

/// Invalid app options provided to initializeApp().
invalidAppOptions(
code: 'invalid-app-options',
message: 'Invalid app options provided to initializeApp().',
),

/// Invalid credential configuration.
invalidCredential(
code: 'invalid-credential',
message: 'The credential configuration is invalid.',
),

/// Network error occurred during the operation.
networkError(
code: 'network-error',
message: 'A network error has occurred.',
),

/// Network timeout occurred during the operation.
networkTimeout(
code: 'network-timeout',
message: 'The network request timed out.',
),

/// No Firebase app exists with the given name.
noApp(
code: 'no-app',
message: 'No Firebase app exists with the given name.',
),

/// Unable to parse the server response.
unableToParseResponse(
code: 'unable-to-parse-response',
message: 'Unable to parse the response from the server.',
);

const AppErrorCode({
required this.code,
required this.message,
});

/// The error code string identifier.
final String code;

/// The default error message for this error code.
final String message;
}
Loading
Loading