- Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathUserViewController.swift
326 lines (266 loc) · 9.9 KB
/
UserViewController.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
// Copyright 2020 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 UIKit
import FirebaseAuth
import AuthenticationServices
import CryptoKit
classUserViewController:UIViewController,DataSourceProviderDelegate{
vardataSourceProvider:DataSourceProvider<User>!
varuserImage=UIImageView(systemImageName:"person.circle.fill", tintColor:.secondaryLabel)
vartableView:UITableView{ view as!UITableView}
privatevar_user:User?
varuser:User?{
get{ _user ??Auth.auth().currentUser }
set{ _user = newValue }
}
/// Init allows for injecting a `User` instance during UI Testing
/// - Parameter user: A Firebase User instance
init(_ user:User?=nil){
super.init(nibName:nil, bundle:nil)
self.user = user
}
requiredinit?(coder:NSCoder){
fatalError("init(coder:) has not been implemented")
}
// MARK: - UIViewController Life Cycle
overridefunc loadView(){
view =UITableView(frame:.zero, style:.insetGrouped)
}
overridefunc viewDidLoad(){
super.viewDidLoad()
configureNavigationBar()
}
overridefunc viewWillAppear(_ animated:Bool){
super.viewWillAppear(animated)
configureDataSourceProvider()
updateUserImage()
}
// MARK: - DataSourceProviderDelegate
func tableViewDidScroll(_ tableView:UITableView){
adjustUserImageAlpha(tableView.contentOffset.y)
}
func didSelectRowAt(_ indexPath:IndexPath, on tableView:UITableView){
letitem= dataSourceProvider.item(at: indexPath)
letactionName= item.isEditable ? item.detailTitle! : item.title!
guardlet action =UserAction(rawValue: actionName)else{
// The row tapped has no affiliated action.
return
}
switch action {
case.signOut:
signCurrentUserOut()
case.link:
linkUserToOtherAuthProviders()
case.requestVerifyEmail:
requestVerifyEmail()
case.tokenRefresh:
refreshCurrentUserIDToken()
case.delete:
deleteCurrentUser()
case.updateEmail:
presentEditUserInfoController(for: item, to: updateUserEmail)
case.updateDisplayName:
presentEditUserInfoController(for: item, to: updateUserDisplayName)
case.updatePhotoURL:
presentEditUserInfoController(for: item, to: updatePhotoURL)
case.refreshUserInfo:
refreshUserInfo()
}
}
// MARK: - Firebase 🔥
publicfunc signCurrentUserOut(){
try?Auth.auth().signOut()
updateUI()
}
publicfunc linkUserToOtherAuthProviders(){
guardlet user = user else{return}
letaccountLinkingController=AccountLinkingViewController(for: user)
letnavController=UINavigationController(rootViewController: accountLinkingController)
navigationController?.present(navController, animated:true, completion:nil)
}
publicfunc requestVerifyEmail(){
user?.sendEmailVerification{ error in
guard error ==nilelse{returnself.displayError(error)}
print("Verification email sent!")
}
}
publicfunc refreshCurrentUserIDToken(){
letforceRefresh=true
user?.getIDTokenForcingRefresh(forceRefresh){ token, error in
guard error ==nilelse{returnself.displayError(error)}
iflet token = token {
print("New token: \(token)")
}
}
}
publicfunc refreshUserInfo(){
user?.reload{ error in
iflet error = error {
print(error)
}
self.updateUI()
}
}
publicfunc updateUserDisplayName(to newDisplayName:String){
letchangeRequest= user?.createProfileChangeRequest()
changeRequest?.displayName = newDisplayName
changeRequest?.commitChanges{ error in
guard error ==nilelse{returnself.displayError(error)}
self.updateUI()
}
}
publicfunc updateUserEmail(to newEmail:String){
user?.updateEmail(to: newEmail, completion:{ error in
guard error ==nilelse{returnself.displayError(error)}
self.updateUI()
})
}
publicfunc updatePhotoURL(to newPhotoURL:String){
guardlet newPhotoURL =URL(string: newPhotoURL)else{
print("Could not create new photo URL!")
return
}
letchangeRequest= user?.createProfileChangeRequest()
changeRequest?.photoURL = newPhotoURL
changeRequest?.commitChanges{ error in
guard error ==nilelse{returnself.displayError(error)}
self.updateUI()
}
}
// MARK: - Sign in with Apple Token Revocation Flow
// For Sign in with Apple
privatevarcurrentNonce:String?
// [START token_revocation_deleteuser]
privatefunc deleteCurrentUser(){
do{
letnonce=tryCryptoUtils.randomNonceString()
currentNonce = nonce
letappleIDProvider=ASAuthorizationAppleIDProvider()
letrequest= appleIDProvider.createRequest()
request.requestedScopes =[.fullName,.email]
request.nonce =CryptoUtils.sha256(nonce)
letauthorizationController=ASAuthorizationController(authorizationRequests:[request])
authorizationController.delegate =self
authorizationController.presentationContextProvider =self
authorizationController.performRequests()
}catch{
// In the unlikely case that nonce generation fails, show error view.
displayError(error)
}
}
// [END token_revocation_deleteuser]
// MARK: - Private Helpers
privatefunc configureNavigationBar(){
navigationItem.title ="User"
guardlet navigationBar = navigationController?.navigationBar else{return}
navigationBar.prefersLargeTitles =true
navigationBar.titleTextAttributes =[.foregroundColor:UIColor.systemOrange]
navigationBar.largeTitleTextAttributes =[.foregroundColor:UIColor.systemOrange]
navigationBar.addProfilePic(userImage)
}
privatefunc updateUserImage(){
guardlet photoURL = user?.photoURL else{
letdefaultImage=UIImage(systemName:"person.circle.fill")
userImage.image = defaultImage?.withTintColor(.secondaryLabel, renderingMode:.alwaysOriginal)
return
}
userImage.setImage(from: photoURL)
}
privatefunc configureDataSourceProvider(){
dataSourceProvider =DataSourceProvider(
dataSource: user?.sections,
emptyStateView:SignedOutView(),
tableView: tableView
)
dataSourceProvider.delegate =self
}
privatefunc updateUI(){
configureDataSourceProvider()
animateUpdates(for: tableView)
updateUserImage()
}
privatefunc animateUpdates(for tableView:UITableView){
UIView.transition(with: tableView, duration:0.2,
options:.transitionCrossDissolve,
animations:{ tableView.reloadData()})
}
privatefunc presentEditUserInfoController(for item:Itemable,
to saveHandler:@escaping(String)->Void){
leteditController=UIAlertController(
title:"Update \(item.detailTitle!)",
message:nil,
preferredStyle:.alert
)
editController.addTextField{ $0.placeholder ="New \(item.detailTitle!)"}
letsaveHandler:(UIAlertAction)->Void={ _ in
lettext= editController.textFields!.first!.text!
saveHandler(text)
}
editController.addAction(UIAlertAction(title:"Save", style:.default, handler: saveHandler))
editController.addAction(UIAlertAction(title:"Cancel", style:.cancel))
present(editController, animated:true, completion:nil)
}
privatevaroriginalOffset:CGFloat?
privatefunc adjustUserImageAlpha(_ offset:CGFloat){
originalOffset = originalOffset ?? offset
letverticalOffset= offset - originalOffset!
userImage.alpha =1-(verticalOffset *0.05)
}
}
// MARK: - Implementing Sign in with Apple for the Token Revocation Flow
extensionUserViewController:ASAuthorizationControllerDelegate,
ASAuthorizationControllerPresentationContextProviding{
// MARK: ASAuthorizationControllerDelegate
// [START token_revocation]
func authorizationController(controller:ASAuthorizationController,
didCompleteWithAuthorization authorization:ASAuthorization){
guardlet appleIDCredential = authorization.credential as?ASAuthorizationAppleIDCredential
else{
print("Unable to retrieve AppleIDCredential")
return
}
guardlet _ = currentNonce else{
fatalError("Invalid state: A login callback was received, but no login request was sent.")
}
guardlet appleAuthCode = appleIDCredential.authorizationCode else{
print("Unable to fetch authorization code")
return
}
guardlet authCodeString =String(data: appleAuthCode, encoding:.utf8)else{
print("Unable to serialize auth code string from data: \(appleAuthCode.debugDescription)")
return
}
Task{
do{
tryawaitAuth.auth().revokeToken(withAuthorizationCode: authCodeString)
tryawait user?.delete()
self.updateUI()
}catch{
self.displayError(error)
}
}
}
// [END token_revocation]
func authorizationController(controller:ASAuthorizationController,
didCompleteWithError error:Error){
// Ensure that you have:
// - enabled `Sign in with Apple` on the Firebase console
// - added the `Sign in with Apple` capability for this project
print("Sign in with Apple failed: \(error)")
}
// MARK: ASAuthorizationControllerPresentationContextProviding
func presentationAnchor(for controller:ASAuthorizationController)->ASPresentationAnchor{
return view.window!
}
}