-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathAuth.swift
2396 lines (2249 loc) · 105 KB
/
Auth.swift
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 2023 Google LLC
//
// 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 Foundation
import FirebaseAppCheckInterop
import FirebaseAuthInterop
import FirebaseCore
import FirebaseCoreExtension
#if COCOAPODS
@_implementationOnly import GoogleUtilities
#else
@_implementationOnly import GoogleUtilities_AppDelegateSwizzler
@_implementationOnly import GoogleUtilities_Environment
#endif
#if os(iOS) || os(tvOS) || targetEnvironment(macCatalyst)
import UIKit
#endif
// Export the deprecated Objective-C defined globals and typedefs.
#if SWIFT_PACKAGE
@_exported import FirebaseAuthInternal
#endif // SWIFT_PACKAGE
#if os(iOS)
@available(iOS 13.0, *)
extension Auth: UISceneDelegate {
open func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
let _ = canHandle(urlContext.url)
}
}
}
@available(iOS 13.0, *)
extension Auth: UIApplicationDelegate {
open func application(_ application: UIApplication,
didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
setAPNSToken(deviceToken, type: .unknown)
}
open func application(_ application: UIApplication,
didFailToRegisterForRemoteNotificationsWithError error: Error) {
kAuthGlobalWorkQueue.sync {
self.tokenManager.cancel(withError: error)
}
}
open func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler:
@escaping (UIBackgroundFetchResult) -> Void) {
_ = canHandleNotification(userInfo)
completionHandler(UIBackgroundFetchResult.noData)
}
open func application(_ application: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any]) -> Bool {
return canHandle(url)
}
}
#endif
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
extension Auth: AuthInterop {
/// Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
///
/// This method is not for public use. It is for Firebase clients of AuthInterop.
@objc(getTokenForcingRefresh:withCallback:)
public func getToken(forcingRefresh forceRefresh: Bool,
completion callback: @escaping (String?, Error?) -> Void) {
kAuthGlobalWorkQueue.async { [weak self] in
if let strongSelf = self {
// Enable token auto-refresh if not already enabled.
if !strongSelf.autoRefreshTokens {
AuthLog.logInfo(code: "I-AUT000002", message: "Token auto-refresh enabled.")
strongSelf.autoRefreshTokens = true
strongSelf.scheduleAutoTokenRefresh()
#if os(iOS) || os(tvOS) // TODO(ObjC): Is a similar mechanism needed on macOS?
strongSelf.applicationDidBecomeActiveObserver =
NotificationCenter.default.addObserver(
forName: UIApplication.didBecomeActiveNotification,
object: nil, queue: nil
) { notification in
if let strongSelf = self {
strongSelf.isAppInBackground = false
if !strongSelf.autoRefreshScheduled {
strongSelf.scheduleAutoTokenRefresh()
}
}
}
strongSelf.applicationDidEnterBackgroundObserver =
NotificationCenter.default.addObserver(
forName: UIApplication.didEnterBackgroundNotification,
object: nil, queue: nil
) { notification in
if let strongSelf = self {
strongSelf.isAppInBackground = true
}
}
#endif
}
}
// Call back with 'nil' if there is no current user.
guard let strongSelf = self, let currentUser = strongSelf.currentUser else {
DispatchQueue.main.async {
callback(nil, nil)
}
return
}
// Call back with current user token.
currentUser.internalGetToken(forceRefresh: forceRefresh) { token, error in
DispatchQueue.main.async {
callback(token, error)
}
}
}
}
/// Get the current Auth user's UID. Returns nil if there is no user signed in.
///
/// This method is not for public use. It is for Firebase clients of AuthInterop.
open func getUserID() -> String? {
return currentUser?.uid
}
}
/// Manages authentication for Firebase apps.
///
/// This class is thread-safe.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
@objc(FIRAuth) open class Auth: NSObject {
/// Gets the auth object for the default Firebase app.
///
/// The default Firebase app must have already been configured or an exception will be raised.
@objc open class func auth() -> Auth {
guard let defaultApp = FirebaseApp.app() else {
fatalError("The default FirebaseApp instance must be configured before the default Auth " +
"instance can be initialized. One way to ensure this is to call " +
"`FirebaseApp.configure()` in the App Delegate's " +
"`application(_:didFinishLaunchingWithOptions:)` (or the `@main` struct's " +
"initializer in SwiftUI).")
}
return auth(app: defaultApp)
}
/// Gets the auth object for a `FirebaseApp`.
/// - Parameter app: The app for which to retrieve the associated `Auth` instance.
/// - Returns: The `Auth` instance associated with the given app.
@objc open class func auth(app: FirebaseApp) -> Auth {
return ComponentType<AuthInterop>.instance(for: AuthInterop.self, in: app.container) as! Auth
}
/// Gets the `FirebaseApp` object that this auth object is connected to.
@objc public internal(set) weak var app: FirebaseApp?
/// Synchronously gets the cached current user, or null if there is none.
@objc public internal(set) var currentUser: User?
/// The current user language code.
///
/// This property can be set to the app's current language by
/// calling `useAppLanguage()`.
///
/// The string used to set this property must be a language code that follows BCP 47.
@objc open var languageCode: String? {
get {
kAuthGlobalWorkQueue.sync {
requestConfiguration.languageCode
}
}
set(val) {
kAuthGlobalWorkQueue.sync {
requestConfiguration.languageCode = val
}
}
}
/// Contains settings related to the auth object.
@NSCopying @objc open var settings: AuthSettings?
/// The current user access group that the Auth instance is using.
///
/// Default is `nil`.
@objc public internal(set) var userAccessGroup: String?
/// Contains shareAuthStateAcrossDevices setting related to the auth object.
///
/// If userAccessGroup is not set, setting shareAuthStateAcrossDevices will
/// have no effect. You should set shareAuthStateAcrossDevices to its desired
/// state and then set the userAccessGroup after.
@objc open var shareAuthStateAcrossDevices: Bool = false
/// The tenant ID of the auth instance. `nil` if none is available.
@objc open var tenantID: String?
/// The custom authentication domain used to handle all sign-in redirects.
/// End-users will see
/// this domain when signing in. This domain must be allowlisted in the Firebase Console.
@objc open var customAuthDomain: String?
/// Sets the `currentUser` on the receiver to the provided user object.
/// - Parameters:
/// - user: The user object to be set as the current user of the calling Auth instance.
/// - completion: Optionally; a block invoked after the user of the calling Auth instance has
/// been updated or an error was encountered.
@objc open func updateCurrentUser(_ user: User?, completion: ((Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
guard let user else {
let error = AuthErrorUtils.nullUserError(message: nil)
Auth.wrapMainAsync(completion, error)
return
}
let updateUserBlock: (User) -> Void = { user in
do {
try self.updateCurrentUser(user, byForce: true, savingToDisk: true)
Auth.wrapMainAsync(completion, nil)
} catch {
Auth.wrapMainAsync(completion, error)
}
}
if user.requestConfiguration.apiKey != self.requestConfiguration.apiKey {
// If the API keys are different, then we need to confirm that the user belongs to the same
// project before proceeding.
user.requestConfiguration = self.requestConfiguration
user.reload { error in
if let error {
Auth.wrapMainAsync(completion, error)
return
}
updateUserBlock(user)
}
} else {
updateUserBlock(user)
}
}
}
/// Sets the `currentUser` on the receiver to the provided user object.
/// - Parameter user: The user object to be set as the current user of the calling Auth instance.
/// - Parameter completion: Optionally; a block invoked after the user of the calling Auth
/// instance has been updated or an error was encountered.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
open func updateCurrentUser(_ user: User) async throws {
return try await withCheckedThrowingContinuation { continuation in
self.updateCurrentUser(user) { error in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume()
}
}
}
}
/// [Deprecated] Fetches the list of all sign-in methods previously used for the provided
/// email address. This method returns an empty list when [Email Enumeration
/// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
/// is enabled, irrespective of the number of authentication methods available for the given
/// email.
///
/// Possible error codes: `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
///
/// - Parameter email: The email address for which to obtain a list of sign-in methods.
/// - Parameter completion: Optionally; a block which is invoked when the list of sign in methods
/// for the specified email address is ready or an error was encountered. Invoked asynchronously
/// on the main thread in the future.
#if !FIREBASE_CI
@available(
*,
deprecated,
message: "`fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled."
)
#endif // !FIREBASE_CI
@objc open func fetchSignInMethods(forEmail email: String,
completion: (([String]?, Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
let request = CreateAuthURIRequest(identifier: email,
continueURI: "http://www.google.com/",
requestConfiguration: self.requestConfiguration)
Task {
do {
let response = try await AuthBackend.call(with: request)
Auth.wrapMainAsync(callback: completion, withParam: response.signinMethods, error: nil)
} catch {
Auth.wrapMainAsync(callback: completion, withParam: nil, error: error)
}
}
}
}
/// [Deprecated] Fetches the list of all sign-in methods previously used for the provided
/// email address. This method returns an empty list when [Email Enumeration
/// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
/// is enabled, irrespective of the number of authentication methods available for the given
/// email.
///
/// Possible error codes: `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
///
/// - Parameter email: The email address for which to obtain a list of sign-in methods.
/// - Returns: List of sign-in methods
@available(
*,
deprecated,
message: "`fetchSignInMethods` is deprecated and will be removed in a future release. This method returns an empty list when Email Enumeration Protection is enabled."
)
open func fetchSignInMethods(forEmail email: String) async throws -> [String] {
return try await withCheckedThrowingContinuation { continuation in
self.fetchSignInMethods(forEmail: email) { methods, error in
if let methods {
continuation.resume(returning: methods)
} else {
continuation.resume(throwing: error!)
}
}
}
}
/// Signs in using an email address and password.
///
/// When [Email Enumeration
/// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
/// is enabled, this method fails with an error in case of an invalid
/// email/password.
///
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
/// accounts are not enabled. Enable them in the Auth section of the
/// Firebase console.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
/// sign in with an incorrect password.
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// - Parameter email: The user's email address.
/// - Parameter password: The user's password.
/// - Parameter completion: Optionally; a block which is invoked when the sign in flow finishes,
/// or is canceled. Invoked asynchronously on the main thread in the future.
@objc open func signIn(withEmail email: String,
password: String,
completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
Task {
do {
let authData = try await self.internalSignInAndRetrieveData(
withEmail: email,
password: password
)
decoratedCallback(authData, nil)
} catch {
decoratedCallback(nil, error)
}
}
}
}
/// Signs in using an email address and password.
///
/// When [Email Enumeration
/// Protection](https://cloud.google.com/identity-platform/docs/admin/email-enumeration-protection)
/// is enabled, this method throws in case of an invalid email/password.
///
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
/// accounts are not enabled. Enable them in the Auth section of the
/// Firebase console.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
/// sign in with an incorrect password.
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// - Parameter email: The user's email address.
/// - Parameter password: The user's password.
/// - Returns: The signed in user.
func internalSignInUser(withEmail email: String,
password: String) async throws -> User {
let request = VerifyPasswordRequest(email: email,
password: password,
requestConfiguration: requestConfiguration)
if request.password.count == 0 {
throw AuthErrorUtils.wrongPasswordError(message: nil)
}
#if os(iOS)
let response = try await injectRecaptcha(request: request,
action: AuthRecaptchaAction.signInWithPassword)
#else
let response = try await AuthBackend.call(with: request)
#endif
return try await completeSignIn(
withAccessToken: response.idToken,
accessTokenExpirationDate: response.approximateExpirationDate,
refreshToken: response.refreshToken,
anonymous: false
)
}
/// Signs in using an email address and password.
///
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
/// accounts are not enabled. Enable them in the Auth section of the
/// Firebase console.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
/// sign in with an incorrect password.
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// - Parameter email: The user's email address.
/// - Parameter password: The user's password.
/// - Returns: The `AuthDataResult` after a successful signin.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
@discardableResult
open func signIn(withEmail email: String, password: String) async throws -> AuthDataResult {
return try await withCheckedThrowingContinuation { continuation in
self.signIn(withEmail: email, password: password) { authData, error in
if let authData {
continuation.resume(returning: authData)
} else {
continuation.resume(throwing: error!)
}
}
}
}
/// Signs in using an email address and email sign-in link.
///
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
/// accounts are not enabled. Enable them in the Auth section of the
/// Firebase console.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
/// sign in with an incorrect password.
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// - Parameter email: The user's email address.
/// - Parameter link: The email sign-in link.
/// - Parameter completion: Optionally; a block which is invoked when the sign in flow finishes,
/// or is canceled. Invoked asynchronously on the main thread in the future.
@objc open func signIn(withEmail email: String,
link: String,
completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
let credential = EmailAuthCredential(withEmail: email, link: link)
Task {
do {
let authData = try await self.internalSignInAndRetrieveData(withCredential: credential,
isReauthentication: false)
decoratedCallback(authData, nil)
} catch {
decoratedCallback(nil, error)
}
}
}
}
/// Signs in using an email address and email sign-in link.
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
/// accounts are not enabled. Enable them in the Auth section of the
/// Firebase console.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
/// sign in with an incorrect password.
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// - Parameter email: The user's email address.
/// - Parameter link: The email sign-in link.
/// - Returns: The `AuthDataResult` after a successful signin.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
open func signIn(withEmail email: String, link: String) async throws -> AuthDataResult {
return try await withCheckedThrowingContinuation { continuation in
self.signIn(withEmail: email, link: link) { result, error in
if let result {
continuation.resume(returning: result)
} else {
continuation.resume(throwing: error!)
}
}
}
}
#if os(iOS)
/// Signs in using the provided auth provider instance.
///
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
/// accounts are not enabled. Enable them in the Auth section of the
/// Firebase console.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
/// sign in with an incorrect password.
/// * `AuthErrorCodeWebNetworkRequestFailed` - Indicates that a network request within a
/// SFSafariViewController or WKWebView failed.
/// * `AuthErrorCodeWebInternalError` - Indicates that an internal error occurred within a
/// SFSafariViewController or WKWebView.
/// * `AuthErrorCodeWebSignInUserInteractionFailure` - Indicates a general failure during
/// a web sign-in flow.
/// * `AuthErrorCodeWebContextAlreadyPresented` - Indicates that an attempt was made to
/// present a new web context while one was already being presented.
/// * `AuthErrorCodeWebContextCancelled` - Indicates that the URL presentation was
/// cancelled prematurely by the user.
/// * `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted
/// by the credential (e.g. the email in a Facebook access token) is already in use by an
/// existing account, that cannot be authenticated with this sign-in method. Call
/// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of
/// the sign-in providers returned. This error will only be thrown if the "One account per
/// email address" setting is enabled in the Firebase console, under Auth settings.
/// - Parameter provider: An instance of an auth provider used to initiate the sign-in flow.
/// - Parameter uiDelegate: Optionally an instance of a class conforming to the AuthUIDelegate
/// protocol, this is used for presenting the web context. If nil, a default AuthUIDelegate
/// will be used.
/// - Parameter completion: Optionally; a block which is invoked when the sign in flow finishes,
/// or is canceled. Invoked asynchronously on the main thread in the future.
@available(tvOS, unavailable)
@available(macOS, unavailable)
@available(watchOS, unavailable)
@objc(signInWithProvider:UIDelegate:completion:)
open func signIn(with provider: FederatedAuthProvider,
uiDelegate: AuthUIDelegate?,
completion: ((AuthDataResult?, Error?) -> Void)?) {
kAuthGlobalWorkQueue.async {
Task {
let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
do {
let credential = try await provider.credential(with: uiDelegate)
let authData = try await self.internalSignInAndRetrieveData(
withCredential: credential,
isReauthentication: false
)
decoratedCallback(authData, nil)
} catch {
decoratedCallback(nil, error)
}
}
}
}
/// Signs in using the provided auth provider instance.
///
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password
/// accounts are not enabled. Enable them in the Auth section of the
/// Firebase console.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted
/// sign in with an incorrect password.
/// * `AuthErrorCodeWebNetworkRequestFailed` - Indicates that a network request within a
/// SFSafariViewController or WKWebView failed.
/// * `AuthErrorCodeWebInternalError` - Indicates that an internal error occurred within a
/// SFSafariViewController or WKWebView.
/// * `AuthErrorCodeWebSignInUserInteractionFailure` - Indicates a general failure during
/// a web sign-in flow.
/// * `AuthErrorCodeWebContextAlreadyPresented` - Indicates that an attempt was made to
/// present a new web context while one was already being presented.
/// * `AuthErrorCodeWebContextCancelled` - Indicates that the URL presentation was
/// cancelled prematurely by the user.
/// * `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted
/// by the credential (e.g. the email in a Facebook access token) is already in use by an
/// existing account, that cannot be authenticated with this sign-in method. Call
/// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of
/// the sign-in providers returned. This error will only be thrown if the "One account per
/// email address" setting is enabled in the Firebase console, under Auth settings.
/// - Parameter provider: An instance of an auth provider used to initiate the sign-in flow.
/// - Parameter uiDelegate: Optionally an instance of a class conforming to the AuthUIDelegate
/// protocol, this is used for presenting the web context. If nil, a default AuthUIDelegate
/// will be used.
/// - Returns: The `AuthDataResult` after the successful signin.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
@available(tvOS, unavailable)
@available(macOS, unavailable)
@available(watchOS, unavailable)
@discardableResult
open func signIn(with provider: FederatedAuthProvider,
uiDelegate: AuthUIDelegate?) async throws -> AuthDataResult {
return try await withCheckedThrowingContinuation { continuation in
self.signIn(with: provider, uiDelegate: uiDelegate) { result, error in
if let result {
continuation.resume(returning: result)
} else {
continuation.resume(throwing: error!)
}
}
}
}
#endif // iOS
/// Asynchronously signs in to Firebase with the given 3rd-party credentials (e.g. a Facebook
/// login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional
/// identity provider data.
///
/// Possible error codes:
/// * `AuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid.
/// This could happen if it has expired or it is malformed.
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that accounts
/// with the identity provider represented by the credential are not enabled.
/// Enable them in the Auth section of the Firebase console.
/// * `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted
/// by the credential (e.g. the email in a Facebook access token) is already in use by an
/// existing account, that cannot be authenticated with this sign-in method. Call
/// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of
/// the sign-in providers returned. This error will only be thrown if the "One account per
/// email address" setting is enabled in the Firebase console, under Auth settings.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted sign in with an
/// incorrect password, if credential is of the type EmailPasswordAuthCredential.
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// * `AuthErrorCodeMissingVerificationID` - Indicates that the phone auth credential was
/// created with an empty verification ID.
/// * `AuthErrorCodeMissingVerificationCode` - Indicates that the phone auth credential
/// was created with an empty verification code.
/// * `AuthErrorCodeInvalidVerificationCode` - Indicates that the phone auth credential
/// was created with an invalid verification Code.
/// * `AuthErrorCodeInvalidVerificationID` - Indicates that the phone auth credential was
/// created with an invalid verification ID.
/// * `AuthErrorCodeSessionExpired` - Indicates that the SMS code has expired.
/// - Parameter credential: The credential supplied by the IdP.
/// - Parameter completion: Optionally; a block which is invoked when the sign in flow finishes,
/// or is canceled. Invoked asynchronously on the main thread in the future.
@objc(signInWithCredential:completion:)
open func signIn(with credential: AuthCredential,
completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
Task {
do {
let authData = try await self.internalSignInAndRetrieveData(withCredential: credential,
isReauthentication: false)
decoratedCallback(authData, nil)
} catch {
decoratedCallback(nil, error)
}
}
}
}
/// Asynchronously signs in to Firebase with the given 3rd-party credentials (e.g. a Facebook
/// login Access Token, a Google ID Token/Access Token pair, etc.) and returns additional
/// identity provider data.
///
/// Possible error codes:
/// * `AuthErrorCodeInvalidCredential` - Indicates the supplied credential is invalid.
/// This could happen if it has expired or it is malformed.
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that accounts
/// with the identity provider represented by the credential are not enabled.
/// Enable them in the Auth section of the Firebase console.
/// * `AuthErrorCodeAccountExistsWithDifferentCredential` - Indicates the email asserted
/// by the credential (e.g. the email in a Facebook access token) is already in use by an
/// existing account, that cannot be authenticated with this sign-in method. Call
/// fetchProvidersForEmail for this user’s email and then prompt them to sign in with any of
/// the sign-in providers returned. This error will only be thrown if the "One account per
/// email address" setting is enabled in the Firebase console, under Auth settings.
/// * `AuthErrorCodeUserDisabled` - Indicates the user's account is disabled.
/// * `AuthErrorCodeWrongPassword` - Indicates the user attempted sign in with an
/// incorrect password, if credential is of the type EmailPasswordAuthCredential.
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// * `AuthErrorCodeMissingVerificationID` - Indicates that the phone auth credential was
/// created with an empty verification ID.
/// * `AuthErrorCodeMissingVerificationCode` - Indicates that the phone auth credential
/// was created with an empty verification code.
/// * `AuthErrorCodeInvalidVerificationCode` - Indicates that the phone auth credential
/// was created with an invalid verification Code.
/// * `AuthErrorCodeInvalidVerificationID` - Indicates that the phone auth credential was
/// created with an invalid verification ID.
/// * `AuthErrorCodeSessionExpired` - Indicates that the SMS code has expired.
/// - Parameter credential: The credential supplied by the IdP.
/// - Returns: The `AuthDataResult` after the successful signin.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
@discardableResult
open func signIn(with credential: AuthCredential) async throws -> AuthDataResult {
return try await withCheckedThrowingContinuation { continuation in
self.signIn(with: credential) { result, error in
if let result {
continuation.resume(returning: result)
} else {
continuation.resume(throwing: error!)
}
}
}
}
/// Asynchronously creates and becomes an anonymous user.
///
/// If there is already an anonymous user signed in, that user will be returned instead.
/// If there is any other existing user signed in, that user will be signed out.
///
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that anonymous accounts are
/// not enabled. Enable them in the Auth section of the Firebase console.
/// - Parameter completion: Optionally; a block which is invoked when the sign in finishes, or is
/// canceled. Invoked asynchronously on the main thread in the future.
@objc open func signInAnonymously(completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
if let currentUser = self.currentUser, currentUser.isAnonymous {
let result = AuthDataResult(withUser: currentUser, additionalUserInfo: nil)
decoratedCallback(result, nil)
return
}
let request = SignUpNewUserRequest(requestConfiguration: self.requestConfiguration)
Task {
do {
let response = try await AuthBackend.call(with: request)
let user = try await self.completeSignIn(
withAccessToken: response.idToken,
accessTokenExpirationDate: response.approximateExpirationDate,
refreshToken: response.refreshToken,
anonymous: true
)
// TODO: The ObjC implementation passed a nil providerID to the nonnull providerID
let additionalUserInfo = AdditionalUserInfo(providerID: "",
profile: nil,
username: nil,
isNewUser: true)
decoratedCallback(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo),
nil)
} catch {
decoratedCallback(nil, error)
}
}
}
}
/// Asynchronously creates and becomes an anonymous user.
///
/// If there is already an anonymous user signed in, that user will be returned instead.
/// If there is any other existing user signed in, that user will be signed out.
///
/// Possible error codes:
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that anonymous accounts are
/// not enabled. Enable them in the Auth section of the Firebase console.
/// - Returns: The `AuthDataResult` after the successful signin.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
@discardableResult
@objc open func signInAnonymously() async throws -> AuthDataResult {
return try await withCheckedThrowingContinuation { continuation in
self.signInAnonymously { result, error in
if let result {
continuation.resume(returning: result)
} else {
continuation.resume(throwing: error!)
}
}
}
}
/// Asynchronously signs in to Firebase with the given Auth token.
///
/// Possible error codes:
/// * `AuthErrorCodeInvalidCustomToken` - Indicates a validation error with
/// the custom token.
/// * `AuthErrorCodeCustomTokenMismatch` - Indicates the service account and the API key
/// belong to different projects.
/// - Parameter token: A self-signed custom auth token.
/// - Parameter completion: Optionally; a block which is invoked when the sign in finishes, or is
/// canceled. Invoked asynchronously on the main thread in the future.
@objc open func signIn(withCustomToken token: String,
completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
kAuthGlobalWorkQueue.async {
let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
let request = VerifyCustomTokenRequest(token: token,
requestConfiguration: self.requestConfiguration)
Task {
do {
let response = try await AuthBackend.call(with: request)
let user = try await self.completeSignIn(
withAccessToken: response.idToken,
accessTokenExpirationDate: response.approximateExpirationDate,
refreshToken: response.refreshToken,
anonymous: false
)
// TODO: The ObjC implementation passed a nil providerID to the nonnull providerID
let additionalUserInfo = AdditionalUserInfo(providerID: "",
profile: nil,
username: nil,
isNewUser: response.isNewUser)
decoratedCallback(AuthDataResult(withUser: user, additionalUserInfo: additionalUserInfo),
nil)
} catch {
decoratedCallback(nil, error)
}
}
}
}
/// Asynchronously signs in to Firebase with the given Auth token.
///
/// Possible error codes:
/// * `AuthErrorCodeInvalidCustomToken` - Indicates a validation error with
/// the custom token.
/// * `AuthErrorCodeCustomTokenMismatch` - Indicates the service account and the API key
/// belong to different projects.
/// - Parameter token: A self-signed custom auth token.
/// - Returns: The `AuthDataResult` after the successful signin.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
@discardableResult
open func signIn(withCustomToken token: String) async throws -> AuthDataResult {
return try await withCheckedThrowingContinuation { continuation in
self.signIn(withCustomToken: token) { result, error in
if let result {
continuation.resume(returning: result)
} else {
continuation.resume(throwing: error!)
}
}
}
}
/// Creates and, on success, signs in a user with the given email address and password.
///
/// Possible error codes:
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email used to attempt sign up
/// already exists. Call fetchProvidersForEmail to check which sign-in mechanisms the user
/// used, and prompt the user to sign in with one of those.
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts
/// are not enabled. Enable them in the Auth section of the Firebase console.
/// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
/// considered too weak. The NSLocalizedFailureReasonErrorKey field in the NSError.userInfo
/// dictionary object will contain more detailed explanation that can be shown to the user.
/// - Parameter email: The user's email address.
/// - Parameter password: The user's desired password.
/// - Parameter completion: Optionally; a block which is invoked when the sign up flow finishes,
/// or is canceled. Invoked asynchronously on the main thread in the future.
@objc open func createUser(withEmail email: String,
password: String,
completion: ((AuthDataResult?, Error?) -> Void)? = nil) {
guard password.count > 0 else {
if let completion {
completion(nil, AuthErrorUtils.weakPasswordError(serverResponseReason: "Missing password"))
}
return
}
guard email.count > 0 else {
if let completion {
completion(nil, AuthErrorUtils.missingEmailError(message: nil))
}
return
}
kAuthGlobalWorkQueue.async {
let decoratedCallback = self.signInFlowAuthDataResultCallback(byDecorating: completion)
let request = SignUpNewUserRequest(email: email,
password: password,
displayName: nil,
idToken: nil,
requestConfiguration: self.requestConfiguration)
#if os(iOS)
self.wrapInjectRecaptcha(request: request,
action: AuthRecaptchaAction.signUpPassword) { response, error in
if let error {
DispatchQueue.main.async {
decoratedCallback(nil, error)
}
return
}
self.internalCreateUserWithEmail(request: request, inResponse: response,
decoratedCallback: decoratedCallback)
}
#else
self.internalCreateUserWithEmail(request: request, decoratedCallback: decoratedCallback)
#endif
}
}
func internalCreateUserWithEmail(request: SignUpNewUserRequest,
inResponse: SignUpNewUserResponse? = nil,
decoratedCallback: @escaping (AuthDataResult?, Error?) -> Void) {
Task {
do {
var response: SignUpNewUserResponse
if let inResponse {
response = inResponse
} else {
response = try await AuthBackend.call(with: request)
}
let user = try await self.completeSignIn(
withAccessToken: response.idToken,
accessTokenExpirationDate: response.approximateExpirationDate,
refreshToken: response.refreshToken,
anonymous: false
)
let additionalUserInfo = AdditionalUserInfo(providerID: EmailAuthProvider.id,
profile: nil,
username: nil,
isNewUser: true)
decoratedCallback(AuthDataResult(withUser: user,
additionalUserInfo: additionalUserInfo),
nil)
} catch {
decoratedCallback(nil, error)
}
}
}
/// Creates and, on success, signs in a user with the given email address and password.
///
/// Possible error codes:
/// * `AuthErrorCodeInvalidEmail` - Indicates the email address is malformed.
/// * `AuthErrorCodeEmailAlreadyInUse` - Indicates the email used to attempt sign up
/// already exists. Call fetchProvidersForEmail to check which sign-in mechanisms the user
/// used, and prompt the user to sign in with one of those.
/// * `AuthErrorCodeOperationNotAllowed` - Indicates that email and password accounts
/// are not enabled. Enable them in the Auth section of the Firebase console.
/// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
/// considered too weak. The NSLocalizedFailureReasonErrorKey field in the NSError.userInfo
/// dictionary object will contain more detailed explanation that can be shown to the user.
/// - Parameter email: The user's email address.
/// - Parameter password: The user's desired password.
/// - Returns: The `AuthDataResult` after the successful signin.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
@discardableResult
open func createUser(withEmail email: String, password: String) async throws -> AuthDataResult {
return try await withCheckedThrowingContinuation { continuation in
self.createUser(withEmail: email, password: password) { result, error in
if let result {
continuation.resume(returning: result)
} else {
continuation.resume(throwing: error!)
}
}
}
}
/// Resets the password given a code sent to the user outside of the app and a new password
/// for the user.
///
/// Possible error codes:
/// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
/// considered too weak.
/// * `AuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled sign
/// in with the specified identity provider.
/// * `AuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired.
/// * `AuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid.
/// - Parameter code: The reset code.
/// - Parameter newPassword: The new password.
/// - Parameter completion: Optionally; a block which is invoked when the request finishes.
/// Invoked asynchronously on the main thread in the future.
@objc open func confirmPasswordReset(withCode code: String, newPassword: String,
completion: @escaping (Error?) -> Void) {
kAuthGlobalWorkQueue.async {
let request = ResetPasswordRequest(oobCode: code,
newPassword: newPassword,
requestConfiguration: self.requestConfiguration)
self.wrapAsyncRPCTask(request, completion)
}
}
/// Resets the password given a code sent to the user outside of the app and a new password
/// for the user.
///
/// Possible error codes:
/// * `AuthErrorCodeWeakPassword` - Indicates an attempt to set a password that is
/// considered too weak.
/// * `AuthErrorCodeOperationNotAllowed` - Indicates the administrator disabled sign
/// in with the specified identity provider.
/// * `AuthErrorCodeExpiredActionCode` - Indicates the OOB code is expired.
/// * `AuthErrorCodeInvalidActionCode` - Indicates the OOB code is invalid.
/// - Parameter code: The reset code.
/// - Parameter newPassword: The new password.
@available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
open func confirmPasswordReset(withCode code: String, newPassword: String) async throws {
return try await withCheckedThrowingContinuation { continuation in
self.confirmPasswordReset(withCode: code, newPassword: newPassword) { error in
if let error {
continuation.resume(throwing: error)
} else {
continuation.resume()
}
}
}
}
/// Checks the validity of an out of band code.
/// - Parameter code: The out of band code to check validity.
/// - Parameter completion: Optionally; a block which is invoked when the request finishes.
/// Invoked
/// asynchronously on the main thread in the future.
@objc open func checkActionCode(_ code: String,
completion: @escaping (ActionCodeInfo?, Error?) -> Void) {
kAuthGlobalWorkQueue.async {
let request = ResetPasswordRequest(oobCode: code,
newPassword: nil,
requestConfiguration: self.requestConfiguration)
Task {
do {
let response = try await AuthBackend.call(with: request)
let operation = ActionCodeInfo.actionCodeOperation(forRequestType: response.requestType)