-
Notifications
You must be signed in to change notification settings - Fork 481
/
Copy pathAuthService.swift
205 lines (180 loc) · 5.65 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
@preconcurrency import FirebaseAuth
import SwiftUI
public protocol GoogleProviderProtocol {
func handleUrl(_ url: URL) -> Bool
@MainActor func signInWithGoogle(clientID: String) async throws -> AuthCredential
}
public protocol FacebookProviderProtocol {}
public enum AuthenticationProvider {
case email
case google
}
public enum AuthenticationOperationType: String {
case signIn
case signUp
case deleteAccount
}
public enum AuthenticationState {
case unauthenticated
case authenticating
case authenticated
}
public enum AuthenticationFlow {
case login
case signUp
}
@MainActor
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 let configuration: AuthConfiguration
public let auth: Auth
private var listenerManager: AuthListenerManager?
private let googleProvider: GoogleProviderProtocol?
private let facebookProvider: FacebookProviderProtocol?
public let string: StringUtils
public init(configuration: AuthConfiguration = AuthConfiguration(), auth: Auth = Auth.auth(),
googleProvider: GoogleProviderProtocol? = nil,
facebookProvider: FacebookProviderProtocol? = nil) {
self.auth = auth
self.configuration = configuration
self.googleProvider = googleProvider
self.facebookProvider = facebookProvider
string = StringUtils(bundle: configuration.customStringsBundle ?? Bundle.module)
listenerManager = AuthListenerManager(auth: auth, authEnvironment: self)
}
public var currentUser: User?
public var authenticationState: AuthenticationState = .unauthenticated
public var authenticationFlow: AuthenticationFlow = .login
private var safeGoogleProvider: GoogleProviderProtocol {
get throws {
guard let provider = googleProvider else {
throw NSError(
domain: "AuthEnvironmentErrorDomain",
code: 1,
userInfo: [
NSLocalizedDescriptionKey: "`GoogleProviderSwift` has not been configured",
]
)
}
return provider
}
}
private var safeFacebookProvider: FacebookProviderProtocol {
get throws {
guard let provider = facebookProvider else {
throw NSError(
domain: "AuthEnvironmentErrorDomain",
code: 1,
userInfo: [
NSLocalizedDescriptionKey: "`FacebookProviderSwift` has not been configured",
]
)
}
return provider
}
}
func updateAuthenticationState() {
authenticationState =
(currentUser == nil || currentUser?.isAnonymous == true)
? .unauthenticated
: .authenticated
}
public func signOut() async throws {
try await auth.signOut()
updateAuthenticationState()
}
public func signInWithGoogle() async throws {
authenticationState = .authenticating
do {
guard let clientID = auth.app?.options.clientID else { throw NSError(
domain: "AuthServiceErrorDomain",
code: 2,
userInfo: [
NSLocalizedDescriptionKey: "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(with: credential)
updateAuthenticationState()
} catch {
authenticationState = .unauthenticated
throw error
}
}
func signIn(with credentials: AuthCredential) async throws {
authenticationState = .authenticating
do {
try await auth.signIn(with: credentials)
updateAuthenticationState()
} catch {
authenticationState = .unauthenticated
throw error
}
}
func sendEmailVerification() async throws {
if currentUser != nil {
do {
// TODO: - can use set user action code settings?
try await currentUser!.sendEmailVerification()
} catch {
throw error
}
}
}
func signIn(withEmail email: String, password: String) async throws {
let credential = EmailAuthProvider.credential(withEmail: email, password: password)
try await auth.signIn(with: 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
throw error
}
}
func sendPasswordRecoveryEmail(to email: String) async throws {
do {
try await auth.sendPasswordReset(withEmail: email)
} catch {
throw error
}
}
func sendEmailSignInLink(to email: String) async throws {
do {
// TODO: - how does user set action code settings? Needs configuring
let actionCodeSettings = ActionCodeSettings()
actionCodeSettings.handleCodeInApp = true
try await auth.sendSignInLink(
toEmail: email,
actionCodeSettings: actionCodeSettings
)
} catch {
throw error
}
}
}