/
FLTFirebaseAuthPlugin.m
1897 lines (1645 loc) 路 76.9 KB
/
FLTFirebaseAuthPlugin.m
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
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2020 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 <Firebase/Firebase.h>
#import <TargetConditionals.h>
#import <firebase_core/FLTFirebasePluginRegistry.h>
#import "Private/FLTAuthStateChannelStreamHandler.h"
#import "Private/FLTIdTokenChannelStreamHandler.h"
#import "Private/FLTPhoneNumberVerificationStreamHandler.h"
#import "Public/CustomPigeonHeader.h"
#import "Public/FLTFirebaseAuthPlugin.h"
@import CommonCrypto;
#import <AuthenticationServices/AuthenticationServices.h>
NSString *const kFLTFirebaseAuthChannelName = @"plugins.flutter.io/firebase_auth";
// Argument Keys
NSString *const kAppName = @"appName";
// Provider type keys.
NSString *const kSignInMethodPassword = @"password";
NSString *const kSignInMethodEmailLink = @"emailLink";
NSString *const kSignInMethodFacebook = @"facebook.com";
NSString *const kSignInMethodGoogle = @"google.com";
NSString *const kSignInMethodTwitter = @"twitter.com";
NSString *const kSignInMethodGithub = @"github.com";
NSString *const kSignInMethodApple = @"apple.com";
NSString *const kSignInMethodPhone = @"phone";
NSString *const kSignInMethodOAuth = @"oauth";
// Credential argument keys.
NSString *const kArgumentCredential = @"credential";
NSString *const kArgumentProviderId = @"providerId";
NSString *const kArgumentProviderScope = @"scopes";
NSString *const kArgumentProviderCustomParameters = @"customParameters";
NSString *const kArgumentSignInMethod = @"signInMethod";
NSString *const kArgumentSecret = @"secret";
NSString *const kArgumentIdToken = @"idToken";
NSString *const kArgumentAccessToken = @"accessToken";
NSString *const kArgumentRawNonce = @"rawNonce";
NSString *const kArgumentEmail = @"email";
NSString *const kArgumentCode = @"code";
NSString *const kArgumentNewEmail = @"newEmail";
NSString *const kArgumentEmailLink = kSignInMethodEmailLink;
NSString *const kArgumentToken = @"token";
NSString *const kArgumentVerificationId = @"verificationId";
NSString *const kArgumentSmsCode = @"smsCode";
NSString *const kArgumentActionCodeSettings = @"actionCodeSettings";
// MultiFactor
NSString *const kArgumentMultiFactorHints = @"multiFactorHints";
NSString *const kArgumentMultiFactorSessionId = @"multiFactorSessionId";
NSString *const kArgumentMultiFactorResolverId = @"multiFactorResolverId";
NSString *const kArgumentMultiFactorInfo = @"multiFactorInfo";
// Manual error codes & messages.
NSString *const kErrCodeNoCurrentUser = @"no-current-user";
NSString *const kErrMsgNoCurrentUser = @"No user currently signed in.";
NSString *const kErrCodeInvalidCredential = @"invalid-credential";
NSString *const kErrMsgInvalidCredential =
@"The supplied auth credential is malformed, has expired or is not "
@"currently supported.";
@interface FLTFirebaseAuthPlugin ()
@property(nonatomic, retain) NSObject<FlutterBinaryMessenger> *messenger;
@property(strong, nonatomic) FIROAuthProvider *authProvider;
// Used to keep the user who wants to link with Apple Sign In
@property(strong, nonatomic) FIRUser *linkWithAppleUser;
@property(strong, nonatomic) NSString *currentNonce;
@property(strong, nonatomic) FLTFirebaseMethodCallResult *appleResult;
@property(strong, nonatomic) id appleArguments;
@end
@implementation FLTFirebaseAuthPlugin {
// Used for caching credentials between Method Channel method calls.
NSMutableDictionary<NSNumber *, FIRAuthCredential *> *_credentials;
#if TARGET_OS_IPHONE
// Map an id to a MultiFactorSession object.
NSMutableDictionary<NSString *, FIRMultiFactorSession *> *_multiFactorSessionMap;
// Map an id to a MultiFactorResolver object.
NSMutableDictionary<NSString *, FIRMultiFactorResolver *> *_multiFactorResolverMap;
#endif
NSObject<FlutterBinaryMessenger> *_binaryMessenger;
NSMutableDictionary<NSString *, FlutterEventChannel *> *_eventChannels;
NSMutableDictionary<NSString *, NSObject<FlutterStreamHandler> *> *_streamHandlers;
NSData *_apnsToken;
}
#pragma mark - FlutterPlugin
- (instancetype)init:(NSObject<FlutterBinaryMessenger> *)messenger {
self = [super init];
if (self) {
[[FLTFirebasePluginRegistry sharedInstance] registerFirebasePlugin:self];
_credentials = [NSMutableDictionary<NSNumber *, FIRAuthCredential *> dictionary];
_binaryMessenger = messenger;
_eventChannels = [NSMutableDictionary dictionary];
_streamHandlers = [NSMutableDictionary dictionary];
#if TARGET_OS_IPHONE
_multiFactorSessionMap = [NSMutableDictionary dictionary];
_multiFactorResolverMap = [NSMutableDictionary dictionary];
#endif
}
return self;
}
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
FlutterMethodChannel *channel =
[FlutterMethodChannel methodChannelWithName:kFLTFirebaseAuthChannelName
binaryMessenger:[registrar messenger]];
FLTFirebaseAuthPlugin *instance = [[FLTFirebaseAuthPlugin alloc] init:registrar.messenger];
[registrar addMethodCallDelegate:instance channel:channel];
#if TARGET_OS_OSX
// TODO(Salakar): Publish does not exist on MacOS version of
// FlutterPluginRegistrar.
// TODO(Salakar): addApplicationDelegate does not exist on MacOS version of
// FlutterPluginRegistrar. (https://github.com/flutter/flutter/issues/41471)
#else
[registrar publish:instance];
[registrar addApplicationDelegate:instance];
MultiFactorUserHostApiSetup(registrar.messenger, instance);
MultiFactoResolverHostApiSetup(registrar.messenger, instance);
#endif
}
- (void)cleanupWithCompletion:(void (^)(void))completion {
// Cleanup credentials.
[_credentials removeAllObjects];
for (FlutterEventChannel *channel in self->_eventChannels.allValues) {
[channel setStreamHandler:nil];
}
[self->_eventChannels removeAllObjects];
for (NSObject<FlutterStreamHandler> *handler in self->_streamHandlers.allValues) {
[handler onCancelWithArguments:nil];
}
[self->_streamHandlers removeAllObjects];
if (completion != nil) completion();
}
- (void)detachFromEngineForRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar {
[self cleanupWithCompletion:nil];
}
- (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)flutterResult {
FLTFirebaseMethodCallErrorBlock errorBlock =
^(NSString *_Nullable code, NSString *_Nullable message, NSDictionary *_Nullable details,
NSError *_Nullable error) {
NSMutableDictionary *generatedDetails = [NSMutableDictionary new];
if (code == nil) {
NSDictionary *errorDetails = [FLTFirebaseAuthPlugin getNSDictionaryFromNSError:error];
[self storeAuthCredentialIfPresent:error];
code = errorDetails[kArgumentCode];
message = errorDetails[@"message"];
generatedDetails = [NSMutableDictionary dictionaryWithDictionary:errorDetails];
} else {
generatedDetails = [NSMutableDictionary dictionaryWithDictionary:@{
kArgumentCode : code,
@"message" : message,
@"additionalData" : @{},
}];
}
if (details != nil) {
generatedDetails[@"additionalData"] = details;
}
if ([@"unknown" isEqualToString:code]) {
NSLog(@"FLTFirebaseAuth: An error occurred while calling method %@, "
@"errorOrNil => %@",
call.method, [error userInfo]);
}
flutterResult([FLTFirebasePlugin createFlutterErrorFromCode:code
message:message
optionalDetails:generatedDetails
andOptionalNSError:error]);
};
FLTFirebaseMethodCallSuccessBlock successBlock = ^(id _Nullable result) {
if ([result isKindOfClass:[FIRAuthDataResult class]]) {
flutterResult([self getNSDictionaryFromAuthResult:result]);
} else if ([result isKindOfClass:[FIRUser class]]) {
flutterResult([FLTFirebaseAuthPlugin getNSDictionaryFromUser:result]);
} else {
flutterResult(result);
}
};
FLTFirebaseMethodCallResult *methodCallResult =
[FLTFirebaseMethodCallResult createWithSuccess:successBlock andErrorBlock:errorBlock];
[self ensureAPNSTokenSetting];
if ([@"Auth#registerIdTokenListener" isEqualToString:call.method]) {
[self registerIdTokenListener:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#registerAuthStateListener" isEqualToString:call.method]) {
[self registerAuthStateListener:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#applyActionCode" isEqualToString:call.method]) {
[self applyActionCode:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#checkActionCode" isEqualToString:call.method]) {
[self checkActionCode:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#confirmPasswordReset" isEqualToString:call.method]) {
[self confirmPasswordReset:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#createUserWithEmailAndPassword" isEqualToString:call.method]) {
[self createUserWithEmailAndPassword:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#fetchSignInMethodsForEmail" isEqualToString:call.method]) {
[self fetchSignInMethodsForEmail:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#sendPasswordResetEmail" isEqualToString:call.method]) {
[self sendPasswordResetEmail:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#sendSignInLinkToEmail" isEqualToString:call.method]) {
[self sendSignInLinkToEmail:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#signInWithCredential" isEqualToString:call.method]) {
[self signInWithCredential:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#setLanguageCode" isEqualToString:call.method]) {
[self setLanguageCode:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#setSettings" isEqualToString:call.method]) {
[self setSettings:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#signInAnonymously" isEqualToString:call.method]) {
[self signInAnonymously:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#signInWithCustomToken" isEqualToString:call.method]) {
[self signInWithCustomToken:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#signInWithEmailAndPassword" isEqualToString:call.method]) {
[self signInWithEmailAndPassword:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#signInWithEmailLink" isEqualToString:call.method]) {
[self signInWithEmailLink:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#signOut" isEqualToString:call.method]) {
[self signOut:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#useEmulator" isEqualToString:call.method]) {
[self useEmulator:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#verifyPasswordResetCode" isEqualToString:call.method]) {
[self verifyPasswordResetCode:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#signInWithProvider" isEqualToString:call.method]) {
[self signInWithProvider:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"Auth#verifyPhoneNumber" isEqualToString:call.method]) {
[self verifyPhoneNumber:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#delete" isEqualToString:call.method]) {
[self userDelete:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#getIdToken" isEqualToString:call.method]) {
[self userGetIdToken:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#linkWithCredential" isEqualToString:call.method]) {
[self userLinkWithCredential:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#linkWithProvider" isEqualToString:call.method]) {
[self userLinkWithProvider:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#reauthenticateWithProvider" isEqualToString:call.method]) {
[self reauthenticateWithProvider:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#reauthenticateUserWithCredential" isEqualToString:call.method]) {
[self userReauthenticateUserWithCredential:call.arguments
withMethodCallResult:methodCallResult];
} else if ([@"User#reload" isEqualToString:call.method]) {
[self userReload:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#sendEmailVerification" isEqualToString:call.method]) {
[self userSendEmailVerification:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#unlink" isEqualToString:call.method]) {
[self userUnlink:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#updateEmail" isEqualToString:call.method]) {
[self userUpdateEmail:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#updatePassword" isEqualToString:call.method]) {
[self userUpdatePassword:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#updatePhoneNumber" isEqualToString:call.method]) {
[self userUpdatePhoneNumber:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#updateProfile" isEqualToString:call.method]) {
[self userUpdateProfile:call.arguments withMethodCallResult:methodCallResult];
} else if ([@"User#verifyBeforeUpdateEmail" isEqualToString:call.method]) {
[self userVerifyBeforeUpdateEmail:call.arguments withMethodCallResult:methodCallResult];
} else {
methodCallResult.success(FlutterMethodNotImplemented);
}
}
#pragma mark - AppDelegate
#if TARGET_OS_IPHONE
#if !__has_include(<FirebaseMessaging/FirebaseMessaging.h>)
- (BOOL)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)notification
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
if ([[FIRAuth auth] canHandleNotification:notification]) {
completionHandler(UIBackgroundFetchResultNoData);
return YES;
}
return NO;
}
#endif
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
_apnsToken = deviceToken;
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary *)options {
return [[FIRAuth auth] canHandleURL:url];
}
#endif
#pragma mark - FLTFirebasePlugin
- (void)didReinitializeFirebaseCore:(void (^_Nonnull)(void))completion {
[self cleanupWithCompletion:completion];
}
- (NSString *_Nonnull)firebaseLibraryName {
return LIBRARY_NAME;
}
- (NSString *_Nonnull)firebaseLibraryVersion {
return LIBRARY_VERSION;
}
- (NSString *_Nonnull)flutterChannelName {
return kFLTFirebaseAuthChannelName;
}
- (NSDictionary *_Nonnull)pluginConstantsForFIRApp:(FIRApp *_Nonnull)firebaseApp {
FIRAuth *auth = [FIRAuth authWithApp:firebaseApp];
return @{
@"APP_LANGUAGE_CODE" : (id)[auth languageCode] ?: [NSNull null],
@"APP_CURRENT_USER" : [auth currentUser]
? (id)[FLTFirebaseAuthPlugin getNSDictionaryFromUser:[auth currentUser]]
: [NSNull null],
};
}
#pragma mark - Firebase Auth API
- (void)applyActionCode:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth applyActionCode:arguments[kArgumentCode]
completion:^(NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
- (void)checkActionCode:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth checkActionCode:arguments[kArgumentCode]
completion:^(FIRActionCodeInfo *_Nullable info, NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
NSMutableDictionary *actionCodeResultDict = [NSMutableDictionary dictionary];
NSMutableDictionary *dataDict = [NSMutableDictionary dictionary];
if (info.email != nil) {
dataDict[@"email"] = info.email;
}
if (info.previousEmail != nil) {
dataDict[@"previousEmail"] = info.previousEmail;
}
if (info.operation == FIRActionCodeOperationPasswordReset) {
actionCodeResultDict[@"operation"] = @1;
} else if (info.operation == FIRActionCodeOperationVerifyEmail) {
actionCodeResultDict[@"operation"] = @2;
} else if (info.operation == FIRActionCodeOperationRecoverEmail) {
actionCodeResultDict[@"operation"] = @3;
} else if (info.operation == FIRActionCodeOperationEmailLink) {
actionCodeResultDict[@"operation"] = @4;
} else if (info.operation == FIRActionCodeOperationVerifyAndChangeEmail) {
actionCodeResultDict[@"operation"] = @5;
} else if (info.operation == FIRActionCodeOperationRevertSecondFactorAddition) {
actionCodeResultDict[@"operation"] = @6;
} else {
// Unknown / Error.
actionCodeResultDict[@"operation"] = @0;
}
actionCodeResultDict[@"data"] = dataDict;
result.success(actionCodeResultDict);
}
}];
}
- (void)confirmPasswordReset:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth confirmPasswordResetWithCode:arguments[kArgumentCode]
newPassword:arguments[@"newPassword"]
completion:^(NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
- (void)createUserWithEmailAndPassword:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth createUserWithEmail:arguments[kArgumentEmail]
password:arguments[@"password"]
completion:^(FIRAuthDataResult *authResult, NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(authResult);
}
}];
}
- (void)fetchSignInMethodsForEmail:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth fetchSignInMethodsForEmail:arguments[kArgumentEmail]
completion:^(NSArray<NSString *> *_Nullable providers,
NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(@{
@"providers" : (id)providers ?: @[],
});
}
}];
}
- (void)sendPasswordResetEmail:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
NSString *email = arguments[kArgumentEmail];
FIRActionCodeSettings *actionCodeSettings =
[self getFIRActionCodeSettingsFromArguments:arguments];
[auth sendPasswordResetWithEmail:email
actionCodeSettings:actionCodeSettings
completion:^(NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
- (void)sendSignInLinkToEmail:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
NSString *email = arguments[kArgumentEmail];
FIRActionCodeSettings *actionCodeSettings =
[self getFIRActionCodeSettingsFromArguments:arguments];
[auth sendSignInLinkToEmail:email
actionCodeSettings:actionCodeSettings
completion:^(NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
- (void)signInWithCredential:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
FIRAuthCredential *credential = [self getFIRAuthCredentialFromArguments:arguments];
if (credential == nil) {
result.error(kErrCodeInvalidCredential, kErrMsgInvalidCredential, nil, nil);
return;
}
[auth signInWithCredential:credential
completion:^(FIRAuthDataResult *authResult, NSError *error) {
if (error != nil) {
NSDictionary *userInfo = [error userInfo];
NSError *underlyingError = [userInfo objectForKey:NSUnderlyingErrorKey];
NSDictionary *firebaseDictionary =
underlyingError.userInfo[@"FIRAuthErrorUserInfoDeserializedResponseKey"];
if (firebaseDictionary != nil && firebaseDictionary[@"message"] != nil) {
// error from firebase-ios-sdk is buried in underlying
// error.
result.error(nil, firebaseDictionary[@"message"], nil, nil);
} else {
if (error.code == FIRAuthErrorCodeSecondFactorRequired) {
[self handleMultiFactorError:arguments withResult:result withError:error];
} else {
result.error(nil, nil, nil, error);
}
}
} else {
result.success(authResult);
}
}];
}
// Adapted from
// https://auth0.com/docs/api-auth/tutorials/nonce#generate-a-cryptographically-random-nonce Used
// for Apple Sign In
- (NSString *)randomNonce:(NSInteger)length {
NSAssert(length > 0, @"Expected nonce to have positive length");
NSString *characterSet = @"0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._";
NSMutableString *result = [NSMutableString string];
NSInteger remainingLength = length;
while (remainingLength > 0) {
NSMutableArray *randoms = [NSMutableArray arrayWithCapacity:16];
for (NSInteger i = 0; i < 16; i++) {
uint8_t random = 0;
int errorCode = SecRandomCopyBytes(kSecRandomDefault, 1, &random);
NSAssert(errorCode == errSecSuccess, @"Unable to generate nonce: OSStatus %i", errorCode);
[randoms addObject:@(random)];
}
for (NSNumber *random in randoms) {
if (remainingLength == 0) {
break;
}
if (random.unsignedIntValue < characterSet.length) {
unichar character = [characterSet characterAtIndex:random.unsignedIntValue];
[result appendFormat:@"%C", character];
remainingLength--;
}
}
}
return [result copy];
}
- (NSString *)stringBySha256HashingString:(NSString *)input {
const char *string = [input UTF8String];
unsigned char result[CC_SHA256_DIGEST_LENGTH];
CC_SHA256(string, (CC_LONG)strlen(string), result);
NSMutableString *hashed = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
for (NSInteger i = 0; i < CC_SHA256_DIGEST_LENGTH; i++) {
[hashed appendFormat:@"%02x", result[i]];
}
return hashed;
}
static void handleSignInWithApple(FLTFirebaseAuthPlugin *object, FIRAuthDataResult *authResult,
NSError *error) {
if (error != nil) {
if (error.code == FIRAuthErrorCodeSecondFactorRequired) {
[object handleMultiFactorError:object.appleArguments
withResult:object.appleResult
withError:error];
} else {
object.appleResult.error(nil, nil, nil, error);
}
return;
}
object.appleResult.success(authResult);
}
- (void)authorizationController:(ASAuthorizationController *)controller
didCompleteWithAuthorization:(ASAuthorization *)authorization
API_AVAILABLE(macos(10.15), ios(13.0)) {
if ([authorization.credential isKindOfClass:[ASAuthorizationAppleIDCredential class]]) {
ASAuthorizationAppleIDCredential *appleIDCredential = authorization.credential;
NSString *rawNonce = self.currentNonce;
NSAssert(rawNonce != nil,
@"Invalid state: A login callback was received, but no login request was sent.");
if (appleIDCredential.identityToken == nil) {
NSLog(@"Unable to fetch identity token.");
return;
}
NSString *idToken = [[NSString alloc] initWithData:appleIDCredential.identityToken
encoding:NSUTF8StringEncoding];
if (idToken == nil) {
NSLog(@"Unable to serialize id token from data: %@", appleIDCredential.identityToken);
}
// Initialize a Firebase credential.
FIROAuthCredential *credential = [FIROAuthProvider credentialWithProviderID:@"apple.com"
IDToken:idToken
rawNonce:rawNonce];
if (self.linkWithAppleUser != nil) {
[self.linkWithAppleUser linkWithCredential:credential
completion:^(FIRAuthDataResult *authResult, NSError *error) {
handleSignInWithApple(self, authResult, error);
}];
} else {
[FIRAuth.auth signInWithCredential:credential
completion:^(FIRAuthDataResult *_Nullable authResult,
NSError *_Nullable error) {
handleSignInWithApple(self, authResult, error);
}];
}
}
}
- (void)authorizationController:(ASAuthorizationController *)controller
didCompleteWithError:(NSError *)error API_AVAILABLE(macos(10.15), ios(13.0)) {
NSLog(@"Sign in with Apple errored: %@", error);
self.appleResult.error(nil, nil, nil, error);
}
- (void)signInWithProvider:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
if ([arguments[@"signInProvider"] isEqualToString:kSignInMethodApple]) {
if (@available(iOS 13.0, macOS 10.15, *)) {
launchAppleSignInRequest(self, arguments, result);
} else {
NSLog(@"Sign in with Apple was introduced in iOS 13, update your Podfile with platform :ios, "
@"'13.0'");
}
return;
}
#if TARGET_OS_OSX
NSLog(@"signInWithProvider is not supported on the "
@"MacOS platform.");
result.success(nil);
#else
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
self.authProvider = [FIROAuthProvider providerWithProviderID:arguments[@"signInProvider"]];
NSArray *scopes = arguments[kArgumentProviderScope];
if (scopes != nil) {
[self.authProvider setScopes:scopes];
}
NSDictionary *customParameters = arguments[kArgumentProviderCustomParameters];
if (customParameters != nil) {
[self.authProvider setCustomParameters:customParameters];
}
[self.authProvider
getCredentialWithUIDelegate:nil
completion:^(FIRAuthCredential *_Nullable credential,
NSError *_Nullable error) {
handleAppleAuthResult(self, arguments, auth, credential, error, result);
}];
#endif
}
- (void)setLanguageCode:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
NSString *languageCode = arguments[@"languageCode"];
if (languageCode != nil && ![languageCode isEqual:[NSNull null]]) {
auth.languageCode = languageCode;
} else {
[auth useAppLanguage];
}
result.success(@{@"languageCode" : auth.languageCode});
}
- (void)setSettings:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
if ([[arguments allKeys] containsObject:@"userAccessGroup"] &&
![arguments[@"userAccessGroup"] isEqual:[NSNull null]]) {
BOOL useUserAccessGroupSuccessful;
NSError *useUserAccessGroupErrorPtr;
useUserAccessGroupSuccessful = [auth useUserAccessGroup:arguments[@"userAccessGroup"]
error:&useUserAccessGroupErrorPtr];
if (!useUserAccessGroupSuccessful) {
return result.error(nil, nil, nil, useUserAccessGroupErrorPtr);
}
}
#if TARGET_OS_IPHONE
if ([[arguments allKeys] containsObject:@"appVerificationDisabledForTesting"] &&
![arguments[@"appVerificationDisabledForTesting"] isEqual:[NSNull null]]) {
auth.settings.appVerificationDisabledForTesting =
[arguments[@"appVerificationDisabledForTesting"] boolValue];
}
#else
NSLog(@"FIRAuthSettings.appVerificationDisabledForTesting is not supported "
@"on MacOS.");
#endif
result.success(nil);
}
- (void)signInWithCustomToken:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth signInWithCustomToken:arguments[kArgumentToken]
completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
if (error != nil) {
if (error.code == FIRAuthErrorCodeSecondFactorRequired) {
[self handleMultiFactorError:arguments withResult:result withError:error];
} else {
result.error(nil, nil, nil, error);
}
} else {
result.success(authResult);
}
}];
}
- (void)handleMultiFactorError:(id)arguments
withResult:(FLTFirebaseMethodCallResult *)result
withError:(NSError *_Nullable)error {
#if TARGET_OS_OSX
result.error(nil, nil, nil, error);
#else
FIRMultiFactorResolver *resolver =
(FIRMultiFactorResolver *)error.userInfo[FIRAuthErrorUserInfoMultiFactorResolverKey];
NSArray<FIRMultiFactorInfo *> *hints = resolver.hints;
FIRMultiFactorSession *session = resolver.session;
NSString *sessionId = [[NSUUID UUID] UUIDString];
self->_multiFactorSessionMap[sessionId] = session;
NSString *resolverId = [[NSUUID UUID] UUIDString];
self->_multiFactorResolverMap[resolverId] = resolver;
NSMutableArray<NSDictionary *> *pigeonHints = [NSMutableArray array];
for (FIRMultiFactorInfo *multiFactorInfo in hints) {
NSString *phoneNumber;
if ([multiFactorInfo class] == [FIRPhoneMultiFactorInfo class]) {
FIRPhoneMultiFactorInfo *phoneFactorInfo = (FIRPhoneMultiFactorInfo *)multiFactorInfo;
phoneNumber = phoneFactorInfo.phoneNumber;
}
PigeonMultiFactorInfo *object = [PigeonMultiFactorInfo
makeWithDisplayName:multiFactorInfo.displayName
enrollmentTimestamp:[NSNumber numberWithDouble:multiFactorInfo.enrollmentDate
.timeIntervalSince1970]
factorId:multiFactorInfo.factorID
uid:multiFactorInfo.UID
phoneNumber:phoneNumber];
[pigeonHints addObject:object.toMap];
}
NSDictionary *output = @{
kAppName : arguments[kAppName],
kArgumentMultiFactorHints : pigeonHints,
kArgumentMultiFactorSessionId : sessionId,
kArgumentMultiFactorResolverId : resolverId,
};
result.error(nil, nil, output, error);
#endif
}
- (void)signInWithEmailAndPassword:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth signInWithEmail:arguments[kArgumentEmail]
password:arguments[@"password"]
completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
if (error != nil) {
if (error.code == FIRAuthErrorCodeSecondFactorRequired) {
[self handleMultiFactorError:arguments withResult:result withError:error];
} else {
result.error(nil, nil, nil, error);
}
} else {
result.success(authResult);
}
}];
}
- (void)signInWithEmailLink:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth signInWithEmail:arguments[kArgumentEmail]
link:arguments[@"emailLink"]
completion:^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
if (error != nil) {
if (error.code == FIRAuthErrorCodeSecondFactorRequired) {
[self handleMultiFactorError:arguments withResult:result withError:error];
} else {
result.error(nil, nil, nil, error);
}
} else {
result.success(authResult);
}
}];
}
- (void)signOut:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
if (auth.currentUser == nil) {
result.success(nil);
return;
}
NSError *signOutErrorPtr;
BOOL signOutSuccessful = [auth signOut:&signOutErrorPtr];
if (!signOutSuccessful) {
result.error(nil, nil, nil, signOutErrorPtr);
} else {
result.success(nil);
}
}
- (void)useEmulator:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth useEmulatorWithHost:arguments[@"host"] port:[arguments[@"port"] integerValue]];
result.success(nil);
}
- (void)verifyPasswordResetCode:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
[auth verifyPasswordResetCode:arguments[kArgumentCode]
completion:^(NSString *_Nullable email, NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(@{kArgumentEmail : (id)email ?: [NSNull null]});
}
}];
}
- (void)userDelete:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
FIRUser *currentUser = auth.currentUser;
if (currentUser == nil) {
result.error(kErrCodeNoCurrentUser, kErrMsgNoCurrentUser, nil, nil);
return;
}
[currentUser deleteWithCompletion:^(NSError *_Nullable error) {
if (error != nil) {
result.error(nil, nil, nil, error);
} else {
result.success(nil);
}
}];
}
- (void)userGetIdToken:(id)arguments withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
FIRUser *currentUser = auth.currentUser;
if (currentUser == nil) {
result.error(kErrCodeNoCurrentUser, kErrMsgNoCurrentUser, nil, nil);
return;
}
BOOL forceRefresh = [arguments[@"forceRefresh"] boolValue];
BOOL tokenOnly = [arguments[@"tokenOnly"] boolValue];
[currentUser
getIDTokenResultForcingRefresh:forceRefresh
completion:^(FIRAuthTokenResult *tokenResult, NSError *error) {
if (error != nil) {
result.error(nil, nil, nil, error);
return;
}
if (tokenOnly) {
result.success(
@{kArgumentToken : (id)tokenResult.token ?: [NSNull null]});
} else {
long expirationTimestamp =
(long)[tokenResult.expirationDate timeIntervalSince1970] * 1000;
long authTimestamp =
(long)[tokenResult.authDate timeIntervalSince1970] * 1000;
long issuedAtTimestamp =
(long)[tokenResult.issuedAtDate timeIntervalSince1970] * 1000;
NSMutableDictionary *tokenData =
[[NSMutableDictionary alloc] initWithDictionary:@{
@"authTimestamp" : @(authTimestamp),
@"claims" : tokenResult.claims,
@"expirationTimestamp" : @(expirationTimestamp),
@"issuedAtTimestamp" : @(issuedAtTimestamp),
@"signInProvider" : (id)tokenResult.signInProvider
?: [NSNull null],
@"signInSecondFactor" : (id)tokenResult.signInSecondFactor
?: [NSNull null],
kArgumentToken : tokenResult.token,
}];
result.success(tokenData);
}
}];
}
static void launchAppleSignInRequest(FLTFirebaseAuthPlugin *object, id arguments,
FLTFirebaseMethodCallResult *result) {
NSString *nonce = [object randomNonce:32];
object.currentNonce = nonce;
object.appleResult = result;
object.appleArguments = arguments;
ASAuthorizationAppleIDProvider *appleIDProvider = [[ASAuthorizationAppleIDProvider alloc] init];
ASAuthorizationAppleIDRequest *request = [appleIDProvider createRequest];
NSMutableArray *requestedScopes = [NSMutableArray arrayWithCapacity:2];
if ([arguments[kArgumentProviderScope] containsObject:@"name"]) {
[requestedScopes addObject:ASAuthorizationScopeFullName];
}
if ([arguments[kArgumentProviderScope] containsObject:@"email"]) {
[requestedScopes addObject:ASAuthorizationScopeEmail];
}
request.requestedScopes = [requestedScopes copy];
request.nonce = [object stringBySha256HashingString:nonce];
ASAuthorizationController *authorizationController =
[[ASAuthorizationController alloc] initWithAuthorizationRequests:@[ request ]];
authorizationController.delegate = object;
authorizationController.presentationContextProvider = object;
[authorizationController performRequests];
}
static void handleAppleAuthResult(FLTFirebaseAuthPlugin *object, id arguments, FIRAuth *auth,
FIRAuthCredential *credentials, NSError *error,
FLTFirebaseMethodCallResult *result) {
if (error) {
if (error.code == FIRAuthErrorCodeSecondFactorRequired) {
[object handleMultiFactorError:arguments withResult:result withError:error];
} else {
result.error(nil, nil, nil, error);
}
return;
}
if (credentials) {
[auth signInWithCredential:credentials
completion:^(FIRAuthDataResult *authResult, NSError *error) {
if (error != nil) {
NSDictionary *userInfo = [error userInfo];
NSError *underlyingError = [userInfo objectForKey:NSUnderlyingErrorKey];
NSDictionary *firebaseDictionary =
underlyingError.userInfo[@"FIRAuthErrorUserInfoDes"
@"erializedResponseKey"];
if (firebaseDictionary != nil && firebaseDictionary[@"message"] != nil) {
// error from firebase-ios-sdk is
// buried in underlying error.
result.error(nil, firebaseDictionary[@"message"], nil, nil);
} else {
result.error(nil, nil, nil, error);
}
} else {
result.success(authResult);
}
}];
}
}
- (void)userLinkWithProvider:(id)arguments
withMethodCallResult:(FLTFirebaseMethodCallResult *)result {
FIRAuth *auth = [self getFIRAuthFromArguments:arguments];
FIRUser *currentUser = auth.currentUser;
if (currentUser == nil) {
result.error(kErrCodeNoCurrentUser, kErrMsgNoCurrentUser, nil, nil);
return;
}
if ([arguments[@"signInProvider"] isEqualToString:kSignInMethodApple]) {
if (@available(iOS 13.0, macOS 10.15, *)) {
self.linkWithAppleUser = currentUser;
launchAppleSignInRequest(self, arguments, result);
} else {
NSLog(@"Sign in with Apple was introduced in iOS 13, update your Podfile with platform :ios, "
@"'13.0'");
}
return;
}
#if TARGET_OS_OSX
NSLog(@"linkWithProvider is not supported on the "
@"MacOS platform.");
result.success(nil);
#else
self.authProvider = [FIROAuthProvider providerWithProviderID:arguments[@"signInProvider"]];
NSArray *scopes = arguments[kArgumentProviderScope];
if (scopes != nil) {
[self.authProvider setScopes:scopes];
}
NSDictionary *customParameters = arguments[kArgumentProviderCustomParameters];
if (customParameters != nil) {
[self.authProvider setCustomParameters:customParameters];
}
[currentUser
linkWithProvider:self.authProvider
UIDelegate:nil
completion:^(FIRAuthDataResult *authResult, NSError *error) {
handleAppleAuthResult(self, arguments, auth, authResult.credential, error, result);
}];