-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathauth_example.dart
More file actions
609 lines (551 loc) · 18.1 KB
/
auth_example.dart
File metadata and controls
609 lines (551 loc) · 18.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import 'package:dart_firebase_admin/auth.dart';
import 'package:dart_firebase_admin/dart_firebase_admin.dart';
Future<void> authExample(FirebaseApp admin) async {
print('\n### Auth Example ###\n');
final auth = admin.auth();
UserRecord? user;
try {
print('> Check if user with email exists: test@example.com\n');
user = await auth.getUserByEmail('test@example.com');
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: 'test@example.com', password: 'Test@12345'),
);
} else {
print('> Auth error: ${e.errorCode} - ${e.message}');
}
} catch (e, stackTrace) {
print('> Unexpected error: $e');
print('Stack trace: $stackTrace');
}
if (user != null) {
print('Fetched user email: ${user.email}');
}
}
Future<void> projectConfigExample(FirebaseApp admin) async {
print('\n### Project Config Example ###\n');
final projectConfigManager = admin.auth().projectConfigManager;
try {
// Get current project configuration
print('> Fetching current project configuration...\n');
final config = await projectConfigManager.getProjectConfig();
// Display current configuration
print('Current project configuration:');
if (config.emailPrivacyConfig != null) {
print(
' - Email Privacy: ${config.emailPrivacyConfig!.enableImprovedEmailPrivacy}',
);
}
if (config.passwordPolicyConfig != null) {
print(
' - Password Policy: ${config.passwordPolicyConfig!.enforcementState}',
);
}
if (config.smsRegionConfig != null) {
print(' - SMS Region Config: enabled');
}
if (config.mobileLinksConfig != null) {
print(' - Mobile Links: ${config.mobileLinksConfig!.domain?.value}');
}
print('');
// Example: Update email privacy configuration
print('> Updating email privacy configuration...\n');
final updatedConfig = await projectConfigManager.updateProjectConfig(
UpdateProjectConfigRequest(
emailPrivacyConfig: EmailPrivacyConfig(
enableImprovedEmailPrivacy: true,
),
),
);
print('Configuration updated successfully!');
if (updatedConfig.emailPrivacyConfig != null) {
print(
' - Improved Email Privacy: ${updatedConfig.emailPrivacyConfig!.enableImprovedEmailPrivacy}',
);
}
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error managing project config: $e');
}
}
/// Tenant management example.
///
/// Steps to enable Identity Platform:
///
/// 1. Go to Google Cloud Console (not Firebase Console):
/// - Visit: https://console.cloud.google.com/
/// - Select your project
///
/// 2. Enable Identity Platform API:
/// - In the search bar, search for "Identity Platform"
/// - Click on "Identity Platform"
/// - Click "Enable API" if not already enabled
///
/// 3. Upgrade to Identity Platform:
/// - Once in Identity Platform, look for an "Upgrade" or "Get Started" button
/// - Follow the prompts to upgrade from Firebase Auth to Identity Platform
///
/// 4. Enable Multi-tenancy:
/// - After upgrading, go to Settings
/// - Look for "Multi-tenancy" option
/// - Enable it
Future<void> tenantExample(FirebaseApp admin) async {
print('\n### Tenant Example ###\n');
final tenantManager = admin.auth().tenantManager;
String? createdTenantId;
try {
print('> Creating a new tenant...\n');
final newTenant = await tenantManager.createTenant(
UpdateTenantRequest(
displayName: 'example-tenant',
emailSignInConfig: EmailSignInProviderConfig(
enabled: true,
passwordRequired: true,
),
),
);
createdTenantId = newTenant.tenantId;
print('Tenant created successfully!');
print(' - Tenant ID: ${newTenant.tenantId}');
print(' - Display Name: ${newTenant.displayName}');
print('');
// Get the tenant
print('> Fetching tenant details...\n');
final tenant = await tenantManager.getTenant(createdTenantId);
print('Tenant details:');
print(' - ID: ${tenant.tenantId}');
print(' - Display Name: ${tenant.displayName}');
print('');
// Update the tenant
print('> Updating tenant...\n');
final updatedTenant = await tenantManager.updateTenant(
createdTenantId,
UpdateTenantRequest(displayName: 'updated-tenant'),
);
print('Tenant updated successfully!');
print(' - New Display Name: ${updatedTenant.displayName}');
print('');
// List tenants
print('> Listing all tenants...\n');
final listResult = await tenantManager.listTenants();
print('Found ${listResult.tenants.length} tenant(s)');
for (final t in listResult.tenants) {
print(' - ${t.tenantId}: ${t.displayName}');
}
print('');
// Delete the tenant
print('> Deleting tenant...\n');
await tenantManager.deleteTenant(createdTenantId);
print('Tenant deleted successfully!');
} on FirebaseAuthAdminException catch (e) {
if (e.code == 'auth/invalid-project-id') {
print('> Multi-tenancy is not enabled for this project.');
print(
' Enable it in Firebase Console under Identity Platform settings.',
);
} else {
print('> Auth error: ${e.code} - ${e.message}');
}
// Clean up if tenant was created
if (createdTenantId != null) {
try {
await tenantManager.deleteTenant(createdTenantId);
} catch (_) {
// Ignore cleanup errors
}
}
} catch (e) {
print('> Error managing tenants: $e');
// Clean up if tenant was created
if (createdTenantId != null) {
try {
await tenantManager.deleteTenant(createdTenantId);
} catch (_) {
// Ignore cleanup errors
}
}
}
}
Future<void> userManagementExample(FirebaseApp admin) async {
print('\n### User Management Example ###\n');
final auth = admin.auth();
// getUser
try {
print('> Fetching user by UID...\n');
final user = await auth.getUser('some-uid');
print('User: ${user.uid} — ${user.email}');
} on FirebaseAuthAdminException catch (e) {
if (e.errorCode == AuthClientErrorCode.userNotFound) {
print('> User not found');
} else {
print('> Auth error: ${e.code} - ${e.message}');
}
} catch (e) {
print('> Error: $e');
}
// getUserByPhoneNumber
try {
print('> Fetching user by phone number...\n');
final user = await auth.getUserByPhoneNumber('+15551234567');
print('User by phone: ${user.uid}');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// getUserByProviderUid
try {
print('> Fetching user by provider UID...\n');
final user = await auth.getUserByProviderUid(
providerId: 'google.com',
uid: 'google-uid-123',
);
print('User by provider: ${user.uid}');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// getUsers (batch lookup)
try {
print('> Batch fetching users...\n');
final result = await auth.getUsers([
UidIdentifier(uid: 'uid-1'),
EmailIdentifier(email: 'user@example.com'),
PhoneIdentifier(phoneNumber: '+15559876543'),
]);
print('Found ${result.users.length} user(s)');
print('Not found: ${result.notFound.length}');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// updateUser
try {
print('> Updating user...\n');
final updated = await auth.updateUser(
'some-uid',
UpdateRequest(displayName: 'Updated Name', disabled: false),
);
print('Updated user: ${updated.displayName}');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// listUsers
try {
print('> Listing users (first page)...\n');
final result = await auth.listUsers(maxResults: 10);
print('Listed ${result.users.length} user(s)');
if (result.pageToken != null) {
print('Next page token: ${result.pageToken}');
}
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// importUsers
try {
print('> Importing users...\n');
final importResult = await auth.importUsers([
UserImportRecord(uid: 'import-uid-1', email: 'import1@example.com'),
UserImportRecord(uid: 'import-uid-2', email: 'import2@example.com'),
]);
print(
'Import complete: ${importResult.successCount} succeeded, '
'${importResult.failureCount} failed',
);
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// deleteUser
try {
print('> Deleting single user...\n');
await auth.deleteUser('some-uid');
print('User deleted');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// deleteUsers
try {
print('> Deleting multiple users...\n');
final result = await auth.deleteUsers(['uid-a', 'uid-b', 'uid-c']);
print(
'Deleted: ${result.successCount} succeeded, '
'${result.failureCount} failed',
);
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
}
Future<void> emailLinksExample(FirebaseApp admin) async {
print('\n### Email Action Links Example ###\n');
final auth = admin.auth();
const email = 'user@example.com';
final actionCodeSettings = ActionCodeSettings(
url: 'https://example.com/finishSignUp?cartId=1234',
handleCodeInApp: true,
iOS: ActionCodeSettingsIos('com.example.ios'),
android: ActionCodeSettingsAndroid(
packageName: 'com.example.android',
installApp: true,
minimumVersion: '12',
),
);
// generatePasswordResetLink
try {
print('> Generating password reset link...\n');
final link = await auth.generatePasswordResetLink(
email,
actionCodeSettings: actionCodeSettings,
);
print('Password reset link: $link\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// generateEmailVerificationLink
try {
print('> Generating email verification link...\n');
final link = await auth.generateEmailVerificationLink(
email,
actionCodeSettings: actionCodeSettings,
);
print('Email verification link: $link\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// generateVerifyAndChangeEmailLink
try {
print('> Generating verify-and-change-email link...\n');
final link = await auth.generateVerifyAndChangeEmailLink(
email,
'newemail@example.com',
actionCodeSettings: actionCodeSettings,
);
print('Verify-and-change-email link: $link\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// generateSignInWithEmailLink
try {
print('> Generating sign-in-with-email link...\n');
final link = await auth.generateSignInWithEmailLink(
email,
actionCodeSettings,
);
print('Sign-in-with-email link: $link\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
}
Future<void> tokenExample(FirebaseApp admin) async {
print('\n### Custom Tokens & ID Token Verification Example ###\n');
final auth = admin.auth();
const uid = 'some-uid';
// setCustomUserClaims
try {
print('> Setting custom user claims...\n');
await auth.setCustomUserClaims(
uid,
customUserClaims: {'admin': true, 'accessLevel': 5},
);
print('Custom claims set\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// createCustomToken
try {
print('> Creating custom token...\n');
final customToken = await auth.createCustomToken(uid);
print(
'Custom token (first 40 chars): ${customToken.substring(0, 40)}...\n',
);
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// verifyIdToken
try {
print('> Verifying ID token...\n');
final decoded = await auth.verifyIdToken('<id-token-from-client>');
print('Decoded token:');
print(' - uid: ${decoded.uid}');
print(' - email: ${decoded.email}');
print(' - iss: ${decoded.iss}');
print('');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// revokeRefreshTokens + verifyIdToken with checkRevoked
try {
print('> Revoking refresh tokens for user...\n');
await auth.revokeRefreshTokens(uid);
print('Refresh tokens revoked\n');
print('> Verifying ID token with revocation check...\n');
final decoded = await auth.verifyIdToken(
'<id-token-from-client>',
checkRevoked: true,
);
print('Token is still valid: uid=${decoded.uid}\n');
} on FirebaseAuthAdminException catch (e) {
if (e.errorCode == AuthClientErrorCode.idTokenRevoked) {
print('> Token has been revoked — require re-authentication');
} else {
print('> Auth error: ${e.code} - ${e.message}');
}
} catch (e) {
print('> Error: $e');
}
}
Future<void> sessionCookieExample(FirebaseApp admin) async {
print('\n### Session Cookie Example ###\n');
final auth = admin.auth();
// createSessionCookie
try {
print('> Creating session cookie...\n');
final sessionCookie = await auth.createSessionCookie(
'<id-token-from-client>',
SessionCookieOptions(expiresIn: const Duration(days: 5).inMilliseconds),
);
print(
'Session cookie created (first 40 chars): '
'${sessionCookie.substring(0, 40)}...\n',
);
// verifySessionCookie
print('> Verifying session cookie...\n');
final decoded = await auth.verifySessionCookie(sessionCookie);
print('Session cookie valid: uid=${decoded.uid}\n');
} on FirebaseAuthAdminException catch (e) {
if (e.errorCode == AuthClientErrorCode.sessionCookieRevoked) {
print('> Session cookie has been revoked');
} else {
print('> Auth error: ${e.code} - ${e.message}');
}
} catch (e) {
print('> Error: $e');
}
}
Future<void> providerConfigExample(FirebaseApp admin) async {
print('\n### Provider Config Example ###\n');
final auth = admin.auth();
const oidcProviderId = 'oidc.my-provider';
const samlProviderId = 'saml.my-provider';
// createProviderConfig (OIDC)
try {
print('> Creating OIDC provider config...\n');
final config = await auth.createProviderConfig(
OIDCAuthProviderConfig(
providerId: oidcProviderId,
clientId: 'my-client-id',
issuer: 'https://accounts.google.com',
displayName: 'My OIDC Provider',
enabled: true,
),
);
print('OIDC provider created: ${config.providerId}\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// createProviderConfig (SAML)
try {
print('> Creating SAML provider config...\n');
final config = await auth.createProviderConfig(
SAMLAuthProviderConfig(
providerId: samlProviderId,
idpEntityId: 'https://idp.example.com',
ssoURL: 'https://idp.example.com/sso',
x509Certificates: [
'-----BEGIN CERTIFICATE-----\n...\n-----END CERTIFICATE-----',
],
rpEntityId: 'my-rp-entity-id',
displayName: 'My SAML Provider',
enabled: true,
),
);
print('SAML provider created: ${config.providerId}\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// getProviderConfig
try {
print('> Fetching OIDC provider config...\n');
final config = await auth.getProviderConfig(oidcProviderId);
print('Provider: ${config.providerId} — enabled: ${config.enabled}\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// updateProviderConfig
try {
print('> Updating OIDC provider config...\n');
final updated = await auth.updateProviderConfig(
oidcProviderId,
OIDCUpdateAuthProviderRequest(displayName: 'Updated OIDC Provider'),
);
print('Updated provider: ${updated.displayName}\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// listProviderConfigs
try {
print('> Listing OIDC provider configs...\n');
final result = await auth.listProviderConfigs(
AuthProviderConfigFilter.oidc(maxResults: 10),
);
print('Found ${result.providerConfigs.length} OIDC provider(s)');
if (result.pageToken != null) {
print('Next page token: ${result.pageToken}');
}
print('');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
// deleteProviderConfig
try {
print('> Deleting OIDC provider config...\n');
await auth.deleteProviderConfig(oidcProviderId);
print('OIDC provider deleted\n');
print('> Deleting SAML provider config...\n');
await auth.deleteProviderConfig(samlProviderId);
print('SAML provider deleted\n');
} on FirebaseAuthAdminException catch (e) {
print('> Auth error: ${e.code} - ${e.message}');
} catch (e) {
print('> Error: $e');
}
}