-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
method_channel_firebase_auth.dart
688 lines (599 loc) 路 21.5 KB
/
method_channel_firebase_auth.dart
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
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
// ignore_for_file: require_trailing_commas
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:async';
import 'dart:io' show Platform;
import 'package:_flutterfire_internals/_flutterfire_internals.dart';
import 'package:firebase_auth_platform_interface/src/method_channel/method_channel_multi_factor.dart';
import 'package:firebase_auth_platform_interface/src/method_channel/utils/convert_auth_provider.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../../firebase_auth_platform_interface.dart';
import 'method_channel_user.dart';
import 'method_channel_user_credential.dart';
import 'utils/exception.dart';
/// Method Channel delegate for [FirebaseAuthPlatform].
class MethodChannelFirebaseAuth extends FirebaseAuthPlatform {
/// The [MethodChannelFirebaseAuth] method channel.
static const MethodChannel channel = MethodChannel(
'plugins.flutter.io/firebase_auth',
);
/// Map of [MethodChannelFirebaseAuth] that can be get with Firebase App Name.
static Map<String, MethodChannelFirebaseAuth>
methodChannelFirebaseAuthInstances =
<String, MethodChannelFirebaseAuth>{};
static Map<String, MethodChannelMultiFactor> _multiFactorInstances =
<String, MethodChannelMultiFactor>{};
static final Map<String, StreamController<_ValueWrapper<UserPlatform>>>
_authStateChangesListeners =
<String, StreamController<_ValueWrapper<UserPlatform>>>{};
static final Map<String, StreamController<_ValueWrapper<UserPlatform>>>
_idTokenChangesListeners =
<String, StreamController<_ValueWrapper<UserPlatform>>>{};
static final Map<String, StreamController<_ValueWrapper<UserPlatform>>>
_userChangesListeners =
<String, StreamController<_ValueWrapper<UserPlatform>>>{};
StreamController<T> _createBroadcastStream<T>() {
return StreamController<T>.broadcast();
}
/// Returns a stub instance to allow the platform interface to access
/// the class instance statically.
static MethodChannelFirebaseAuth get instance {
return MethodChannelFirebaseAuth._();
}
/// Internal stub class initializer.
///
/// When the user code calls an auth method, the real instance is
/// then initialized via the [delegateFor] method.
MethodChannelFirebaseAuth._() : super(appInstance: null);
/// Creates a new instance with a given [FirebaseApp].
MethodChannelFirebaseAuth({required FirebaseApp app})
: super(appInstance: app) {
channel.invokeMethod<String>('Auth#registerIdTokenListener', {
'appName': app.name,
}).then((channelName) {
final events = EventChannel(channelName!, channel.codec);
events
.receiveGuardedBroadcastStream(onError: convertPlatformException)
.listen(
(arguments) {
_handleIdTokenChangesListener(app.name, arguments);
},
);
});
channel.invokeMethod<String>('Auth#registerAuthStateListener', {
'appName': app.name,
}).then((channelName) {
final events = EventChannel(channelName!, channel.codec);
events
.receiveGuardedBroadcastStream(onError: convertPlatformException)
.listen(
(arguments) {
_handleAuthStateChangesListener(app.name, arguments);
},
);
});
// Create a app instance broadcast stream for native listener events
_authStateChangesListeners[app.name] =
_createBroadcastStream<_ValueWrapper<UserPlatform>>();
_idTokenChangesListeners[app.name] =
_createBroadcastStream<_ValueWrapper<UserPlatform>>();
_userChangesListeners[app.name] =
_createBroadcastStream<_ValueWrapper<UserPlatform>>();
}
@override
UserPlatform? currentUser;
@override
String? languageCode;
@override
void sendAuthChangesEvent(String appName, UserPlatform? userPlatform) {
assert(_userChangesListeners[appName] != null);
_userChangesListeners[appName]!.add(_ValueWrapper(userPlatform));
}
/// Handles any incoming [authChanges] listener events.
// Duplicate setting of [currentUser] in [_handleAuthStateChangesListener] & [_handleIdTokenChangesListener]
// as iOS & Android do not guarantee correct ordering
Future<void> _handleAuthStateChangesListener(
String appName, Map<dynamic, dynamic> arguments) async {
// ignore: close_sinks
final streamController = _authStateChangesListeners[appName]!;
MethodChannelFirebaseAuth instance =
methodChannelFirebaseAuthInstances[appName]!;
MethodChannelMultiFactor? multiFactorInstance =
_multiFactorInstances[appName];
if (multiFactorInstance == null) {
multiFactorInstance = MethodChannelMultiFactor(instance);
_multiFactorInstances[appName] = multiFactorInstance;
}
final userMap = arguments['user'];
if (userMap == null) {
instance.currentUser = null;
streamController.add(const _ValueWrapper.absent());
} else {
final MethodChannelUser user = MethodChannelUser(
instance, multiFactorInstance, userMap.cast<String, dynamic>());
// TODO(rousselGit): should this logic be moved to the setter instead?
instance.currentUser = user;
streamController.add(_ValueWrapper(instance.currentUser));
}
}
/// Handles any incoming [idTokenChanges] listener events.
///
/// This handler also manages the [currentUser] along with sending events
/// to any [userChanges] stream subscribers.
Future<void> _handleIdTokenChangesListener(
String appName, Map<dynamic, dynamic> arguments) async {
final StreamController<_ValueWrapper<UserPlatform>>
// ignore: close_sinks
idTokenStreamController = _idTokenChangesListeners[appName]!;
final StreamController<_ValueWrapper<UserPlatform>>
// ignore: close_sinks
userChangesStreamController = _userChangesListeners[appName]!;
MethodChannelFirebaseAuth instance =
methodChannelFirebaseAuthInstances[appName]!;
MethodChannelMultiFactor? multiFactorInstance =
_multiFactorInstances[appName];
if (multiFactorInstance == null) {
multiFactorInstance = MethodChannelMultiFactor(instance);
_multiFactorInstances[appName] = multiFactorInstance;
}
final userMap = arguments['user'];
if (userMap == null) {
instance.currentUser = null;
idTokenStreamController.add(const _ValueWrapper.absent());
userChangesStreamController.add(const _ValueWrapper.absent());
} else {
final MethodChannelUser user = MethodChannelUser(
instance, multiFactorInstance, userMap.cast<String, dynamic>());
// TODO(rousselGit): should this logic be moved to the setter instead?
instance.currentUser = user;
idTokenStreamController.add(_ValueWrapper(user));
userChangesStreamController.add(_ValueWrapper(user));
}
}
/// Attaches generic default values to method channel arguments.
Map<String, dynamic> _withChannelDefaults(Map<String, dynamic> other) {
return {
'appName': app.name,
'tenantId': tenantId,
}..addAll(other);
}
/// Gets a [FirebaseAuthPlatform] with specific arguments such as a different
/// [FirebaseApp].
///
/// Instances are cached and reused for incoming event handlers.
@override
FirebaseAuthPlatform delegateFor(
{required FirebaseApp app, Persistence? persistence}) {
return methodChannelFirebaseAuthInstances.putIfAbsent(app.name, () {
return MethodChannelFirebaseAuth(app: app);
});
}
@override
MethodChannelFirebaseAuth setInitialValues({
Map<String, dynamic>? currentUser,
String? languageCode,
}) {
if (currentUser != null) {
final multiFactor = MethodChannelMultiFactor(this);
this.currentUser = MethodChannelUser(this, multiFactor, currentUser);
}
this.languageCode = languageCode;
return this;
}
@override
Future<void> useAuthEmulator(String host, int port) async {
try {
await channel.invokeMethod<void>(
'Auth#useEmulator',
_withChannelDefaults({
'host': host,
'port': port,
}));
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> applyActionCode(String code) async {
try {
await channel.invokeMethod<void>(
'Auth#applyActionCode',
_withChannelDefaults({
'code': code,
}));
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<ActionCodeInfo> checkActionCode(String code) async {
try {
Map<String, dynamic> result =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#checkActionCode',
_withChannelDefaults({
'code': code,
})))!;
return ActionCodeInfo(
operation: result['operation'],
data: Map<String, dynamic>.from(result['data']),
);
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> confirmPasswordReset(String code, String newPassword) async {
try {
await channel.invokeMethod<void>(
'Auth#confirmPasswordReset',
_withChannelDefaults({
'code': code,
'newPassword': newPassword,
}));
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<UserCredentialPlatform> createUserWithEmailAndPassword(
String email, String password) async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#createUserWithEmailAndPassword',
_withChannelDefaults({
'email': email,
'password': password,
})))!;
MethodChannelUserCredential userCredential =
MethodChannelUserCredential(this, data);
currentUser = userCredential.user;
return userCredential;
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<List<String>> fetchSignInMethodsForEmail(String email) async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#fetchSignInMethodsForEmail',
_withChannelDefaults({
'email': email,
})))!;
return List<String>.from(data['providers']);
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Stream<UserPlatform?> authStateChanges() async* {
yield currentUser;
yield* _authStateChangesListeners[app.name]!
.stream
.map((event) => event.value);
}
@override
Stream<UserPlatform?> idTokenChanges() async* {
yield currentUser;
yield* _idTokenChangesListeners[app.name]!
.stream
.map((event) => event.value);
}
@override
Stream<UserPlatform?> userChanges() async* {
yield currentUser;
yield* _userChangesListeners[app.name]!.stream.map((event) => event.value);
}
@override
Future<void> sendPasswordResetEmail(
String email, [
ActionCodeSettings? actionCodeSettings,
]) async {
try {
await channel.invokeMethod<void>(
'Auth#sendPasswordResetEmail',
_withChannelDefaults({
'email': email,
'actionCodeSettings': actionCodeSettings?.asMap(),
}));
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> sendSignInLinkToEmail(
String email,
ActionCodeSettings actionCodeSettings,
) async {
try {
await channel.invokeMethod<void>(
'Auth#sendSignInLinkToEmail',
_withChannelDefaults({
'email': email,
'actionCodeSettings': actionCodeSettings.asMap(),
}));
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> setLanguageCode(String? languageCode) async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#setLanguageCode',
_withChannelDefaults({
'appName': app.name,
'languageCode': languageCode,
})))!;
this.languageCode = data['languageCode'];
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> setSettings({
bool? appVerificationDisabledForTesting,
String? userAccessGroup,
String? phoneNumber,
String? smsCode,
bool? forceRecaptchaFlow,
}) async {
if (phoneNumber != null && smsCode == null ||
phoneNumber == null && smsCode != null) {
throw ArgumentError(
"The [smsCode] and the [phoneNumber] must both be either 'null' or a 'String''.",
);
}
// argument for every platform
var arguments = <String, dynamic>{
'appVerificationDisabledForTesting': appVerificationDisabledForTesting,
};
if (Platform.isIOS || Platform.isMacOS) {
arguments['userAccessGroup'] = userAccessGroup;
}
if (Platform.isAndroid) {
if (phoneNumber != null && smsCode != null) {
arguments['phoneNumber'] = phoneNumber;
arguments['smsCode'] = smsCode;
}
if (forceRecaptchaFlow != null) {
arguments['forceRecaptchaFlow'] = forceRecaptchaFlow;
}
}
try {
await channel.invokeMethod(
'Auth#setSettings', _withChannelDefaults(arguments));
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> setPersistence(Persistence persistence) {
throw UnimplementedError(
'setPersistence() is only supported on web based platforms');
}
@override
Future<UserCredentialPlatform> signInAnonymously() async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#signInAnonymously', _withChannelDefaults({})))!;
MethodChannelUserCredential userCredential =
MethodChannelUserCredential(this, data);
currentUser = userCredential.user;
return userCredential;
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<UserCredentialPlatform> signInWithCredential(
AuthCredential credential,
) async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#signInWithCredential',
_withChannelDefaults({
'credential': credential.asMap(),
})))!;
MethodChannelUserCredential userCredential =
MethodChannelUserCredential(this, data);
currentUser = userCredential.user;
return userCredential;
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<UserCredentialPlatform> signInWithCustomToken(String token) async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#signInWithCustomToken',
_withChannelDefaults({
'token': token,
})))!;
MethodChannelUserCredential userCredential =
MethodChannelUserCredential(this, data);
currentUser = userCredential.user;
return userCredential;
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<UserCredentialPlatform> signInWithEmailAndPassword(
String email, String password) async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#signInWithEmailAndPassword',
_withChannelDefaults({
'email': email,
'password': password,
})))!;
MethodChannelUserCredential userCredential =
MethodChannelUserCredential(this, data);
currentUser = userCredential.user;
return userCredential;
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<UserCredentialPlatform> signInWithEmailLink(
String email, String emailLink) async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#signInWithEmailLink',
_withChannelDefaults({
'email': email,
'emailLink': emailLink,
})))!;
MethodChannelUserCredential userCredential =
MethodChannelUserCredential(this, data);
currentUser = userCredential.user;
return userCredential;
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<UserCredentialPlatform> signInWithPopup(AuthProvider provider) {
throw UnimplementedError(
'signInWithPopup() is only supported on web based platforms',
);
}
@override
Future<void> signInWithRedirect(AuthProvider provider) {
throw UnimplementedError(
'signInWithRedirect() is only supported on web based platforms',
);
}
@override
Future<void> signOut() async {
try {
await channel.invokeMethod<void>(
'Auth#signOut', _withChannelDefaults({}));
currentUser = null;
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<String> verifyPasswordResetCode(String code) async {
try {
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#verifyPasswordResetCode',
_withChannelDefaults({
'code': code,
})))!;
return data['email'];
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<UserCredentialPlatform> signInWithProvider(
AuthProvider provider,
) async {
try {
// To extract scopes and custom parameters from the provider
final convertedProvider = convertToOAuthProvider(provider);
Map<String, dynamic> data =
(await channel.invokeMapMethod<String, dynamic>(
'Auth#signInWithProvider',
_withChannelDefaults({
'signInProvider': convertedProvider.providerId,
if (convertedProvider is OAuthProvider) ...{
'scopes': convertedProvider.scopes,
'customParameters': convertedProvider.parameters
},
})))!;
MethodChannelUserCredential userCredential =
MethodChannelUserCredential(this, data);
currentUser = userCredential.user;
return userCredential;
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
@override
Future<void> verifyPhoneNumber({
String? phoneNumber,
MultiFactorInfo? multiFactorInfo,
required PhoneVerificationCompleted verificationCompleted,
required PhoneVerificationFailed verificationFailed,
required PhoneCodeSent codeSent,
required PhoneCodeAutoRetrievalTimeout codeAutoRetrievalTimeout,
String? autoRetrievedSmsCodeForTesting,
Duration timeout = const Duration(seconds: 30),
int? forceResendingToken,
MultiFactorSession? multiFactorSession,
}) async {
if (defaultTargetPlatform == TargetPlatform.macOS) {
throw UnimplementedError(
'verifyPhoneNumber() is not available on MacOS platforms.',
);
}
try {
final eventChannelName = await channel.invokeMethod<String>(
'Auth#verifyPhoneNumber',
_withChannelDefaults({
if (phoneNumber != null) 'phoneNumber': phoneNumber,
if (multiFactorInfo?.uid != null)
'multiFactorInfo': multiFactorInfo?.uid,
'timeout': timeout.inMilliseconds,
'forceResendingToken': forceResendingToken,
'autoRetrievedSmsCodeForTesting': autoRetrievedSmsCodeForTesting,
if (multiFactorSession?.id != null)
'multiFactorSessionId': multiFactorSession!.id,
}));
EventChannel(eventChannelName!)
.receiveGuardedBroadcastStream(onError: convertPlatformException)
.listen((arguments) {
final name = arguments['name'];
if (name == 'Auth#phoneVerificationCompleted') {
final int token = arguments['token'];
final String? smsCode = arguments['smsCode'];
PhoneAuthCredential phoneAuthCredential =
PhoneAuthProvider.credentialFromToken(token, smsCode: smsCode);
verificationCompleted(phoneAuthCredential);
} else if (name == 'Auth#phoneVerificationFailed') {
final Map<dynamic, dynamic>? error = arguments['error'];
final Map<dynamic, dynamic>? details = error?['details'];
FirebaseAuthException exception = FirebaseAuthException(
message: details != null ? details['message'] : error?['message'],
code: details != null ? details['code'] : 'unknown',
);
verificationFailed(exception);
} else if (name == 'Auth#phoneCodeSent') {
final String verificationId = arguments['verificationId'];
final int? forceResendingToken = arguments['forceResendingToken'];
codeSent(verificationId, forceResendingToken);
} else if (name == 'Auth#phoneCodeAutoRetrievalTimeout') {
final String verificationId = arguments['verificationId'];
codeAutoRetrievalTimeout(verificationId);
}
});
} catch (e, stack) {
convertPlatformException(e, stack);
}
}
}
/// Simple helper class to make nullable values transferable through StreamControllers.
class _ValueWrapper<T> {
const _ValueWrapper(this.value);
const _ValueWrapper.absent() : value = null;
final T? value;
}