-
Notifications
You must be signed in to change notification settings - Fork 480
/
Copy pathFUIEmailAuth.m
834 lines (744 loc) · 34.3 KB
/
FUIEmailAuth.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
//
// Copyright (c) 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file 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 "FUIEmailAuth.h"
#import <FirebaseCore/FIRApp.h>
#import <FirebaseCore/FIROptions.h>
#import <FirebaseAuth/FIRAuth.h>
#import <FirebaseAuth/FirebaseAuth.h>
#import <GoogleUtilities/GULUserDefaults.h>
#import "FUIAuth.h"
#import "FUIAuth_Internal.h"
#import "FUIAuthStrings.h"
#import "FUIAuthUtils.h"
#import "FUIAuthErrorUtils.h"
#import "FUIAuthBaseViewController.h"
#import "FUIAuthBaseViewController_Internal.h"
#import "FUIConfirmEmailViewController.h"
#import "FUIEmailAuthStrings.h"
#import "FUIEmailAuth_Internal.h"
#import "FUIEmailEntryViewController.h"
#import "FUIPasswordSignInViewController_Internal.h"
#import "FUIPasswordVerificationViewController.h"
#import "FUIPasswordSignInViewController.h"
/** @var kErrorUserInfoEmailKey
@brief The key for the email address in the userinfo dictionary of a sign in error.
*/
static NSString *const kErrorUserInfoEmailKey = @"FIRAuthErrorUserInfoEmailKey";
/** @var kEmailButtonAccessibilityID
@brief The Accessibility Identifier for the @c email sign in button.
*/
static NSString *const kEmailButtonAccessibilityID = @"EmailButtonAccessibilityID";
/** @var kEmailLinkSignInEmailKey
@brief The key of the email which request email link sign in.
*/
static NSString *const kEmailLinkSignInEmailKey = @"FIRAuthEmailLinkSignInEmail";
/** @var kEmailLinkSignInLinkingCredentialKey
@brief The key of the auth credential to be linked.
*/
static NSString *const kEmailLinkSignInLinkingCredentialKey = @"FIRAuthEmailLinkSignInLinkingCredential";
@interface FUIEmailAuth () <FUIEmailAuthProvider>
/** @property authUI.
@brief The @c FUIAuth instance of the application.
*/
@property(nonatomic, strong, readonly) FUIAuth *authUI;
/** @property pendingSignInCallback.
@brief The callback which should be invoked when the sign in flow completes (or is cancelled.)
*/
@property(nonatomic, copy, readwrite) FUIAuthProviderSignInCompletionBlock pendingSignInCallback;
/** @property presentingViewController
@brief The presenting view controller for interactive sign-in.
*/
@property(nonatomic, strong) UIViewController *presentingViewController;
@end
@implementation FUIEmailAuth
- (instancetype)init {
return [self initAuthAuthUI:[FUIAuth defaultAuthUI]
signInMethod:FIREmailPasswordAuthSignInMethod
forceSameDevice:NO
allowNewEmailAccounts:YES
actionCodeSetting:[[FIRActionCodeSettings alloc] init]];
}
- (instancetype)initAuthAuthUI:(FUIAuth *)authUI
signInMethod:(NSString *)signInMethod
forceSameDevice:(BOOL)forceSameDevice
allowNewEmailAccounts:(BOOL)allowNewEmailAccounts
actionCodeSetting:(FIRActionCodeSettings *)actionCodeSettings {
self = [super init];
if (self) {
_authUI = authUI;
_authUI.emailAuthProvider = self;
_signInMethod = signInMethod;
_forceSameDevice = forceSameDevice;
_actionCodeSettings = actionCodeSettings;
_allowNewEmailAccounts = allowNewEmailAccounts;
}
return self;
}
#pragma mark - FUIAuthProvider
- (nullable NSString *)providerID {
return FIREmailAuthProviderID;
}
/** @fn accessToken:
@brief Email Auth token is matched by FirebaseUI User Access Token
*/
- (nullable NSString *)accessToken {
return nil;
}
/** @fn idToken:
@brief Email Auth Token Secret is matched by FirebaseUI User Id Token
*/
- (nullable NSString *)idToken {
return nil;
}
- (NSString *)shortName {
return @"Email";
}
- (NSString *)signInLabel {
return FUILocalizedString(kStr_SignInWithEmail);
}
- (UIImage *)icon {
return [FUIAuthUtils imageNamed:@"ic_email" fromBundleNameOrNil:FUIEmailAuthBundleName];
}
- (UIColor *)buttonBackgroundColor {
return [UIColor colorWithRed:208.f/255.f green:2.f/255.f blue:27.f/255.f alpha:1.0];
}
- (UIColor *)buttonTextColor {
return [UIColor whiteColor];
}
- (void)signInWithPresentingViewController:(UIViewController *)presentingViewController {
[self signInWithPresentingViewController:presentingViewController
email:nil];
}
- (void)signInWithPresentingViewController:(UIViewController *)presentingViewController
email:(nullable NSString *)email {
[self.authUI signInWithProviderUI:self
presentingViewController:presentingViewController
defaultValue:email];
}
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-implementations"
- (void)signInWithEmail:(nullable NSString *)email
presentingViewController:(nullable UIViewController *)presentingViewController
completion:(nullable FUIAuthProviderSignInCompletionBlock)completion {
[self signInWithDefaultValue:email
presentingViewController:presentingViewController
completion:completion];
}
#pragma clang diagnostic pop
- (void)signInWithDefaultValue:(nullable NSString *)defaultValue
presentingViewController:(nullable UIViewController *)presentingViewController
completion:(nullable FUIAuthProviderSignInCompletionBlock)completion {
self.presentingViewController = presentingViewController;
self.pendingSignInCallback = completion;
id<FUIAuthDelegate> delegate = self.authUI.delegate;
UIViewController *controller;
if (self.allowNewEmailAccounts) {
if ([delegate respondsToSelector:@selector(emailEntryViewControllerForAuthUI:)]) {
controller = [delegate emailEntryViewControllerForAuthUI:self.authUI];
} else {
controller = [[FUIEmailEntryViewController alloc] initWithAuthUI:self.authUI];
}
} else {
if ([delegate respondsToSelector:@selector(emailEntryViewControllerForAuthUI:)]) {
controller = [delegate passwordSignInViewControllerForAuthUI:self.authUI email:@""];
} else {
controller = [[FUIPasswordSignInViewController alloc] initWithAuthUI:self.authUI email:nil];
}
}
if ([presentingViewController isKindOfClass:[FUIAuthBaseViewController class]]) {
FUIAuthBaseViewController *authController =
(FUIAuthBaseViewController *)presentingViewController;
[authController pushViewController:controller];
} else {
UINavigationController *navigationController =
[[UINavigationController alloc] initWithRootViewController:controller];
[presentingViewController presentViewController:navigationController
animated:YES
completion:nil];
}
}
- (void)signOut {
}
- (BOOL)handleOpenURL:(NSURL *)URL sourceApplication:(nullable NSString *)sourceApplication {
self.emailLink = URL.absoluteString;
// Retrieve continueUrl from URL
NSURLComponents *urlComponents = [NSURLComponents componentsWithString:URL.absoluteString];
NSString *continueURLString;
for (NSURLQueryItem *queryItem in urlComponents.queryItems) {
if ([queryItem.name isEqualToString:@"continueUrl"]) {
continueURLString = queryItem.value;
}
}
if (!continueURLString) {
[FUIAuthBaseViewController showAlertWithMessage:@"Invalid link! Missing continue URL."];
return NO;
}
// Retrieve url parameters from continueUrl
NSMutableDictionary *urlParameterDict= [NSMutableDictionary dictionary];
NSURLComponents *continueURLComponents = [NSURLComponents componentsWithString:continueURLString];
for (NSURLQueryItem *queryItem in continueURLComponents.queryItems) {
urlParameterDict[queryItem.name] = queryItem.value;
}
// Retrieve parameters from local storage
NSMutableDictionary *localParameterDict = [NSMutableDictionary dictionary];
localParameterDict[kEmailLinkSignInEmailKey] = [GULUserDefaults.standardUserDefaults
stringForKey:kEmailLinkSignInEmailKey];
localParameterDict[@"ui_sid"] = [GULUserDefaults.standardUserDefaults stringForKey:@"ui_sid"];
// Handling flows
NSString *urlSessionID = urlParameterDict[@"ui_sid"];
NSString *localSessionID = localParameterDict[@"ui_sid"];
BOOL sameDevice = urlSessionID && localSessionID && [urlSessionID isEqualToString:localSessionID];
if (sameDevice) {
// Same device
if (urlParameterDict[@"ui_pid"]) {
// Unverified provider linking
[self handleUnverifiedProviderLinking:urlParameterDict[@"ui_pid"]
email:localParameterDict[kEmailLinkSignInEmailKey]];
} else if (urlParameterDict[@"ui_auid"]) {
// Anonymous upgrade
[self handleAnonymousUpgrade:urlParameterDict[@"ui_auid"]
email:localParameterDict[kEmailLinkSignInEmailKey]];
} else {
// Normal email link sign in
[self handleEmaiLinkSignIn:localParameterDict[kEmailLinkSignInEmailKey]];
}
} else {
// Different device
if ([urlParameterDict[@"ui_sd"] isEqualToString:@"1"]) {
// Force same device enabled
[self handleDifferentDevice];
} else {
// Force same device not enabled
[self handleConfirmEmail];
}
}
return YES;
}
- (void)handleUnverifiedProviderLinking:(NSString *)providerID
email:(NSString *)email {
if ([providerID isEqualToString:FIRFacebookAuthProviderID]) {
NSData *unverifiedProviderCredentialData = [GULUserDefaults.standardUserDefaults
objectForKey:kEmailLinkSignInLinkingCredentialKey];
FIRAuthCredential *unverifiedProviderCredential =
[NSKeyedUnarchiver unarchiveObjectWithData:unverifiedProviderCredentialData];
FIRAuthCredential *emailLinkCredential =
[FIREmailAuthProvider credentialWithEmail:email link:self.emailLink];
void (^completeSignInBlock)(FIRAuthDataResult *, NSError *) = ^(FIRAuthDataResult *authResult,
NSError *error) {
if (error) {
switch (error.code) {
case FIRAuthErrorCodeWrongPassword:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_WrongPasswordError)];
return;
case FIRAuthErrorCodeUserNotFound:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_UserNotFoundError)];
return;
case FIRAuthErrorCodeUserDisabled:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_AccountDisabledError)];
return;
case FIRAuthErrorCodeTooManyRequests:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_SignInTooManyTimesError)];
return;
}
}
void (^dismissHandler)(void) = ^() {
UINavigationController *authViewController = [self.authUI authViewController];
if (!(authViewController.isViewLoaded && authViewController.view.window)) {
[authViewController.navigationController dismissViewControllerAnimated:YES completion:nil];
}
[self.authUI invokeResultCallbackWithAuthDataResult:authResult URL:nil error:error];
};
[FUIAuthBaseViewController showAlertWithTitle:FUILocalizedString(kStr_SignedIn)
message:nil
actionTitle:nil
actionHandler:nil
dismissTitle:@"OK"
dismissHandler:dismissHandler
presentingViewController:nil];
};
[self.authUI.auth signInAndRetrieveDataWithCredential:emailLinkCredential
completion:^(FIRAuthDataResult * _Nullable authResult, NSError * _Nullable error) {
if (error) {
[FUIAuthBaseViewController showAlertWithMessage:error.description];
return;
}
[authResult.user linkAndRetrieveDataWithCredential:unverifiedProviderCredential completion:completeSignInBlock];
}];
}
}
- (void)handleAnonymousUpgrade:(NSString *)anonymousUserID email:(NSString *)email {
// Check for the presence of an anonymous user and whether automatic upgrade is enabled.
if (self.authUI.auth.currentUser.isAnonymous &&
self.authUI.shouldAutoUpgradeAnonymousUsers &&
[anonymousUserID isEqualToString:self.authUI.auth.currentUser.uid]) {
FIRAuthCredential *credential =
[FIREmailAuthProvider credentialWithEmail:email link:self.emailLink];
void (^completeSignInBlock)(FIRAuthDataResult *, NSError *) = ^(FIRAuthDataResult *authResult,
NSError *error) {
if (error) {
switch (error.code) {
case FIRAuthErrorCodeWrongPassword:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_WrongPasswordError)];
return;
case FIRAuthErrorCodeUserNotFound:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_UserNotFoundError)];
return;
case FIRAuthErrorCodeUserDisabled:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_AccountDisabledError)];
return;
case FIRAuthErrorCodeTooManyRequests:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_SignInTooManyTimesError)];
return;
}
}
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_SignedIn)];
};
[self.authUI.auth.currentUser
linkAndRetrieveDataWithCredential:credential
completion:^(FIRAuthDataResult *_Nullable authResult,
NSError *_Nullable error) {
if (error) {
if (error.code == FIRAuthErrorCodeEmailAlreadyInUse) {
NSDictionary *userInfo = @{ FUIAuthCredentialKey : credential };
NSError *mergeError = [FUIAuthErrorUtils mergeConflictErrorWithUserInfo:userInfo
underlyingError:error];
completeSignInBlock(nil, mergeError);
return;
}
completeSignInBlock(nil, error);
return;
}
completeSignInBlock(authResult, nil);
}];
} else {
[self handleDifferentDevice];
}
}
- (void)handleEmaiLinkSignIn:(NSString *)email {
FIRAuthCredential *credential =
[FIREmailAuthProvider credentialWithEmail:email link:self.emailLink];
void (^completeSignInBlock)(FIRAuthDataResult *, NSError *) = ^(FIRAuthDataResult *authResult,
NSError *error) {
if (error) {
switch (error.code) {
case FIRAuthErrorCodeWrongPassword:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_WrongPasswordError)];
return;
case FIRAuthErrorCodeUserNotFound:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_UserNotFoundError)];
return;
case FIRAuthErrorCodeUserDisabled:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_AccountDisabledError)];
return;
case FIRAuthErrorCodeTooManyRequests:
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_SignInTooManyTimesError)];
return;
}
}
void (^dismissHandler)(void) = ^() {
UINavigationController *authViewController = [self.authUI authViewController];
if (!(authViewController.isViewLoaded && authViewController.view.window)) {
[authViewController.navigationController dismissViewControllerAnimated:YES completion:nil];
}
[self.authUI invokeResultCallbackWithAuthDataResult:authResult URL:nil error:error];
};
[FUIAuthBaseViewController showAlertWithTitle:FUILocalizedString(kStr_SignedIn)
message:nil
actionTitle:nil
actionHandler:nil
dismissTitle:FUILocalizedString(kStr_OK)
dismissHandler:dismissHandler
presentingViewController:nil];
};
[self.authUI.auth signInAndRetrieveDataWithCredential:credential completion:completeSignInBlock];
}
- (void)handleDifferentDevice {
UINavigationController *authViewController = [self.authUI authViewController];
void (^completion)(void) = ^(){
[FUIAuthBaseViewController showAlertWithTitle:@"New Device detected"
message:@"Try opening the link using the same "
"device where you started the sign-in process"
presentingViewController:authViewController];
};
if (!(authViewController.isViewLoaded && authViewController.view.window)) {
[UIApplication.sharedApplication.keyWindow.rootViewController
presentViewController:authViewController animated:YES completion:completion];
} else {
completion();
}
}
- (void)handleConfirmEmail {
UINavigationController *authViewController = [self.authUI authViewController];
void (^completion)(void) = ^(){
UIViewController *controller = [[FUIConfirmEmailViewController alloc] initWithAuthUI:self.authUI];
[authViewController pushViewController:controller animated:YES];
};
if (!(authViewController.isViewLoaded && authViewController.view.window)) {
[UIApplication.sharedApplication.keyWindow.rootViewController
presentViewController:authViewController animated:YES completion:completion];
} else {
completion();
}
}
/** @fn callbackWithCredential:error:
@brief Ends the sign-in flow by cleaning up and calling back with given credential or error.
@param credential The credential to pass back, if any.
@param error The error to pass back, if any.
@param result The result of sign-in operation using provided @c FIRAuthCredential object.
@see @c FIRAuth.signInWithCredential:completion:
*/
- (void)callbackWithCredential:(nullable FIRAuthCredential *)credential
error:(nullable NSError *)error
result:(nullable FIRAuthResultCallback)result {
FUIAuthProviderSignInCompletionBlock callback = self.pendingSignInCallback;
self.pendingSignInCallback = nil;
if (callback) {
callback(credential, error, result, nil);
}
}
#pragma mark - FUIEmailAuthProvider
- (void)signInWithEmailHint:(NSString *)emailHint
presentingViewController:(FUIAuthBaseViewController *)presentingViewController
originalError:(NSError *)originalError
completion:(FUIEmailHintSignInCallback)completion {
NSString *kTempApp = @"tempApp";
FIROptions *options = [FIROptions defaultOptions];
// Create an new app instance in order to create a new auth instance.
if (![FIRApp appNamed:kTempApp]) {
[FIRApp configureWithName:kTempApp options:options];
}
FIRApp *tempApp = [FIRApp appNamed:kTempApp];
// Create a new auth instance in order to perform a successful sign-in without losing the
// currently signed in user on the default auth instance.
FIRAuth *tempAuth = [FIRAuth authWithApp:tempApp];
[self.authUI.auth fetchProvidersForEmail:emailHint
completion:^(NSArray<NSString *> *_Nullable providers,
NSError *_Nullable error) {
if (error) {
if (completion) {
completion(nil, error, nil);
}
return;
}
NSString *existingFederatedProviderID = [self authProviderFromProviders:providers];
// Set of providers which can be auto-linked.
NSSet *supportedProviders =
[NSSet setWithObjects:FIRGoogleAuthProviderID,
FIRFacebookAuthProviderID,
FIREmailAuthProviderID,
nil];
if ([supportedProviders containsObject:existingFederatedProviderID]) {
if ([existingFederatedProviderID isEqualToString:FIREmailAuthProviderID]) {
[FUIAuthBaseViewController showSignInAlertWithEmail:emailHint
providerShortName:@"Email/Password"
providerSignInLabel:@"Sign in with Email/Password"
presentingViewController:presentingViewController
signinHandler:^{
FUIAuth *authUI = [FUIAuth authUIWithAuth:tempAuth];
// Email password sign-in
FUIPasswordSignInViewController *controller =
[[FUIPasswordSignInViewController alloc] initWithAuthUI:authUI email:emailHint];
controller.onDismissCallback = ^(FIRAuthDataResult *result, NSError *error) {
if (completion) {
completion(result, error, nil);
}
};
[presentingViewController pushViewController:controller];
}
cancelHandler:^{
if (completion) {
completion(nil, originalError, nil);
}
}];
} else { // Federated sign-in case.
id<FUIAuthProvider> authProviderUI;
// Retrieve the FUIAuthProvider instance from FUIAuth for the existing provider ID.
for (id<FUIAuthProvider> provider in self.authUI.providers) {
if ([provider.providerID isEqualToString:existingFederatedProviderID]) {
authProviderUI = provider;
break;
}
}
[FUIAuthBaseViewController showSignInAlertWithEmail:emailHint
provider:authProviderUI
presentingViewController:presentingViewController
signinHandler:^{
[authProviderUI signOut];
[authProviderUI signInWithDefaultValue:emailHint
presentingViewController:presentingViewController
completion:^(FIRAuthCredential *_Nullable credential,
NSError *_Nullable error,
FIRAuthResultCallback _Nullable result,
NSDictionary *_Nullable userInfo) {
if (error) {
if (completion) {
completion(nil, error, nil);
}
return;
}
[tempAuth signInAndRetrieveDataWithCredential:credential
completion:^(FIRAuthDataResult *_Nullable authResult,
NSError *_Nullable error) {
if (error) {
if (completion) {
completion(nil, error, nil);
}
}
// Handle potential email mismatch.
if (![emailHint isEqualToString:authResult.user.email]) {
NSString *signedInEmail = authResult.user.email;
NSString *title =
[NSString stringWithFormat:@"Continue sign in with %@?", signedInEmail];
NSString *message =
[NSString stringWithFormat:@"You originally wanted to sign in with %@",
emailHint];
[FUIAuthBaseViewController showAlertWithTitle:title
message:message
actionTitle:@"Continue"
actionHandler:^{
if (completion) {
completion(authResult, nil, credential);
}
}
dismissTitle:@"Cancel"
dismissHandler:^{
if (completion) {
completion(nil, error, credential);
}
}
presentingViewController:presentingViewController];
}
if (completion) {
completion(authResult, error, credential);
}
}];
}];
}
cancelHandler:^{
if (completion) {
completion(nil, originalError, nil);
}
}];
}
}
}];
}
- (void)handleAccountLinkingForEmail:(NSString *)email
newCredential:(FIRAuthCredential *)newCredential
presentingViewController:(UIViewController *)presentingViewController
signInResult:(_Nullable FIRAuthResultCallback)result {
id<FUIAuthDelegate> delegate = self.authUI.delegate;
[self.authUI.auth fetchSignInMethodsForEmail:email
completion:^(NSArray<NSString *> *_Nullable providers,
NSError *_Nullable error) {
if (result) {
result(nil, error);
}
if (error) {
if (error.code == FIRAuthErrorCodeInvalidEmail) {
// This should never happen because the email address comes from the backend.
[FUIAuthBaseViewController showAlertWithMessage:FUILocalizedString(kStr_InvalidEmailError)
presentingViewController:presentingViewController];
} else {
[presentingViewController dismissViewControllerAnimated:YES completion:^{
[self.authUI invokeResultCallbackWithAuthDataResult:nil URL:nil error:error];
}];
}
return;
}
if (!providers.count) {
// This should never happen because the user must be registered.
[FUIAuthBaseViewController showAlertWithMessage:
FUILocalizedString(kStr_CannotAuthenticateError)
presentingViewController:presentingViewController];
return;
}
NSString *bestProviderID = providers[0];
if ([bestProviderID isEqual:FIREmailAuthProviderID]) {
// Password verification.
UIViewController *passwordController;
if ([delegate respondsToSelector:
@selector(passwordVerificationViewControllerForAuthUI:email:newCredential:)]) {
passwordController = [delegate passwordVerificationViewControllerForAuthUI:self.authUI
email:email
newCredential:newCredential];
} else {
passwordController =
[[FUIPasswordVerificationViewController alloc] initWithAuthUI:self.authUI
email:email
newCredential:newCredential];
}
if (presentingViewController.navigationController) {
[FUIAuthBaseViewController pushViewController:passwordController
navigationController:
presentingViewController.navigationController];
}
return;
}
if ([bestProviderID isEqual:FIREmailLinkAuthSignInMethod]) {
NSString *providerName;
if ([newCredential.provider isEqualToString:FIRFacebookAuthProviderID]) {
providerName = @"Facebook";
} else if ([newCredential.provider isEqualToString:FIRTwitterAuthProviderID]) {
providerName = @"Twitter";
} else if ([newCredential.provider isEqualToString:FIRGitHubAuthProviderID]) {
providerName = @"Github";
}
NSString *message = [NSString stringWithFormat:
@"You already have an account\n \n You've already used %@. You "
"can connect your %@ account with %@ by signing in with Email "
"link below. \n \n For this flow to successfully connect your "
"account with this email, you have to open the link on the same "
"device or browser.", email, providerName, email];
void (^actionHandler)(void) = ^() {
[self generateURLParametersAndLocalCache:email
linkingProvider:newCredential.provider];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:newCredential];
[GULUserDefaults.standardUserDefaults setObject:data forKey:kEmailLinkSignInLinkingCredentialKey];
void (^completion)(NSError * _Nullable error) = ^(NSError * _Nullable error){
if (error) {
[FUIAuthBaseViewController showAlertWithMessage:error.description];
} else {
NSString *signInMessage = [NSString stringWithFormat:
@"A sign-in email with additional instrucitons was sent to %@. Check your "
"email to complete sign-in.", email];
[FUIAuthBaseViewController
showAlertWithTitle:@"Sign-in email sent"
message:signInMessage
presentingViewController:nil];
}
};
[self.authUI.auth sendSignInLinkToEmail:email
actionCodeSettings:self.actionCodeSettings
completion:completion];
};
[FUIAuthBaseViewController
showAlertWithTitle:@"Sign in"
message:message
actionTitle:@"Sign in"
actionHandler:actionHandler
dismissTitle:nil
dismissHandler:nil
presentingViewController:nil];
return;
}
id<FUIAuthProvider> bestProvider = [self.authUI providerWithID:bestProviderID];
if (!bestProvider) {
// Unsupported provider.
[FUIAuthBaseViewController showAlertWithMessage:
FUILocalizedString(kStr_CannotAuthenticateError)
presentingViewController:presentingViewController];
return;
}
[FUIAuthBaseViewController showSignInAlertWithEmail:email
provider:bestProvider
presentingViewController:presentingViewController
signinHandler:^{
// Sign out first to make sure sign in starts with a clean state.
[bestProvider signOut];
[bestProvider signInWithDefaultValue:email
presentingViewController:presentingViewController
completion:^(FIRAuthCredential *_Nullable credential,
NSError *_Nullable error,
_Nullable FIRAuthResultCallback result,
NSDictionary *_Nullable userInfo) {
if (error) {
if (error.code == FUIAuthErrorCodeUserCancelledSignIn) {
// User cancelled sign in, Do nothing.
if (result) {
result(nil, error);
}
return;
}
[self.authUI invokeResultCallbackWithAuthDataResult:nil URL:nil error:error];
return;
}
[self.authUI.auth signInAndRetrieveDataWithCredential:credential
completion:^(FIRAuthDataResult*_Nullable authResult,
NSError *_Nullable error) {
if (error) {
[self.authUI invokeResultCallbackWithAuthDataResult:nil URL:nil error:error];
if (result) {
result(nil, error);
}
return;
}
FIRUser *user = authResult.user;
[user linkAndRetrieveDataWithCredential:newCredential
completion:^(FIRAuthDataResult *_Nullable authResult,
NSError *_Nullable error) {
if (result) {
result(authResult.user, error);
}
// Ignore any error (most likely caused by email mismatch) and treat the user as
// successfully signed in.
[presentingViewController dismissViewControllerAnimated:YES completion:^{
[self.authUI invokeResultCallbackWithAuthDataResult:authResult URL:nil error:nil];
}];
}];
}];
}];
} cancelHandler:^{
[self.authUI signOutWithError:nil];
}];
}];
}
#pragma mark - Private
- (void)generateURLParametersAndLocalCache:(NSString *)email linkingProvider:(NSString *)linkingProvider {
NSURL *url = self.actionCodeSettings.URL;
NSURLComponents *urlComponents = [NSURLComponents componentsWithString:url.absoluteString];
NSMutableArray<NSURLQueryItem *> *urlQuertItems = [NSMutableArray array];
[GULUserDefaults.standardUserDefaults setObject:email forKey:kEmailLinkSignInEmailKey];
if (self.authUI.auth.currentUser.isAnonymous && self.authUI.shouldAutoUpgradeAnonymousUsers) {
NSString *auid = self.authUI.auth.currentUser.uid;
NSURLQueryItem *anonymousUserIDQueryItem =
[NSURLQueryItem queryItemWithName:@"ui_auid" value:auid];
[urlQuertItems addObject:anonymousUserIDQueryItem];
}
NSInteger ui_sid = arc4random_uniform(999999999);
NSString *sidString = [NSString stringWithFormat:@"%ld", (long)ui_sid];
[GULUserDefaults.standardUserDefaults setObject:sidString forKey:@"ui_sid"];
NSURLQueryItem *sessionIDQueryItem =
[NSURLQueryItem queryItemWithName:@"ui_sid" value:sidString];
[urlQuertItems addObject:sessionIDQueryItem];
NSString *sameDeviceValueString;
if (self.forceSameDevice) {
sameDeviceValueString = @"1";
} else {
sameDeviceValueString = @"0";
}
NSURLQueryItem *sameDeviceQueryItem = [NSURLQueryItem queryItemWithName:@"ui_sd" value:sameDeviceValueString];
[urlQuertItems addObject:sameDeviceQueryItem];
if (linkingProvider) {
NSURLQueryItem *providerIDQueryItem = [NSURLQueryItem queryItemWithName:@"ui_pid" value:linkingProvider];
[urlQuertItems addObject:providerIDQueryItem];
}
urlComponents.queryItems = urlQuertItems;
self.actionCodeSettings.URL = urlComponents.URL;
}
- (nullable NSString *)authProviderFromProviders:(NSArray <NSString *> *) providers {
NSSet *providerSet =
[NSSet setWithArray:@[ FIRFacebookAuthProviderID,
FIRGoogleAuthProviderID,
FIREmailAuthProviderID ]];
for (NSString *provider in providers) {
if ( [providerSet containsObject:provider]) {
return provider;
}
}
return nil;
}
@end