-
Notifications
You must be signed in to change notification settings - Fork 490
Expand file tree
/
Copy pathAuthService.swift
More file actions
1317 lines (1145 loc) · 42.9 KB
/
AuthService.swift
File metadata and controls
1317 lines (1145 loc) · 42.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
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 2025 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.
@preconcurrency import FirebaseAuth
import FirebaseAuthUIComponents
import FirebaseCore
import SwiftUI
/// Base protocol for all authentication providers
public protocol AuthProviderSwift {}
/// Protocol for providers that can directly create an AuthCredential
/// Used by Google, Apple, Twitter, Facebook, and OAuth providers
public protocol CredentialAuthProviderSwift: AuthProviderSwift {
@MainActor func createAuthCredential() async throws -> AuthCredential
}
public protocol AuthProviderUI {
var id: String { get }
var displayName: String { get }
@MainActor func authButton() -> AnyView
var provider: AuthProviderSwift { get }
}
public enum AuthenticationState {
case unauthenticated
case authenticating
case authenticated
}
public enum AuthenticationFlow {
case signIn
case signUp
}
public enum AuthView: Hashable {
case passwordRecovery
case emailLink
case updatePassword
case mfaEnrollment
case mfaManagement
case mfaResolution(MFARequired)
case enterPhoneNumber
case enterVerificationCode(verificationID: String, fullPhoneNumber: String)
}
public enum SignInOutcome: @unchecked Sendable {
case mfaRequired(MFARequired)
case signedIn(AuthDataResult?)
}
public struct LegacySignInOption: Identifiable, Equatable {
public let id: String
public let displayName: String
public init(id: String, displayName: String) {
self.id = id
self.displayName = displayName
}
}
public struct LegacySignInRecoveryContext: Identifiable, Equatable {
public let id = UUID()
public let email: String
public let options: [LegacySignInOption]
public let unavailableProviders: [String]
public init(email: String,
options: [LegacySignInOption],
unavailableProviders: [String] = []) {
self.email = email
self.options = options
self.unavailableProviders = unavailableProviders
}
public static func == (lhs: LegacySignInRecoveryContext,
rhs: LegacySignInRecoveryContext) -> Bool {
lhs.id == rhs.id
}
}
@MainActor
private final class AuthListenerManager {
private var authStateHandle: AuthStateDidChangeListenerHandle?
private let auth: Auth
private weak var authEnvironment: AuthService?
init(auth: Auth, authEnvironment: AuthService) {
self.auth = auth
self.authEnvironment = authEnvironment
setupAuthenticationListener()
}
deinit {
if let handle = authStateHandle {
auth.removeStateDidChangeListener(handle)
}
}
private func setupAuthenticationListener() {
authStateHandle = auth.addStateDidChangeListener { [weak self] _, user in
self?.authEnvironment?.currentUser = user
self?.authEnvironment?.updateAuthenticationState()
}
}
}
@Observable
public class Navigator {
var routes: [AuthView] = []
public func push(_ route: AuthView) {
routes.append(route)
}
@discardableResult
public func pop() -> AuthView? {
routes.popLast()
}
public func clear() {
routes.removeAll()
}
}
@MainActor
@Observable
public final class AuthService {
public init(configuration: AuthConfiguration = AuthConfiguration(), auth: Auth = Auth.auth()) {
self.auth = auth
self.configuration = configuration
string = StringUtils(
bundle: configuration.customStringsBundle ?? Bundle.module,
languageCode: configuration.languageCode
)
listenerManager = AuthListenerManager(auth: auth, authEnvironment: self)
FirebaseApp.registerLibrary("firebase-ui-ios", withVersion: FirebaseAuthSwiftUIVersion.version)
}
@ObservationIgnored @AppStorage("email-link") public var emailLink: String?
// Needed because provider data sign-in doesn't distinguish between email link and password
// sign-in needed for reauthentication
@ObservationIgnored @AppStorage("is-email-link") private var isEmailLinkSignIn: Bool = false
// Storage for email link reauthentication (separate from sign-in)
@ObservationIgnored @AppStorage("email-link-reauth") private var emailLinkReauth: String?
@ObservationIgnored @AppStorage("is-reauthenticating") private var isReauthenticating: Bool =
false
private var currentMFAResolver: MultiFactorResolver?
private var listenerManager: AuthListenerManager?
private var emailLinkSignInCallback: (() -> Void)?
private var providers: [AuthProviderUI] = []
private let emailLinkSignInMethod = "emailLink"
public let configuration: AuthConfiguration
public let auth: Auth
public var isPresented: Bool = false
public let string: StringUtils
public var currentUser: User?
public var authenticationState: AuthenticationState = .unauthenticated
public var authenticationFlow: AuthenticationFlow = .signIn
public var emailPasswordSignInEnabled = false
public var emailLinkSignInEnabled = false
public var legacySignInRecovery: LegacySignInRecoveryContext?
public var suggestedEmailAddress: String?
public private(set) var navigator = Navigator()
public var authView: AuthView? {
navigator.routes.last
}
public func registerProvider(providerWithButton: AuthProviderUI) {
providers.append(providerWithButton)
}
public func renderButtons(spacing: CGFloat = 16) -> AnyView {
AnyView(
VStack(spacing: spacing) {
if emailLinkSignInEnabled {
AuthProviderButton(
label: string.signInWithEmailLinkViewTitle,
style: .email,
accessibilityId: "sign-in-with-email-link-button"
) {
if let callback = self.emailLinkSignInCallback {
callback()
} else {
self.navigator.push(.emailLink)
}
}
}
ForEach(providers, id: \.id) { provider in
provider.authButton()
}
}
)
}
public func renderLegacyRecoveryButtons(spacing: CGFloat = 16) -> AnyView {
AnyView(
VStack(spacing: spacing) {
if let recovery = legacySignInRecovery {
ForEach(recovery.options) { option in
self.legacyRecoveryButton(for: option, email: recovery.email)
}
}
}
)
}
public func signIn(_ provider: CredentialAuthProviderSwift) async throws -> SignInOutcome {
let credential = try await provider.createAuthCredential()
let result = try await signIn(credentials: credential)
return result
}
public func signOut() async throws {
try await auth.signOut()
// Cannot wait for auth listener to change, feedback needs to be immediate
currentUser = nil
// Clear email link sign-in flag
isEmailLinkSignIn = false
// Clear email link reauth state
emailLinkReauth = nil
isReauthenticating = false
legacySignInRecovery = nil
suggestedEmailAddress = nil
updateAuthenticationState()
}
public func linkAccounts(credentials credentials: AuthCredential) async throws {
authenticationState = .authenticating
do {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
try await user.link(with: credentials)
updateAuthenticationState()
} catch {
authenticationState = .unauthenticated
// Check for reauthentication errors first
try await handleErrorWithReauthCheck(error: error)
// If not a reauth error, check for conflicts
// Possible conflicts from user.link():
// - credentialAlreadyInUse: credential is already linked to another account
// - emailAlreadyInUse: email from credential is already used by another account
// - accountExistsWithDifferentCredential: account exists with different sign-in method
try handleErrorWithConflictCheck(error: error, credential: credentials)
}
}
public func signIn(credentials: AuthCredential) async throws -> SignInOutcome {
authenticationState = .authenticating
do {
if shouldHandleAnonymousUpgrade {
return try await handleAutoUpgradeAnonymousUser(credentials: credentials)
} else {
let result = try await auth.signIn(with: credentials)
updateAuthenticationState()
return .signedIn(result)
}
} catch let error as NSError {
authenticationState = .unauthenticated
// Check if this is an MFA required error
if error.code == AuthErrorCode.secondFactorRequired.rawValue {
if let resolver = error
.userInfo[AuthErrorUserInfoMultiFactorResolverKey] as? MultiFactorResolver {
return handleMFARequiredError(resolver: resolver)
}
}
// Possible conflicts from auth.signIn(with:):
// - accountExistsWithDifferentCredential: account exists with different provider
// - credentialAlreadyInUse: credential is already linked to another account
try handleErrorWithConflictCheck(error: error, credential: credentials)
}
}
public func sendEmailVerification() async throws {
if let user = currentUser {
// Requires running on MainActor as passing to sendEmailVerification() which is non-isolated
let settings: ActionCodeSettings? = await MainActor.run {
configuration.verifyEmailActionCodeSettings
}
if let settings = settings {
try await user.sendEmailVerification(with: settings)
} else {
try await user.sendEmailVerification()
}
}
}
/// Reauthenticates with an OAuth provider (Google, Apple, Facebook, Twitter, etc.)
/// - Parameter context: The reauth context from `oauthReauthenticationRequired` error
/// - Throws: Error if reauthentication fails or provider is not found
/// - Note: This only works for providers that can automatically obtain credentials.
/// For email/phone, handle the flow externally and use `reauthenticate(with:)`
public func reauthenticate(context: OAuthReauthContext) async throws {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
// Find the provider and get credential
guard let matchingProvider = providers.first(where: { $0.id == context.providerId }),
let credentialProvider = matchingProvider.provider as? CredentialAuthProviderSwift else {
throw AuthServiceError.providerNotFound("No provider found for \(context.providerId)")
}
let credential = try await credentialProvider.createAuthCredential()
try await user.reauthenticate(with: credential)
currentUser = auth.currentUser
}
/// Reauthenticates with a pre-obtained credential
/// Use this when you've handled getting the credential yourself (email/phone)
/// - Parameter credential: The authentication credential to use for reauthentication
/// - Throws: Error if reauthentication fails
public func reauthenticate(with credential: AuthCredential) async throws {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
try await user.reauthenticate(with: credential)
currentUser = auth.currentUser
}
}
// MARK: - User API
public extension AuthService {
func deleteUser() async throws {
guard let user = auth.currentUser else {
throw AuthServiceError.noCurrentUser
}
do {
try await user.delete()
} catch {
try await handleErrorWithReauthCheck(error: error)
throw error // If we reach here, it wasn't a reauth error, so rethrow
}
}
func updatePassword(to password: String) async throws {
guard let user = auth.currentUser else {
throw AuthServiceError.noCurrentUser
}
do {
try await user.updatePassword(to: password)
} catch {
try await handleErrorWithReauthCheck(error: error)
throw error // If we reach here, it wasn't a reauth error, so rethrow
}
}
func updateUserPhotoURL(url: URL) async throws {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
let changeRequest = user.createProfileChangeRequest()
changeRequest.photoURL = url
try await changeRequest.commitChanges()
}
func updateUserDisplayName(name: String) async throws {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
let changeRequest = user.createProfileChangeRequest()
changeRequest.displayName = name
try await changeRequest.commitChanges()
}
}
// MARK: - Email/Password Sign In
public extension AuthService {
/// Enable email/password sign-in (EmailAuthView is shown directly in AuthPickerView)
func withEmailSignIn() -> AuthService {
emailPasswordSignInEnabled = true
return self
}
func signIn(email: String, password: String) async throws -> SignInOutcome {
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
do {
return try await signIn(credentials: credential)
} catch {
if await tryPresentLegacySignInRecovery(
email: email,
attemptedProviderId: EmailAuthProviderID
) {
throw AuthServiceError.legacySignInRecoveryPresented
}
throw error
}
}
func createUser(email email: String, password: String) async throws -> SignInOutcome {
authenticationState = .authenticating
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
do {
if shouldHandleAnonymousUpgrade {
return try await handleAutoUpgradeAnonymousUser(credentials: credential)
} else {
let result = try await auth.createUser(withEmail: email, password: password)
updateAuthenticationState()
return .signedIn(result)
}
} catch {
// Possible conflicts from auth.createUser():
// - emailAlreadyInUse: email is already registered with another account
authenticationState = .unauthenticated
try handleErrorWithConflictCheck(error: error, credential: credential)
}
}
func sendPasswordRecoveryEmail(email: String) async throws {
try await auth.sendPasswordReset(withEmail: email)
}
}
// MARK: - Email Link Sign In
public extension AuthService {
/// Enable email link sign-in with default behavior (navigates to email link view)
func withEmailLinkSignIn() -> AuthService {
return withEmailLinkSignIn { [weak self] in
self?.navigator.push(.emailLink)
}
}
/// Enable email link sign-in with custom callback
func withEmailLinkSignIn(onTap: @escaping () -> Void) -> AuthService {
emailLinkSignInEnabled = true
emailLinkSignInCallback = onTap
return self
}
/// Send email link for sign-in or reauthentication
/// - Parameters:
/// - email: Email address to send link to
/// - isReauth: Whether this is for reauthentication (default: false)
func sendEmailSignInLink(email: String, isReauth: Bool = false) async throws {
let actionCodeSettings = try updateActionCodeSettings()
try await auth.sendSignInLink(
toEmail: email,
actionCodeSettings: actionCodeSettings
)
// Store email based on context
if isReauth {
emailLinkReauth = email
isReauthenticating = true
}
}
func handleSignInLink(url url: URL) async throws {
do {
// Check which flow we're in based on the flag
let email: String
let isReauth = isReauthenticating
if isReauth {
guard let reauthEmail = emailLinkReauth else {
throw AuthServiceError
.invalidEmailLink("Email address is missing for reauthentication")
}
email = reauthEmail
} else {
guard let signInEmail = emailLink else {
throw AuthServiceError
.invalidEmailLink("email address is missing from app storage. Is this the same device?")
}
email = signInEmail
}
let urlString = url.absoluteString
guard let originalLink = CommonUtils.getQueryParamValue(from: urlString, paramName: "link")
else {
throw AuthServiceError
.invalidEmailLink("'link' parameter is missing from the email link URL")
}
guard let link = originalLink.removingPercentEncoding else {
throw AuthServiceError
.invalidEmailLink("Failed to decode Link URL")
}
if auth.isSignIn(withEmailLink: link) {
let credential = EmailAuthProvider.credential(withEmail: email, link: link)
if isReauth {
// Reauthentication flow
try await reauthenticate(with: credential)
// Clean up reauth state
emailLinkReauth = nil
isReauthenticating = false
} else {
// Sign-in flow
guard let continueUrl = CommonUtils.getQueryParamValue(
from: link,
paramName: "continueUrl"
)
else {
throw AuthServiceError
.invalidEmailLink("`continueUrl` parameter is missing from the email link URL")
}
let anonymousUserID = CommonUtils.getQueryParamValue(
from: continueUrl,
paramName: "ui_auid"
)
if shouldHandleAnonymousUpgrade, anonymousUserID == currentUser?.uid {
try await handleAutoUpgradeAnonymousUser(credentials: credential)
} else {
let result = try await auth.signIn(withEmail: email, link: link)
}
updateAuthenticationState()
// Track that user signed in with email link
isEmailLinkSignIn = true
emailLink = nil
}
}
} catch {
// Determine which email to use for error handling
let email = isReauthenticating ? emailLinkReauth : emailLink
let link = url.absoluteString
guard let email = email else {
throw AuthServiceError
.invalidEmailLink("email address is missing from app storage")
}
let credential = EmailAuthProvider.credential(withEmail: email, link: link)
// Only handle conflicts for sign-in flow, not reauth
if !isReauthenticating {
// Possible conflicts from auth.signIn(withEmail:link:):
// - accountExistsWithDifferentCredential: account exists with different provider
// - credentialAlreadyInUse: credential is already linked to another account
try handleErrorWithConflictCheck(error: error, credential: credential)
} else {
// For reauth, just rethrow
throw error
}
}
}
}
// MARK: - Phone Auth Sign In
public extension AuthService {
func verifyPhoneNumber(phoneNumber: String) async throws -> String {
return try await withCheckedThrowingContinuation { continuation in
PhoneAuthProvider.provider()
.verifyPhoneNumber(phoneNumber, uiDelegate: nil) { verificationID, error in
if let error = error {
continuation.resume(throwing: error)
return
}
continuation.resume(returning: verificationID!)
}
}
}
func signInWithPhoneNumber(verificationID: String, verificationCode: String) async throws {
let credential = PhoneAuthProvider.provider()
.credential(withVerificationID: verificationID, verificationCode: verificationCode)
try await signIn(credentials: credential)
}
}
// MARK: - MFA Methods
public extension AuthService {
func startMfaEnrollment(type: SecondFactorType, accountName: String? = nil,
issuer: String? = nil) async throws -> EnrollmentSession {
guard let user = auth.currentUser else {
throw AuthServiceError.noCurrentUser
}
// Check if MFA is enabled in configuration
guard configuration.mfaEnabled else {
throw AuthServiceError
.multiFactorAuth(
"MFA is not enabled in configuration, please enable `AuthConfiguration.mfaEnabled`"
)
}
// Check if the requested factor type is allowed
guard configuration.allowedSecondFactors.contains(type) else {
throw AuthServiceError
.multiFactorAuth(
"The requested MFA factor type '\(type)' is not allowed in AuthConfiguration.allowedSecondFactors"
)
}
let multiFactorUser = user.multiFactor
// Get the multi-factor session
let session = try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<
MultiFactorSession,
Error
>) in
multiFactorUser.getSessionWithCompletion { session, error in
if let error = error {
continuation.resume(throwing: error)
} else if let session = session {
continuation.resume(returning: session)
} else {
continuation
.resume(throwing: AuthServiceError
.multiFactorAuth("Failed to get MFA session for '\(type)'"))
}
}
}
switch type {
case .sms:
// For SMS, we just return the session - phone number will be provided in
// sendSmsVerificationForEnrollment
return EnrollmentSession(
type: .sms,
session: session,
status: .initiated
)
case .totp:
// For TOTP, generate the secret and QR code
let totpSecret = try await TOTPMultiFactorGenerator.generateSecret(with: session)
// Generate QR code URL
let resolvedAccountName = accountName ?? user.email ?? "User"
let resolvedIssuer = issuer ?? configuration.mfaIssuer
let qrCodeURL = totpSecret.generateQRCodeURL(
withAccountName: resolvedAccountName,
issuer: resolvedIssuer
)
let totpInfo = TOTPEnrollmentInfo(
sharedSecretKey: totpSecret.sharedSecretKey(),
qrCodeURL: URL(string: qrCodeURL),
accountName: resolvedAccountName,
issuer: resolvedIssuer,
verificationStatus: .pending
)
return EnrollmentSession(
type: .totp,
session: session,
totpInfo: totpInfo,
status: .initiated,
_totpSecret: totpSecret
)
}
}
func sendSmsVerificationForEnrollment(session: EnrollmentSession,
phoneNumber: String) async throws -> String {
// Validate session
guard session.type == .sms else {
throw AuthServiceError.multiFactorAuth("Session is not configured for SMS enrollment")
}
guard session.canProceed else {
if session.isExpired {
throw AuthServiceError.multiFactorAuth("Enrollment session has expired")
} else {
throw AuthServiceError
.multiFactorAuth("Session is not in a valid state for SMS verification")
}
}
// Validate phone number format
guard !phoneNumber.isEmpty else {
throw AuthServiceError.multiFactorAuth("Phone number cannot be empty for SMS enrollment")
}
// Send SMS verification using Firebase Auth PhoneAuthProvider
let verificationID =
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<
String,
Error
>) in
PhoneAuthProvider.provider().verifyPhoneNumber(
phoneNumber,
uiDelegate: nil,
multiFactorSession: session.session
) { verificationID, error in
if let error = error {
continuation.resume(throwing: error)
} else if let verificationID = verificationID {
continuation.resume(returning: verificationID)
} else {
continuation
.resume(throwing: AuthServiceError
.multiFactorAuth("Failed to send SMS verification code to verify phone number"))
}
}
}
return verificationID
}
func resolveSignIn(code: String, hintIndex: Int, verificationId: String? = nil) async throws {
guard let resolver = currentMFAResolver else {
throw AuthServiceError.multiFactorAuth("No MFA resolver available")
}
guard hintIndex < resolver.hints.count else {
throw AuthServiceError.multiFactorAuth("Invalid hint index")
}
let hint = resolver.hints[hintIndex]
let assertion: MultiFactorAssertion
// Create the appropriate assertion based on the hint type
if hint.factorID == PhoneMultiFactorID {
guard let verificationId = verificationId else {
throw AuthServiceError.multiFactorAuth("Verification ID is required for SMS MFA")
}
let credential = PhoneAuthProvider.provider().credential(
withVerificationID: verificationId,
verificationCode: code
)
assertion = PhoneMultiFactorGenerator.assertion(with: credential)
} else if hint.factorID == TOTPMultiFactorID {
assertion = TOTPMultiFactorGenerator.assertionForSignIn(
withEnrollmentID: hint.uid,
oneTimePassword: code
)
} else {
throw AuthServiceError.multiFactorAuth("Unsupported MFA hint type")
}
do {
let result = try await resolver.resolveSignIn(with: assertion)
updateAuthenticationState()
// Clear MFA resolution state
currentMFAResolver = nil
} catch {
throw AuthServiceError
.multiFactorAuth("Failed to resolve MFA challenge: \(error.localizedDescription)")
}
}
func completeEnrollment(session: EnrollmentSession, verificationId: String?,
verificationCode: String, displayName: String) async throws {
// Validate session state
guard session.canProceed else {
if session.isExpired {
throw AuthServiceError
.multiFactorAuth("Enrollment session has expired, cannot complete enrollment")
} else {
throw AuthServiceError
.multiFactorAuth("Enrollment session is not in a valid state for completion")
}
}
// Validate verification code
guard !verificationCode.isEmpty else {
throw AuthServiceError.multiFactorAuth("Verification code cannot be empty")
}
guard let user = auth.currentUser else {
throw AuthServiceError.noCurrentUser
}
let multiFactorUser = user.multiFactor
// Create the appropriate assertion based on factor type
let assertion: MultiFactorAssertion
switch session.type {
case .sms:
// For SMS, we need the verification ID
guard let verificationId = verificationId else {
throw AuthServiceError
.multiFactorAuth("Verification ID is required for SMS enrollment")
}
// Create phone credential and assertion
let credential = PhoneAuthProvider.provider().credential(
withVerificationID: verificationId,
verificationCode: verificationCode
)
assertion = PhoneMultiFactorGenerator.assertion(with: credential)
case .totp:
// For TOTP, we need the secret from the session
guard let totpInfo = session.totpInfo else {
throw AuthServiceError
.multiFactorAuth("TOTP info is missing from enrollment session")
}
// Use the stored TOTP secret from the enrollment session
guard let secret = session._totpSecret else {
throw AuthServiceError
.multiFactorAuth("TOTP secret is missing from enrollment session")
}
// The concrete type is FirebaseAuth.TOTPSecret (kept as AnyObject to avoid exposing it)
guard let totpSecret = secret as? TOTPSecret else {
throw AuthServiceError
.multiFactorAuth("Invalid TOTP secret type in enrollment session")
}
assertion = TOTPMultiFactorGenerator.assertionForEnrollment(
with: totpSecret,
oneTimePassword: verificationCode
)
}
// Complete the enrollment
do {
try await user.multiFactor.enroll(with: assertion, displayName: displayName)
currentUser = auth.currentUser
} catch {
try await handleErrorWithReauthCheck(error: error)
throw error // If we reach here, it wasn't a reauth error, so rethrow
}
}
func unenrollMFA(_ factorUid: String) async throws -> [MultiFactorInfo] {
guard let user = auth.currentUser else {
throw AuthServiceError.noCurrentUser
}
let multiFactorUser = user.multiFactor
do {
try await multiFactorUser.unenroll(withFactorUID: factorUid)
// This is the only we to get the actual latest enrolledFactors
currentUser = Auth.auth().currentUser
let freshFactors = currentUser?.multiFactor.enrolledFactors ?? []
return freshFactors
} catch {
try await handleErrorWithReauthCheck(error: error)
throw error // If we reach here, it wasn't a reauth error, so rethrow
}
}
func resolveSmsChallenge(hintIndex: Int) async throws -> String {
guard let resolver = currentMFAResolver else {
throw AuthServiceError.multiFactorAuth("No MFA resolver available")
}
guard hintIndex < resolver.hints.count else {
throw AuthServiceError.multiFactorAuth("Invalid hint index")
}
let hint = resolver.hints[hintIndex]
guard hint.factorID == PhoneMultiFactorID else {
throw AuthServiceError.multiFactorAuth("Selected hint is not a phone hint")
}
let phoneHint = hint as! PhoneMultiFactorInfo
return try await withCheckedThrowingContinuation { continuation in
PhoneAuthProvider.provider().verifyPhoneNumber(
with: phoneHint,
uiDelegate: nil,
multiFactorSession: resolver.session
) { verificationId, error in
if let error = error {
continuation
.resume(throwing: AuthServiceError.multiFactorAuth(error.localizedDescription))
} else if let verificationId = verificationId {
continuation.resume(returning: verificationId)
} else {
continuation
.resume(throwing: AuthServiceError.multiFactorAuth("Unknown error occurred"))
}
}
}
}
}
// MARK: - Private Helper Methods
private extension AuthService {
internal func updateAuthenticationState() {
authenticationState =
(currentUser == nil || currentUser?.isAnonymous == true)
? .unauthenticated
: .authenticated
if authenticationState == .authenticated {
legacySignInRecovery = nil
}
}
private var shouldHandleAnonymousUpgrade: Bool {
currentUser?.isAnonymous == true && configuration.shouldAutoUpgradeAnonymousUsers
}
private func handleAutoUpgradeAnonymousUser(credentials: AuthCredential) async throws
-> SignInOutcome {
if currentUser == nil {
throw AuthServiceError.noCurrentUser
}
do {
let result = try await currentUser?.link(with: credentials)
updateAuthenticationState()
return .signedIn(result)
} catch {
throw error
}
}
// MARK: - Action Code Settings Helper Methods
private func safeActionCodeSettings() throws -> ActionCodeSettings {
// email sign-in requires action code settings
guard let actionCodeSettings = configuration
.emailLinkSignInActionCodeSettings else {
throw AuthServiceError
.notConfiguredActionCodeSettings(
"ActionCodeSettings has not been configured for `AuthConfiguration.emailLinkSignInActionCodeSettings`"
)
}
return actionCodeSettings
}
private func updateActionCodeSettings() throws -> ActionCodeSettings {
let actionCodeSettings = try safeActionCodeSettings()
guard var urlComponents = URLComponents(string: actionCodeSettings.url!.absoluteString) else {
throw AuthServiceError
.notConfiguredActionCodeSettings(
"ActionCodeSettings.url has not been configured for `AuthConfiguration.emailLinkSignInActionCodeSettings`"
)
}
var queryItems: [URLQueryItem] = []
if shouldHandleAnonymousUpgrade {
if let currentUser = currentUser {
let anonymousUID = currentUser.uid
let auidItem = URLQueryItem(name: "ui_auid", value: anonymousUID)
queryItems.append(auidItem)
}
}
urlComponents.queryItems = queryItems
if let finalURL = urlComponents.url {
actionCodeSettings.url = finalURL
}
return actionCodeSettings
}
// MARK: - Reauth Error Helper Methods
/// Checks if an error requires reauthentication and handles it appropriately
/// - Parameter error: The error to check
/// - Throws: Only if it's a reauthentication error (via requireReauthentication())
private func handleErrorWithReauthCheck(error: Error) async throws {
if let nsError = error as NSError?,
nsError.domain == AuthErrorDomain,
nsError.code == AuthErrorCode.requiresRecentLogin.rawValue ||
nsError.code == AuthErrorCode.userTokenExpired.rawValue {
try await requireReauthentication()
}
// If not a reauth error, return normally so caller can handle it
}
/// Internal helper to create reauth context and throw appropriate error
/// - Throws: Appropriate `AuthServiceError` based on the provider type
private func requireReauthentication() async throws -> Never {
let providerId = try await getCurrentSignInProvider()
// Try to find display name from registered provider
let providerDisplayName: String