UserViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. // Copyright 2020 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import AuthenticationServices
  15. import CryptoKit
  16. import FirebaseAuth
  17. import UIKit
  18. class UserViewController: UIViewController, DataSourceProviderDelegate {
  19. var dataSourceProvider: DataSourceProvider<User>!
  20. var userImage = UIImageView(systemImageName: "person.circle.fill", tintColor: .secondaryLabel)
  21. var tableView: UITableView { view as! UITableView }
  22. private var _user: User?
  23. var user: User? {
  24. get { _user ?? AppManager.shared.auth().currentUser }
  25. set { _user = newValue }
  26. }
  27. /// Init allows for injecting a `User` instance during UI Testing
  28. /// - Parameter user: A Firebase User instance
  29. init(_ user: User? = nil) {
  30. super.init(nibName: nil, bundle: nil)
  31. self.user = user
  32. }
  33. @available(*, unavailable)
  34. required init?(coder: NSCoder) {
  35. fatalError("init(coder:) has not been implemented")
  36. }
  37. // MARK: - UIViewController Life Cycle
  38. override func loadView() {
  39. view = UITableView(frame: .zero, style: .insetGrouped)
  40. }
  41. override func viewDidLoad() {
  42. super.viewDidLoad()
  43. configureNavigationBar()
  44. }
  45. override func viewWillAppear(_ animated: Bool) {
  46. super.viewWillAppear(animated)
  47. configureDataSourceProvider()
  48. updateUserImage()
  49. }
  50. // MARK: - DataSourceProviderDelegate
  51. func tableViewDidScroll(_ tableView: UITableView) {
  52. adjustUserImageAlpha(tableView.contentOffset.y)
  53. }
  54. func didSelectRowAt(_ indexPath: IndexPath, on tableView: UITableView) {
  55. let item = dataSourceProvider.item(at: indexPath)
  56. let actionName = item.isEditable ? item.detailTitle! : item.title!
  57. guard let action = UserAction(rawValue: actionName) else {
  58. // The row tapped has no affiliated action.
  59. return
  60. }
  61. switch action {
  62. case .signOut:
  63. signCurrentUserOut()
  64. case .link:
  65. linkUserToOtherAuthProviders()
  66. case .requestVerifyEmail:
  67. requestVerifyEmail()
  68. case .tokenRefresh:
  69. refreshCurrentUserIDToken()
  70. case .tokenRefreshAsync:
  71. refreshCurrentUserIDTokenAsync()
  72. case .delete:
  73. deleteCurrentUser()
  74. case .updateEmail:
  75. presentEditUserInfoController(for: actionName, to: updateUserEmail)
  76. case .updatePassword:
  77. presentEditUserInfoController(for: actionName, to: updatePassword)
  78. case .updateDisplayName:
  79. presentEditUserInfoController(for: actionName, to: updateUserDisplayName)
  80. case .updatePhotoURL:
  81. presentEditUserInfoController(for: actionName, to: updatePhotoURL)
  82. case .updatePhoneNumber:
  83. presentEditUserInfoController(
  84. for: actionName + " formatted like +16509871234",
  85. to: updatePhoneNumber
  86. )
  87. case .refreshUserInfo:
  88. refreshUserInfo()
  89. }
  90. }
  91. // MARK: - Firebase 🔥
  92. public func signCurrentUserOut() {
  93. try? AppManager.shared.auth().signOut()
  94. updateUI()
  95. }
  96. public func linkUserToOtherAuthProviders() {
  97. guard let user = user else { return }
  98. let accountLinkingController = AccountLinkingViewController(for: user)
  99. let navController = UINavigationController(rootViewController: accountLinkingController)
  100. navigationController?.present(navController, animated: true, completion: nil)
  101. }
  102. public func requestVerifyEmail() {
  103. user?.sendEmailVerification { error in
  104. guard error == nil else { return self.displayError(error) }
  105. print("Verification email sent!")
  106. }
  107. }
  108. public func refreshCurrentUserIDToken() {
  109. let forceRefresh = true
  110. user?.getIDTokenForcingRefresh(forceRefresh) { token, error in
  111. guard error == nil else { return self.displayError(error) }
  112. if let token = token {
  113. print("New token: \(token)")
  114. }
  115. }
  116. }
  117. public func refreshCurrentUserIDTokenAsync() {
  118. Task {
  119. do {
  120. let token = try await user!.idTokenForcingRefresh(true)
  121. print("New token: \(token)")
  122. } catch {
  123. self.displayError(error)
  124. }
  125. }
  126. }
  127. public func refreshUserInfo() {
  128. user?.reload { error in
  129. if let error = error {
  130. print(error)
  131. }
  132. self.updateUI()
  133. }
  134. }
  135. public func updateUserDisplayName(to newDisplayName: String) {
  136. let changeRequest = user?.createProfileChangeRequest()
  137. changeRequest?.displayName = newDisplayName
  138. changeRequest?.commitChanges { error in
  139. guard error == nil else { return self.displayError(error) }
  140. self.updateUI()
  141. }
  142. }
  143. public func updateUserEmail(to newEmail: String) {
  144. user?.updateEmail(to: newEmail, completion: { error in
  145. guard error == nil else { return self.displayError(error) }
  146. self.updateUI()
  147. })
  148. }
  149. public func updatePassword(to newPassword: String) {
  150. user?.updatePassword(to: newPassword, completion: {
  151. error in
  152. if let error = error {
  153. print("Update password failed. \(error)", error)
  154. return
  155. } else {
  156. print("Password updated!")
  157. }
  158. self.updateUI()
  159. })
  160. }
  161. public func updatePhotoURL(to newPhotoURL: String) {
  162. guard let newPhotoURL = URL(string: newPhotoURL) else {
  163. print("Could not create new photo URL!")
  164. return
  165. }
  166. let changeRequest = user?.createProfileChangeRequest()
  167. changeRequest?.photoURL = newPhotoURL
  168. changeRequest?.commitChanges { error in
  169. guard error == nil else { return self.displayError(error) }
  170. self.updateUI()
  171. }
  172. }
  173. public func updatePhoneNumber(to newPhoneNumber: String) {
  174. Task {
  175. do {
  176. let phoneAuthProvider = PhoneAuthProvider.provider()
  177. let verificationID = try await phoneAuthProvider.verifyPhoneNumber(newPhoneNumber)
  178. let verificationCode = try await getVerificationCode()
  179. let credential = phoneAuthProvider.credential(withVerificationID: verificationID,
  180. verificationCode: verificationCode)
  181. try await user?.updatePhoneNumber(credential)
  182. self.updateUI()
  183. } catch {
  184. self.displayError(error)
  185. }
  186. }
  187. }
  188. // MARK: - Sign in with Apple Token Revocation Flow
  189. // For Sign in with Apple
  190. private var currentNonce: String?
  191. // [START token_revocation_deleteuser]
  192. private func deleteCurrentUser() {
  193. do {
  194. let nonce = try CryptoUtils.randomNonceString()
  195. currentNonce = nonce
  196. let appleIDProvider = ASAuthorizationAppleIDProvider()
  197. let request = appleIDProvider.createRequest()
  198. request.requestedScopes = [.fullName, .email]
  199. request.nonce = CryptoUtils.sha256(nonce)
  200. let authorizationController = ASAuthorizationController(authorizationRequests: [request])
  201. authorizationController.delegate = self
  202. authorizationController.presentationContextProvider = self
  203. authorizationController.performRequests()
  204. } catch {
  205. // In the unlikely case that nonce generation fails, show error view.
  206. displayError(error)
  207. }
  208. }
  209. // [END token_revocation_deleteuser]
  210. // MARK: - Private Helpers
  211. private func getVerificationCode() async throws -> String {
  212. return try await withCheckedThrowingContinuation { continuation in
  213. self.presentEditUserInfoController(for: "Phone Auth Verification Code") { code in
  214. if code != "" {
  215. continuation.resume(returning: code)
  216. } else {
  217. // Cancelled
  218. continuation.resume(throwing: NSError())
  219. }
  220. }
  221. }
  222. }
  223. private func configureNavigationBar() {
  224. navigationItem.title = "User"
  225. guard let navigationBar = navigationController?.navigationBar else { return }
  226. navigationBar.prefersLargeTitles = true
  227. navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  228. navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  229. navigationBar.addProfilePic(userImage)
  230. }
  231. private func updateUserImage() {
  232. guard let photoURL = user?.photoURL else {
  233. let defaultImage = UIImage(systemName: "person.circle.fill")
  234. userImage.image = defaultImage?.withTintColor(.secondaryLabel, renderingMode: .alwaysOriginal)
  235. return
  236. }
  237. userImage.setImage(from: photoURL)
  238. }
  239. private func configureDataSourceProvider() {
  240. dataSourceProvider = DataSourceProvider(
  241. dataSource: user?.sections,
  242. emptyStateView: SignedOutView(),
  243. tableView: tableView
  244. )
  245. dataSourceProvider.delegate = self
  246. }
  247. private func updateUI() {
  248. configureDataSourceProvider()
  249. animateUpdates(for: tableView)
  250. updateUserImage()
  251. }
  252. private func animateUpdates(for tableView: UITableView) {
  253. UIView.transition(with: tableView, duration: 0.2,
  254. options: .transitionCrossDissolve,
  255. animations: { tableView.reloadData() })
  256. }
  257. private func presentEditUserInfoController(for title: String,
  258. to saveHandler: @escaping (String) -> Void) {
  259. let editController = UIAlertController(
  260. title: "Update \(title)",
  261. message: nil,
  262. preferredStyle: .alert
  263. )
  264. editController.addTextField { $0.placeholder = "New \(title)" }
  265. let saveHandler1: (UIAlertAction) -> Void = { _ in
  266. let text = editController.textFields!.first!.text!
  267. saveHandler(text)
  268. }
  269. let cancel: (UIAlertAction) -> Void = { _ in
  270. saveHandler("")
  271. }
  272. editController.addAction(UIAlertAction(title: "Save", style: .default, handler: saveHandler1))
  273. editController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: cancel))
  274. present(editController, animated: true, completion: nil)
  275. }
  276. private var originalOffset: CGFloat?
  277. private func adjustUserImageAlpha(_ offset: CGFloat) {
  278. originalOffset = originalOffset ?? offset
  279. let verticalOffset = offset - originalOffset!
  280. userImage.alpha = 1 - (verticalOffset * 0.05)
  281. }
  282. }
  283. // MARK: - Implementing Sign in with Apple for the Token Revocation Flow
  284. extension UserViewController: ASAuthorizationControllerDelegate,
  285. ASAuthorizationControllerPresentationContextProviding {
  286. // MARK: ASAuthorizationControllerDelegate
  287. // [START token_revocation]
  288. func authorizationController(controller: ASAuthorizationController,
  289. didCompleteWithAuthorization authorization: ASAuthorization) {
  290. guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential
  291. else {
  292. print("Unable to retrieve AppleIDCredential")
  293. return
  294. }
  295. guard let _ = currentNonce else {
  296. fatalError("Invalid state: A login callback was received, but no login request was sent.")
  297. }
  298. guard let appleAuthCode = appleIDCredential.authorizationCode else {
  299. print("Unable to fetch authorization code")
  300. return
  301. }
  302. guard let authCodeString = String(data: appleAuthCode, encoding: .utf8) else {
  303. print("Unable to serialize auth code string from data: \(appleAuthCode.debugDescription)")
  304. return
  305. }
  306. Task {
  307. do {
  308. try await AppManager.shared.auth().revokeToken(withAuthorizationCode: authCodeString)
  309. try await user?.delete()
  310. self.updateUI()
  311. } catch {
  312. self.displayError(error)
  313. }
  314. }
  315. }
  316. // [END token_revocation]
  317. func authorizationController(controller: ASAuthorizationController,
  318. didCompleteWithError error: any Error) {
  319. // Ensure that you have:
  320. // - enabled `Sign in with Apple` on the Firebase console
  321. // - added the `Sign in with Apple` capability for this project
  322. print("Sign in with Apple failed: \(error)")
  323. }
  324. // MARK: ASAuthorizationControllerPresentationContextProviding
  325. func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
  326. return view.window!
  327. }
  328. }