-
Notifications
You must be signed in to change notification settings - Fork 482
/
Copy pathAuthService.swift
359 lines (315 loc) · 9.76 KB
/
AuthService.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
@preconcurrency import FirebaseAuth
import SwiftUI
public protocol GoogleProviderProtocol {
func handleUrl(_ url: URL) -> Bool
@MainActor func signInWithGoogle(clientID: String) async throws -> AuthCredential
}
public protocol FacebookProviderProtocol {
@MainActor func signInWithFacebook(isLimitedLogin: Bool) async throws -> AuthCredential
}
public protocol PhoneAuthProviderProtocol {
@MainActor func verifyPhoneNumber(phoneNumber: String) async throws -> String
}
public enum AuthenticationState {
case unauthenticated
case authenticating
case authenticated
}
public enum AuthenticationFlow {
case login
case signUp
}
public enum AuthView {
case authPicker
case passwordRecovery
case emailLink
case updatePassword
}
@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()
}
}
}
@MainActor
@Observable
public final class AuthService {
public init(configuration: AuthConfiguration = AuthConfiguration(), auth: Auth = Auth.auth(),
googleProvider: GoogleProviderProtocol? = nil,
facebookProvider: FacebookProviderProtocol? = nil,
phoneAuthProvider: PhoneAuthProviderProtocol? = nil) {
self.auth = auth
self.configuration = configuration
self.googleProvider = googleProvider
self.facebookProvider = facebookProvider
self.phoneAuthProvider = phoneAuthProvider
string = StringUtils(bundle: configuration.customStringsBundle ?? Bundle.module)
listenerManager = AuthListenerManager(auth: auth, authEnvironment: self)
}
@ObservationIgnored @AppStorage("email-link") public var emailLink: String?
public let configuration: AuthConfiguration
public let auth: Auth
public var authView: AuthView = .authPicker
public let string: StringUtils
public var currentUser: User?
public var authenticationState: AuthenticationState = .unauthenticated
public var authenticationFlow: AuthenticationFlow = .login
public var errorMessage = ""
public let passwordPrompt: PasswordPromptCoordinator = .init()
private var listenerManager: AuthListenerManager?
private let googleProvider: GoogleProviderProtocol?
private let facebookProvider: FacebookProviderProtocol?
private let phoneAuthProvider: PhoneAuthProviderProtocol?
private var safeGoogleProvider: GoogleProviderProtocol {
get throws {
guard let provider = googleProvider else {
throw AuthServiceError
.notConfiguredProvider("`GoogleProviderSwift` has not been configured")
}
return provider
}
}
private var safeFacebookProvider: FacebookProviderProtocol {
get throws {
guard let provider = facebookProvider else {
throw AuthServiceError
.notConfiguredProvider("`FacebookProviderSwift` has not been configured")
}
return provider
}
}
private var safePhoneAuthProvider: PhoneAuthProviderProtocol {
get throws {
guard let provider = phoneAuthProvider else {
throw AuthServiceError
.notConfiguredProvider("`PhoneAuthProviderSwift` has not been configured")
}
return provider
}
}
private func safeActionCodeSettings() throws -> ActionCodeSettings {
// email sign-in requires action code settings
guard let actionCodeSettings = configuration
.emailLinkSignInActionCodeSettings else {
throw AuthServiceError
.notConfiguredActionCodeSettings
}
return actionCodeSettings
}
public func updateAuthenticationState() {
reset()
authenticationState =
(currentUser == nil || currentUser?.isAnonymous == true)
? .unauthenticated
: .authenticated
}
func reset() {
errorMessage = ""
}
public func signOut() async throws {
do {
try await auth.signOut()
updateAuthenticationState()
} catch {
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
public func linkAccounts(credentials credentials: AuthCredential) async throws {
authenticationState = .authenticating
do {
try await currentUser?.link(with: credentials)
updateAuthenticationState()
} catch {
authenticationState = .unauthenticated
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
public func signIn(credentials credentials: AuthCredential) async throws {
authenticationState = .authenticating
if currentUser?.isAnonymous == true, configuration.shouldAutoUpgradeAnonymousUsers {
try await linkAccounts(credentials: credentials)
} else {
do {
try await auth.signIn(with: credentials)
updateAuthenticationState()
} catch {
authenticationState = .unauthenticated
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
}
func sendEmailVerification() async throws {
if currentUser != nil {
do {
// TODO: - can use set user action code settings?
try await currentUser!.sendEmailVerification()
} catch {
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
}
}
// MARK: - User API
public extension AuthService {
func deleteUser() async throws {
do {
if let user = auth.currentUser {
let operation = EmailPasswordDeleteUserOperation(passwordPrompt: passwordPrompt)
try await operation(on: user)
}
} catch {
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
func updatePassword(to password: String) async throws {
do {
if let user = auth.currentUser {
let operation = EmailPasswordUpdatePasswordOperation(
passwordPrompt: passwordPrompt,
newPassword: password
)
try await operation(on: user)
}
} catch {
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
}
// MARK: - Email/Password Sign In
public extension AuthService {
func signIn(withEmail email: String, password: String) async throws {
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
try await signIn(credentials: credential)
}
func createUser(withEmail email: String, password: String) async throws {
authenticationState = .authenticating
do {
try await auth.createUser(withEmail: email, password: password)
updateAuthenticationState()
} catch {
authenticationState = .unauthenticated
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
func sendPasswordRecoveryEmail(to email: String) async throws {
do {
try await auth.sendPasswordReset(withEmail: email)
} catch {
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
}
// MARK: - Email Link Sign In
public extension AuthService {
func sendEmailSignInLink(to email: String) async throws {
do {
let actionCodeSettings = try safeActionCodeSettings()
try await auth.sendSignInLink(
toEmail: email,
actionCodeSettings: actionCodeSettings
)
} catch {
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
func handleSignInLink(url url: URL) async throws {
do {
guard let email = emailLink else {
throw AuthServiceError.invalidEmailLink
}
let link = url.absoluteString
if auth.isSignIn(withEmailLink: link) {
let result = try await auth.signIn(withEmail: email, link: link)
updateAuthenticationState()
emailLink = nil
}
} catch {
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
}
// MARK: - Google Sign In
public extension AuthService {
func signInWithGoogle() async throws {
guard let clientID = auth.app?.options.clientID else {
throw AuthServiceError
.clientIdNotFound(
"OAuth client ID not found. Please make sure Google Sign-In is enabled in the Firebase console. You may have to download a new GoogleService-Info.plist file after enabling Google Sign-In."
)
}
let credential = try await safeGoogleProvider.signInWithGoogle(clientID: clientID)
try await signIn(credentials: credential)
}
}
// MARK: - Facebook Sign In
public extension AuthService {
func signInWithFacebook(limitedLogin: Bool = true) async throws {
let credential = try await safeFacebookProvider
.signInWithFacebook(isLimitedLogin: limitedLogin)
try await signIn(credentials: credential)
}
}
// MARK: - Phone Auth Sign In
public extension AuthService {
func verifyPhoneNumber(phoneNumber: String) async throws -> String {
do {
return try await safePhoneAuthProvider.verifyPhoneNumber(phoneNumber: phoneNumber)
} catch {
errorMessage = string.localizedErrorMessage(
for: error
)
throw error
}
}
func signInWithPhoneNumber(verificationID: String, verificationCode: String) async throws {
let credential = PhoneAuthProvider.provider()
.credential(withVerificationID: verificationID, verificationCode: verificationCode)
try await signIn(credentials: credential)
}
}