-
Notifications
You must be signed in to change notification settings - Fork 490
Expand file tree
/
Copy pathAuthService.swift
More file actions
1054 lines (910 loc) · 34.4 KB
/
AuthService.swift
File metadata and controls
1054 lines (910 loc) · 34.4 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
public protocol AuthProviderSwift {
@MainActor func createAuthCredential() async throws -> AuthCredential
}
public protocol AuthProviderUI {
var id: String { get }
@MainActor func authButton() -> AnyView
var provider: AuthProviderSwift { get }
}
public protocol PhoneAuthProviderSwift: AuthProviderSwift {
@MainActor func verifyPhoneNumber(phoneNumber: String) async throws -> String
@MainActor func createAuthCredential(verificationId: String,
verificationCode: String) async throws -> AuthCredential
}
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
case enterPhoneNumber
case enterVerificationCode(verificationID: String, fullPhoneNumber: String)
}
public enum SignInOutcome: @unchecked Sendable {
case mfaRequired(MFARequired)
case signedIn(AuthDataResult?)
}
@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?
public let configuration: AuthConfiguration
public let auth: Auth
public var isPresented: Bool = false
public private(set) var navigator = Navigator()
public var authView: AuthView? {
navigator.routes.last
}
var authViewRoutes: [AuthView] {
navigator.routes
}
public let string: StringUtils
public var currentUser: User?
public var authenticationState: AuthenticationState = .unauthenticated
public var authenticationFlow: AuthenticationFlow = .signIn
private var _currentError: AlertError?
/// A binding that allows SwiftUI views to observe and clear errors
public var currentError: Binding<AlertError?> {
Binding(
get: { self._currentError },
set: { newValue in
if newValue == nil {
self._currentError = nil
}
}
)
}
public let passwordPrompt: PasswordPromptCoordinator = .init()
public var currentMFARequired: MFARequired?
private var currentMFAResolver: MultiFactorResolver?
/// Current account conflict context - observe this to handle conflicts and update backend
public private(set) var currentAccountConflict: AccountConflictContext?
// MARK: - Provider APIs
private var listenerManager: AuthListenerManager?
var emailSignInEnabled = false
private var providers: [AuthProviderUI] = []
public var currentPhoneProvider: PhoneAuthProviderSwift? {
providers.compactMap { $0.provider as? PhoneAuthProviderSwift }.first
}
public func registerProvider(providerWithButton: AuthProviderUI) {
providers.append(providerWithButton)
}
public func renderButtons(spacing: CGFloat = 16) -> AnyView {
AnyView(
VStack(spacing: spacing) {
AuthProviderButton(
label: string.signInWithEmailLinkViewTitle,
style: .email,
accessibilityId: "sign-in-with-email-link-button"
) {
self.navigator.push(.emailLink)
}
ForEach(providers, id: \.id) { provider in
provider.authButton()
}
}
)
}
public func signIn(_ provider: AuthProviderSwift) async throws -> SignInOutcome {
do {
let credential = try await provider.createAuthCredential()
let result = try await signIn(credentials: credential)
return result
} catch {
// Always pass the underlying error - view decides what to show
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
// MARK: - End Provider APIs
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
}
public func updateAuthenticationState() {
reset()
authenticationState =
(currentUser == nil || currentUser?.isAnonymous == true)
? .unauthenticated
: .authenticated
}
func reset() {
_currentError = nil
currentAccountConflict = nil
}
func updateError(title: String = "Error", message: String, underlyingError: Error? = nil) {
_currentError = AlertError(title: title, message: message, underlyingError: underlyingError)
}
public var shouldHandleAnonymousUpgrade: Bool {
currentUser?.isAnonymous == true && configuration.shouldAutoUpgradeAnonymousUsers
}
public func signOut() async throws {
do {
try await auth.signOut()
// Cannot wait for auth listener to change, feedback needs to be immediate
currentUser = nil
updateAuthenticationState()
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
public func linkAccounts(credentials credentials: AuthCredential) async throws {
authenticationState = .authenticating
do {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
try await withReauthenticationIfNeeded(on: user) {
try await user.link(with: credentials)
}
updateAuthenticationState()
} catch {
// 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
authenticationState = .unauthenticated
try handleErrorWithConflictCheck(error: error, credential: credentials)
}
}
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
}
}
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 {
do {
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()
}
}
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
}
// MARK: - User API
public extension AuthService {
func deleteUser() async throws {
do {
guard let user = auth.currentUser else {
throw AuthServiceError.noCurrentUser
}
try await withReauthenticationIfNeeded(on: user) {
try await user.delete()
}
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
func updatePassword(to password: String) async throws {
do {
guard let user = auth.currentUser else {
throw AuthServiceError.noCurrentUser
}
try await withReauthenticationIfNeeded(on: user) {
try await user.updatePassword(to: password)
}
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
}
// MARK: - Email/Password Sign In
public extension AuthService {
func withEmailSignIn() -> AuthService {
emailSignInEnabled = true
return self
}
func signIn(email: String, password: String) async throws -> SignInOutcome {
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
return try await signIn(credentials: credential)
}
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 {
do {
try await auth.sendPasswordReset(withEmail: email)
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
}
// MARK: - Email Link Sign In
public extension AuthService {
func sendEmailSignInLink(email: String) async throws {
do {
let actionCodeSettings = try updateActionCodeSettings()
try await auth.sendSignInLink(
toEmail: email,
actionCodeSettings: actionCodeSettings
)
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
func handleSignInLink(url url: URL) async throws {
do {
guard let email = emailLink else {
throw AuthServiceError
.invalidEmailLink("email address is missing from app storage. Is this the same device?")
}
let link = url.absoluteString
guard let continueUrl = CommonUtils.getQueryParamValue(from: link, paramName: "continueUrl")
else {
throw AuthServiceError
.invalidEmailLink("`continueUrl` parameter is missing from the email link URL")
}
if auth.isSignIn(withEmailLink: link) {
let anonymousUserID = CommonUtils.getQueryParamValue(
from: continueUrl,
paramName: "ui_auid"
)
if shouldHandleAnonymousUpgrade, anonymousUserID == currentUser?.uid {
let credential = EmailAuthProvider.credential(withEmail: email, link: link)
try await handleAutoUpgradeAnonymousUser(credentials: credential)
} else {
let result = try await auth.signIn(withEmail: email, link: link)
}
updateAuthenticationState()
emailLink = nil
}
} catch {
// Reconstruct credential for conflict handling
let link = url.absoluteString
guard let email = emailLink else {
throw AuthServiceError
.invalidEmailLink("email address is missing from app storage. Is this the same device?")
}
let credential = EmailAuthProvider.credential(withEmail: email, link: link)
// 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)
}
}
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: - 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: - User Profile Management
public extension AuthService {
func updateUserPhotoURL(url: URL) async throws {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
do {
let changeRequest = user.createProfileChangeRequest()
changeRequest.photoURL = url
try await changeRequest.commitChanges()
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
func updateUserDisplayName(name: String) async throws {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
do {
let changeRequest = user.createProfileChangeRequest()
changeRequest.displayName = name
try await changeRequest.commitChanges()
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
}
// MARK: - MFA Methods
public extension AuthService {
func startMfaEnrollment(type: SecondFactorType, accountName: String? = nil,
issuer: String? = nil) async throws -> EnrollmentSession {
do {
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
)
}
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
func sendSmsVerificationForEnrollment(session: EnrollmentSession,
phoneNumber: String) async throws -> String {
do {
// 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
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
func completeEnrollment(session: EnrollmentSession, verificationId: String?,
verificationCode: String, displayName: String) async throws {
do {
// 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
try await withReauthenticationIfNeeded(on: user) {
try await user.multiFactor.enroll(with: assertion, displayName: displayName)
}
currentUser = auth.currentUser
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
/// Gets the provider ID that was used for the current sign-in session
private func getCurrentSignInProvider() async throws -> String {
guard let user = currentUser else {
throw AuthServiceError.noCurrentUser
}
// Get the ID token result which contains the signInProvider claim
let tokenResult = try await user.getIDTokenResult(forcingRefresh: false)
// The signInProvider property tells us which provider was used for this session
let signInProvider = tokenResult.signInProvider
// If signInProvider is not empty, use it
if !signInProvider.isEmpty {
return signInProvider
}
// Fallback: if signInProvider is empty, try to infer from providerData
// Prefer non-password providers as they're more specific
let providerId = user.providerData.first(where: { $0.providerID != "password" })?.providerID
?? user.providerData.first?.providerID
guard let providerId = providerId else {
throw AuthServiceError.reauthenticationRequired(
"Unable to determine sign-in provider for reauthentication"
)
}
return providerId
}
func reauthenticateCurrentUser(on user: User) async throws {
// Get the provider from the token instead of stored credential
let providerId = try await getCurrentSignInProvider()
if providerId == EmailAuthProviderID {
guard let email = user.email else {
throw AuthServiceError.invalidCredentials("User does not have an email address")
}
let password = try await passwordPrompt.confirmPassword()
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
_ = try await user.reauthenticate(with: credential)
} else if let matchingProvider = providers.first(where: { $0.id == providerId }) {
let credential = try await matchingProvider.provider.createAuthCredential()
_ = try await user.reauthenticate(with: credential)
} else {
throw AuthServiceError.providerNotFound("No provider found for \(providerId)")
}
}
private func withReauthenticationIfNeeded(on user: User,
operation: () async throws -> Void) async throws {
do {
try await operation()
} catch let error as NSError {
if error.domain == AuthErrorDomain,
error.code == AuthErrorCode.requiresRecentLogin.rawValue || error.code == AuthErrorCode
.userTokenExpired.rawValue {
try await reauthenticateCurrentUser(on: user)
try await operation()
} else {
throw error
}
}
}
func unenrollMFA(_ factorUid: String) async throws -> [MultiFactorInfo] {
do {
guard let user = auth.currentUser else {
throw AuthServiceError.noCurrentUser
}
let multiFactorUser = user.multiFactor
try await withReauthenticationIfNeeded(on: user) {
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 {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
// MARK: - Account Conflict Helper Methods
private func determineConflictType(from error: NSError) -> AccountConflictType? {
switch error.code {
case AuthErrorCode.accountExistsWithDifferentCredential.rawValue:
return shouldHandleAnonymousUpgrade ? .anonymousUpgradeConflict :
.accountExistsWithDifferentCredential
case AuthErrorCode.credentialAlreadyInUse.rawValue:
return shouldHandleAnonymousUpgrade ? .anonymousUpgradeConflict : .credentialAlreadyInUse
case AuthErrorCode.emailAlreadyInUse.rawValue:
return shouldHandleAnonymousUpgrade ? .anonymousUpgradeConflict : .emailAlreadyInUse
default:
return nil
}
}
private func createConflictContext(from error: NSError,
conflictType: AccountConflictType,
credential: AuthCredential) -> AccountConflictContext {
let updatedCredential = error
.userInfo[AuthErrorUserInfoUpdatedCredentialKey] as? AuthCredential ?? credential
let email = error.userInfo[AuthErrorUserInfoEmailKey] as? String
return AccountConflictContext(
conflictType: conflictType,
credential: updatedCredential,
underlyingError: error,
message: string.localizedErrorMessage(for: error),
email: email
)
}
/// Handles account conflict errors by creating context, storing it, and throwing structured error
/// - Parameters:
/// - error: The error to check and handle
/// - credential: The credential that caused the conflict
/// - Throws: AuthServiceError.accountConflict if it's a conflict error, otherwise rethrows the
/// original error
private func handleErrorWithConflictCheck(error: Error,
credential: AuthCredential) throws -> Never {
// Check for account conflict errors
if let error = error as NSError?,
let conflictType = determineConflictType(from: error) {
let context = createConflictContext(
from: error,
conflictType: conflictType,
credential: credential
)
// Store it for consumers to observe
currentAccountConflict = context
// Only set error alert if we're NOT auto-handling it
if conflictType != .anonymousUpgradeConflict {
updateError(message: context.message, underlyingError: error)
}
// Throw the specific error with context
throw AuthServiceError.accountConflict(context)
} else {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}
// MARK: - MFA Helper Methods
private func extractMFAHints(from resolver: MultiFactorResolver) -> [MFAHint] {
return resolver.hints.map { hint -> MFAHint in
if hint.factorID == PhoneMultiFactorID {
let phoneHint = hint as! PhoneMultiFactorInfo
return .phone(
displayName: phoneHint.displayName,
uid: phoneHint.uid,
phoneNumber: phoneHint.phoneNumber
)
} else if hint.factorID == TOTPMultiFactorID {
return .totp(
displayName: hint.displayName,
uid: hint.uid
)
} else {
// Fallback for unknown hint types
return .totp(displayName: hint.displayName, uid: hint.uid)
}
}
}
private func handleMFARequiredError(resolver: MultiFactorResolver) -> SignInOutcome {
let hints = extractMFAHints(from: resolver)
currentMFARequired = MFARequired(hints: hints)
currentMFAResolver = resolver
navigator.push(.mfaResolution)
return .mfaRequired(MFARequired(hints: hints))
}
func resolveSmsChallenge(hintIndex: Int) async throws -> String {
do {
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"))
}
}
}
} catch {
updateError(message: string.localizedErrorMessage(for: error), underlyingError: error)
throw error
}
}