-
Notifications
You must be signed in to change notification settings - Fork 74
Expand file tree
/
Copy pathfirebase.dart
More file actions
652 lines (610 loc) · 19.3 KB
/
Copy pathfirebase.dart
File metadata and controls
652 lines (610 loc) · 19.3 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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
/*
* Copyright (c) 2016-present Invertase Limited & Contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this library except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import 'dart:convert';
import 'dart:io';
import 'package:ansi_styles/ansi_styles.dart';
import 'package:http/http.dart' as http;
import 'package:path/path.dart' as path;
import 'common/global.dart';
import 'common/strings.dart';
import 'common/utils.dart';
import 'firebase/firebase_app.dart';
import 'firebase/firebase_project.dart';
/// Simple check to verify Firebase Tools CLI is installed.
bool? _existsCache;
Future<bool> exists() async {
if (_existsCache != null) {
return _existsCache!;
}
final process = await Process.run(
'firebase',
['--version'],
runInShell: true,
);
return _existsCache = process.exitCode == 0;
}
/// Tries to read the default Firebase project id from the
/// .firbaserc file at the root of the dart project if it exists.
Future<String?> getDefaultFirebaseProjectId() async {
final firebaseRcFile = File(firebaseRcPathForDirectory(Directory.current));
if (!firebaseRcFile.existsSync()) return null;
final fileContents = firebaseRcFile.readAsStringSync();
try {
final jsonMap =
const JsonDecoder().convert(fileContents) as Map<String, dynamic>;
if (jsonMap['projects'] != null &&
(jsonMap['projects'] as Map)['default'] != null) {
return (jsonMap['projects'] as Map)['default'] as String;
}
} catch (e) {
return null;
}
return null;
}
/// Executes a command on the Firebase CLI and returns
/// the result as a parsed JSON Map.
/// Example:
/// final result = await runFirebaseCommand(['projects:list']);
/// print(result);
Future<Map<String, dynamic>> runFirebaseCommand(
List<String> commandAndArgs, {
String? project,
String? account,
String? serviceAccount,
}) async {
final cliExists = await exists();
if (!cliExists) {
throw FirebaseCommandException(
'--version',
logMissingFirebaseCli,
);
}
final workingDirectoryPath = Directory.current.path;
final execArgs = [
...commandAndArgs,
'--json',
if (project != null) '--project=$project',
if (account != null) '--account=$account',
];
ProcessResult process;
try {
process = await Process.run(
'firebase',
execArgs,
workingDirectory: workingDirectoryPath,
environment: {
if (serviceAccount != null)
'GOOGLE_APPLICATION_CREDENTIALS': serviceAccount,
},
runInShell: true,
);
} catch (e) {
if (debugMode) {
logger.stdout(
'Firebase CLI:`runFirebaseCommand()`:Process.run(`firebase`):execArgs: $execArgs',
);
}
rethrow;
}
final jsonString = firebaseCLIJsonParse(process.stdout.toString());
Map<String, dynamic> commandResult;
try {
// 400 projects is roughly 134,000 characters. Roughly 334 characters per project.
const characterLimit = 130000;
if (jsonString.length > characterLimit) {
// If the JSON string is large, write it to a temporary file
final tempFile =
File('${Directory.systemTemp.path}/firebase_output.json');
await tempFile.writeAsString(jsonString);
// Read from the temporary file to create a Dart object
final tempFileContent = await tempFile.readAsString();
final jsonObject = const JsonDecoder().convert(tempFileContent);
commandResult = Map<String, dynamic>.from(jsonObject);
// Delete the temporary file
await tempFile.delete();
} else {
commandResult = Map<String, dynamic>.from(
const JsonDecoder().convert(jsonString) as Map,
);
}
} catch (e) {
if (debugMode) {
logger.stdout(
'Firebase CLI:`runFirebaseCommand()`:JsonDecoder().convert: $jsonString',
);
}
rethrow;
}
if (commandResult['status'] == 'success') {
return commandResult;
}
throw FirebaseCommandException(
execArgs.join(' '),
commandResult['error'] as String,
);
}
/// Get all available Firebase projects for the authenticated CLI user
/// or for the account provided.
Future<List<FirebaseProject>> getProjects({
String? account,
String? token,
String? serviceAccount,
}) async {
final response = await runFirebaseCommand(
[
'projects:list',
if (token != null) '--token=$token',
],
account: account,
serviceAccount: serviceAccount,
);
try {
final result = List<Map<String, dynamic>>.from(response['result'] as List);
return result
.map<FirebaseProject>(
(Map<String, dynamic> e) =>
FirebaseProject.fromJson(Map<String, dynamic>.from(e)),
)
.where((project) => project.state == 'ACTIVE')
.toList();
} catch (e) {
if (debugMode) {
logger.stdout('Firebase CLI:`getProjects()`:response: $response');
}
rethrow;
}
}
/// Create a new [FirebaseProject].
Future<FirebaseProject> createProject({
required String projectId,
String? displayName,
String? account,
String? token,
String? serviceAccount,
}) async {
final response = await runFirebaseCommand(
[
'projects:create',
projectId,
if (displayName != null) displayName,
if (token != null) '--token=$token',
],
account: account,
serviceAccount: serviceAccount,
);
final result = Map<String, dynamic>.from(response['result'] as Map);
return FirebaseProject.fromJson(<String, dynamic>{
...Map<String, dynamic>.from(result),
'state': 'ACTIVE',
});
}
/// Get registered Firebase apps for a project.
Future<List<FirebaseApp>> getApps({
required String project,
String? account,
String? platform,
String? token,
String? serviceAccount,
}) async {
if (platform != null) _assertFirebaseSupportedPlatform(platform);
final response = await runFirebaseCommand(
[
'apps:list',
if (platform != null) platform,
if (token != null) '--token=$token',
],
project: project,
account: account,
serviceAccount: serviceAccount,
);
final result = List<Map<String, dynamic>>.from(response['result'] as List);
return result
.map<FirebaseApp>(
(Map<String, dynamic> e) =>
FirebaseApp.fromJson(Map<String, dynamic>.from(e)),
)
.toList();
}
class FirebaseAppSdkConfig {
FirebaseAppSdkConfig({
required this.fileName,
required this.fileContents,
});
final String fileName;
final String fileContents;
}
/// Get registered Firebase apps for a project.
Future<FirebaseAppSdkConfig> getAppSdkConfig({
required String appId,
required String platform,
String? account,
String? token,
String? serviceAccount,
}) async {
final platformFirebase = platform == kMacos ? kIos : platform;
_assertFirebaseSupportedPlatform(platformFirebase);
final response = await runFirebaseCommand(
[
'apps:sdkconfig',
platformFirebase,
appId,
if (token != null) '--token=$token',
],
account: account,
serviceAccount: serviceAccount,
);
final result = Map<String, dynamic>.from(response['result'] as Map);
final fileContents = result['fileContents'] as String;
final fileName = result['fileName'] as String;
return FirebaseAppSdkConfig(
fileName: fileName,
fileContents: fileContents,
);
}
Future<String?> getRecaptchaEnterpriseSiteKey({
required String projectNumber,
required String appId,
String? accessToken,
http.Client? client,
}) async {
try {
accessToken ??= await getAccessToken();
} catch (e) {
if (debugMode) {
logger.stdout(
'Firebase App Check:`getRecaptchaEnterpriseSiteKey()`:getAccessToken: $e',
);
}
return null;
}
final httpClient = client ?? http.Client();
late http.Response response;
try {
response = await httpClient.get(
Uri.https(
'firebaseappcheck.googleapis.com',
'/v1/projects/$projectNumber/apps/$appId/recaptchaEnterpriseConfig',
),
headers: {'Authorization': 'Bearer $accessToken'},
);
} catch (e) {
if (debugMode) {
logger.stdout(
'Firebase App Check:`getRecaptchaEnterpriseSiteKey()`:http.get: $e',
);
}
return null;
} finally {
if (client == null) {
httpClient.close();
}
}
if (response.statusCode == 200) {
final json = jsonDecode(response.body) as Map<String, dynamic>;
final siteKey = json['siteKey'] as String?;
return siteKey == null || siteKey.isEmpty ? null : siteKey;
}
if (debugMode && response.statusCode != 404) {
logger.stdout(
'Firebase App Check:`getRecaptchaEnterpriseSiteKey()`: '
'statusCode: ${response.statusCode}, response: ${response.body}',
);
}
return null;
}
void _assertFirebaseSupportedPlatform(String platformIdentifier) {
if (![kAndroid, kWeb, kIos].contains(platformIdentifier)) {
throw FirebasePlatformNotSupportedException(platformIdentifier);
}
}
Future<FirebaseApp> findOrCreateFirebaseApp({
required String platform,
required String displayName,
required String project,
String? packageNameOrBundleIdentifier,
String? account,
String? token,
String? serviceAccount,
// used for web and windows.
String? webAppId,
}) async {
var foundFirebaseApp = false;
final displayNameWithPlatform = '$displayName ($platform)';
var platformFirebase = platform;
if (platformFirebase == kMacos) platformFirebase = kIos;
if (platformFirebase == kWindows) platformFirebase = kWeb;
if (platformFirebase == kLinux) platformFirebase = kWeb;
_assertFirebaseSupportedPlatform(platformFirebase);
final fetchingAppsSpinner = spinner(
(done) {
final loggingAppName =
packageNameOrBundleIdentifier ?? webAppId ?? displayNameWithPlatform;
if (!done) {
return AnsiStyles.bold(
'Fetching registered ${AnsiStyles.cyan(platform)} Firebase apps for project ${AnsiStyles.cyan(project)}',
);
}
if (!foundFirebaseApp) {
return AnsiStyles.bold(
'Firebase ${AnsiStyles.cyan(platform)} app ${AnsiStyles.cyan(loggingAppName)} is not registered on Firebase project ${AnsiStyles.cyan(project)}.',
);
}
return AnsiStyles.bold(
'Firebase ${AnsiStyles.cyan(platform)} app ${AnsiStyles.cyan(loggingAppName)} registered.',
);
},
);
final unfilteredFirebaseApps = await getApps(
project: project,
account: account,
platform: platformFirebase,
token: token,
serviceAccount: serviceAccount,
);
Iterable<FirebaseApp> filteredFirebaseApps;
if (platform == kWeb || platform == kWindows) {
if (webAppId != null) {
final flagOption = platform == kWeb ? kWebAppIdFlag : kWindowsAppIdFlag;
// Find provided web app id for web and windows, otherwise, throw Exception that it doesn't exist
final webApp = unfilteredFirebaseApps.firstWhere(
(firebaseApp) => firebaseApp.appId == webAppId,
orElse: () {
fetchingAppsSpinner.done();
throw Exception(
'The $flagOption: $webAppId provided does not match the web app id of any existing Firebase app.',
);
},
);
foundFirebaseApp = true;
fetchingAppsSpinner.done();
return webApp;
}
// Find web app for web and windows using display name with this signature: "flutter_app_name (platform)
filteredFirebaseApps = unfilteredFirebaseApps.where(
(firebaseApp) {
if (firebaseApp.displayName == displayNameWithPlatform) {
return true;
}
return false;
},
);
// Find any for that platform if no web app found with display name
if (filteredFirebaseApps.isEmpty) {
filteredFirebaseApps = unfilteredFirebaseApps.where(
(firebaseApp) {
return firebaseApp.platform == platform;
},
);
}
} else {
filteredFirebaseApps = unfilteredFirebaseApps.where(
(firebaseApp) {
if (packageNameOrBundleIdentifier != null) {
return firebaseApp.packageNameOrBundleIdentifier ==
packageNameOrBundleIdentifier &&
firebaseApp.platform == platformFirebase;
}
return false;
},
);
}
foundFirebaseApp = filteredFirebaseApps.isNotEmpty;
fetchingAppsSpinner.done();
if (foundFirebaseApp) {
return filteredFirebaseApps.first;
}
// Existing app not found so we need to create it.
Future<FirebaseApp> createFirebaseAppFuture;
switch (platformFirebase) {
case kAndroid:
createFirebaseAppFuture = createAndroidApp(
project: project,
displayName: displayNameWithPlatform,
packageName: packageNameOrBundleIdentifier!,
account: account,
token: token,
serviceAccount: serviceAccount,
);
break;
case kIos:
createFirebaseAppFuture = createAppleApp(
project: project,
displayName: displayNameWithPlatform,
bundleId: packageNameOrBundleIdentifier!,
account: account,
token: token,
serviceAccount: serviceAccount,
);
break;
case kWeb:
// This is used to also create windows app, Firebase has no concept of a windows app
createFirebaseAppFuture = createWebApp(
project: project,
displayName: displayNameWithPlatform,
account: account,
token: token,
serviceAccount: serviceAccount,
);
break;
default:
throw FlutterPlatformNotSupportedException(platform);
}
final creatingAppSpinner = spinner(
(done) {
if (!done) {
return AnsiStyles.bold(
'Registering new Firebase ${AnsiStyles.cyan(platform)} app on Firebase project ${AnsiStyles.cyan(project)}.',
);
}
return AnsiStyles.bold(
'Registered a new Firebase ${AnsiStyles.cyan(platform)} app on Firebase project ${AnsiStyles.cyan(project)}.',
);
},
);
final firebaseApp = await createFirebaseAppFuture;
creatingAppSpinner.done();
return firebaseApp;
}
/// Create a new web [FirebaseApp].
Future<FirebaseApp> createWebApp({
required String project,
required String displayName,
String? account,
String? token,
String? serviceAccount,
}) async {
final response = await runFirebaseCommand(
['apps:create', 'web', displayName, if (token != null) '--token=$token'],
project: project,
account: account,
serviceAccount: serviceAccount,
);
final result = Map<String, dynamic>.from(response['result'] as Map);
return FirebaseApp.fromJson(<String, dynamic>{
...Map<String, dynamic>.from(result),
'platform': kWeb,
});
}
/// Create a new android [FirebaseApp].
Future<FirebaseApp> createAndroidApp({
required String project,
required String displayName,
required String packageName,
String? account,
String? token,
String? serviceAccount,
}) async {
final response = await runFirebaseCommand(
[
'apps:create',
'android',
displayName,
'--package-name=$packageName',
if (token != null) '--token=$token',
],
project: project,
account: account,
serviceAccount: serviceAccount,
);
final result = Map<String, dynamic>.from(response['result'] as Map);
return FirebaseApp.fromJson(<String, dynamic>{
...Map<String, dynamic>.from(result),
'platform': kAndroid,
});
}
/// Create a new iOS or macOS [FirebaseApp].
Future<FirebaseApp> createAppleApp({
required String project,
required String displayName,
required String bundleId,
String? account,
String? token,
String? serviceAccount,
}) async {
final response = await runFirebaseCommand(
[
'apps:create',
'ios',
displayName,
'--bundle-id=$bundleId',
if (token != null) '--token=$token',
],
project: project,
account: account,
serviceAccount: serviceAccount,
);
final result = Map<String, dynamic>.from(response['result'] as Map);
return FirebaseApp.fromJson(<String, dynamic>{
...Map<String, dynamic>.from(result),
'platform': kIos,
});
}
Future<String> getAccessToken() async {
// Use refresh token to get access token, cannot simply use access token found in "firebase-tools.json"
final homeDir = Platform.isWindows
? Platform.environment['UserProfile']!
: Platform.environment['HOME']!;
// Path to 'firebase-tools.json'
final configPath =
path.join(homeDir, '.config', 'configstore', 'firebase-tools.json');
final configFile = File(configPath);
if (!configFile.existsSync()) {
throw Exception(
'Failed to find "firebase-tools.json" file, it should be located at "$configPath',
);
}
final map = await configFile.readAsString();
final configJson = jsonDecode(map) as Map<String, dynamic>;
final tokens = configJson['tokens'] as Map<String, dynamic>;
final refreshToken = tokens['refresh_token'] as String;
final response = await http.post(
Uri.parse('https://oauth2.googleapis.com/token'),
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
// Values for obtaining the access token are taken from the Firebase CLI source code: https://github.com/firebase/firebase-tools/blob/b14b5f38fe23da6543778a588811b0e2391427c0/src/api.ts#L18
body:
'grant_type=refresh_token&client_id=563584335869-fgrhgmd47bqnekij5i8b5pr03ho849e6.apps.googleusercontent.com&client_secret=j9iVZfS8kkCEFUPaAeJV0sAi&refresh_token=$refreshToken',
);
if (response.statusCode == 200) {
final json = jsonDecode(response.body) as Map<String, dynamic>;
return json['access_token'] as String;
} else {
throw Exception(
'Failed to obtain an access token for making Firebase Management REST API requests. Status code: ${response.statusCode}. Response body: ${response.body}',
);
}
}
// Return string value of "GoogleService-Info.plist" or "google-services.json" file for relevant platform
Future<String> getServiceFileContent(
String projectId,
String appId,
String accessToken,
String platform,
) async {
String? uri;
if (platform == kIos || platform == kMacos) {
uri =
'https://firebase.googleapis.com/v1beta1/projects/$projectId/iosApps/$appId/config';
} else if (platform == kAndroid) {
uri =
'https://firebase.googleapis.com/v1beta1/projects/$projectId/androidApps/$appId/config';
} else {
throw ServiceFileException(
platform,
'Invalid platform: $platform. Use $kIos, $kAndroid or $kMacos to write service file content.',
);
}
final response = await http.get(
Uri.parse(
uri,
),
headers: {'Authorization': 'Bearer $accessToken'},
);
if (response.statusCode == 200) {
final json = jsonDecode(response.body) as Map<String, dynamic>;
final decodedBytes = base64.decode(json['configFileContents'] as String);
final decodedContent = utf8.decode(decodedBytes);
return decodedContent;
} else {
final serviceFileName = platform == kIos || platform == kMacos
? appleServiceFileName
: androidServiceFileName;
throw ServiceFileException(
platform,
'Failed to obtain the service file: $serviceFileName for $platform. Response code: ${response.statusCode}. Response body: ${response.body}',
);
}
}