UserViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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 .delete:
  71. deleteCurrentUser()
  72. case .updateEmail:
  73. presentEditUserInfoController(for: actionName, to: updateUserEmail)
  74. case .updateDisplayName:
  75. presentEditUserInfoController(for: actionName, to: updateUserDisplayName)
  76. case .updatePhotoURL:
  77. presentEditUserInfoController(for: actionName, to: updatePhotoURL)
  78. case .updatePhoneNumber:
  79. presentEditUserInfoController(
  80. for: actionName + " formatted like +16509871234",
  81. to: updatePhoneNumber
  82. )
  83. case .refreshUserInfo:
  84. refreshUserInfo()
  85. }
  86. }
  87. // MARK: - Firebase 🔥
  88. public func signCurrentUserOut() {
  89. try? AppManager.shared.auth().signOut()
  90. updateUI()
  91. }
  92. public func linkUserToOtherAuthProviders() {
  93. guard let user = user else { return }
  94. let accountLinkingController = AccountLinkingViewController(for: user)
  95. let navController = UINavigationController(rootViewController: accountLinkingController)
  96. navigationController?.present(navController, animated: true, completion: nil)
  97. }
  98. public func requestVerifyEmail() {
  99. user?.sendEmailVerification { error in
  100. guard error == nil else { return self.displayError(error) }
  101. print("Verification email sent!")
  102. }
  103. }
  104. public func refreshCurrentUserIDToken() {
  105. let forceRefresh = true
  106. user?.getIDTokenForcingRefresh(forceRefresh) { token, error in
  107. guard error == nil else { return self.displayError(error) }
  108. if let token = token {
  109. print("New token: \(token)")
  110. }
  111. }
  112. }
  113. public func refreshUserInfo() {
  114. user?.reload { error in
  115. if let error = error {
  116. print(error)
  117. }
  118. self.updateUI()
  119. }
  120. }
  121. public func updateUserDisplayName(to newDisplayName: String) {
  122. let changeRequest = user?.createProfileChangeRequest()
  123. changeRequest?.displayName = newDisplayName
  124. changeRequest?.commitChanges { error in
  125. guard error == nil else { return self.displayError(error) }
  126. self.updateUI()
  127. }
  128. }
  129. public func updateUserEmail(to newEmail: String) {
  130. user?.updateEmail(to: newEmail, completion: { error in
  131. guard error == nil else { return self.displayError(error) }
  132. self.updateUI()
  133. })
  134. }
  135. public func updatePhotoURL(to newPhotoURL: String) {
  136. guard let newPhotoURL = URL(string: newPhotoURL) else {
  137. print("Could not create new photo URL!")
  138. return
  139. }
  140. let changeRequest = user?.createProfileChangeRequest()
  141. changeRequest?.photoURL = newPhotoURL
  142. changeRequest?.commitChanges { error in
  143. guard error == nil else { return self.displayError(error) }
  144. self.updateUI()
  145. }
  146. }
  147. public func updatePhoneNumber(to newPhoneNumber: String) {
  148. Task {
  149. do {
  150. let phoneAuthProvider = PhoneAuthProvider.provider()
  151. let verificationID = try await phoneAuthProvider.verifyPhoneNumber(newPhoneNumber)
  152. let verificationCode = try await getVerificationCode()
  153. let credential = phoneAuthProvider.credential(withVerificationID: verificationID,
  154. verificationCode: verificationCode)
  155. try await user?.updatePhoneNumber(credential)
  156. self.updateUI()
  157. } catch {
  158. self.displayError(error)
  159. }
  160. }
  161. }
  162. // MARK: - Sign in with Apple Token Revocation Flow
  163. // For Sign in with Apple
  164. private var currentNonce: String?
  165. // [START token_revocation_deleteuser]
  166. private func deleteCurrentUser() {
  167. do {
  168. let nonce = try CryptoUtils.randomNonceString()
  169. currentNonce = nonce
  170. let appleIDProvider = ASAuthorizationAppleIDProvider()
  171. let request = appleIDProvider.createRequest()
  172. request.requestedScopes = [.fullName, .email]
  173. request.nonce = CryptoUtils.sha256(nonce)
  174. let authorizationController = ASAuthorizationController(authorizationRequests: [request])
  175. authorizationController.delegate = self
  176. authorizationController.presentationContextProvider = self
  177. authorizationController.performRequests()
  178. } catch {
  179. // In the unlikely case that nonce generation fails, show error view.
  180. displayError(error)
  181. }
  182. }
  183. // [END token_revocation_deleteuser]
  184. // MARK: - Private Helpers
  185. private func getVerificationCode() async throws -> String {
  186. return try await withCheckedThrowingContinuation { continuation in
  187. self.presentEditUserInfoController(for: "Phone Auth Verification Code") { code in
  188. if code != "" {
  189. continuation.resume(returning: code)
  190. } else {
  191. // Cancelled
  192. continuation.resume(throwing: NSError())
  193. }
  194. }
  195. }
  196. }
  197. private func configureNavigationBar() {
  198. navigationItem.title = "User"
  199. guard let navigationBar = navigationController?.navigationBar else { return }
  200. navigationBar.prefersLargeTitles = true
  201. navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  202. navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  203. navigationBar.addProfilePic(userImage)
  204. }
  205. private func updateUserImage() {
  206. guard let photoURL = user?.photoURL else {
  207. let defaultImage = UIImage(systemName: "person.circle.fill")
  208. userImage.image = defaultImage?.withTintColor(.secondaryLabel, renderingMode: .alwaysOriginal)
  209. return
  210. }
  211. userImage.setImage(from: photoURL)
  212. }
  213. private func configureDataSourceProvider() {
  214. dataSourceProvider = DataSourceProvider(
  215. dataSource: user?.sections,
  216. emptyStateView: SignedOutView(),
  217. tableView: tableView
  218. )
  219. dataSourceProvider.delegate = self
  220. }
  221. private func updateUI() {
  222. configureDataSourceProvider()
  223. animateUpdates(for: tableView)
  224. updateUserImage()
  225. }
  226. private func animateUpdates(for tableView: UITableView) {
  227. UIView.transition(with: tableView, duration: 0.2,
  228. options: .transitionCrossDissolve,
  229. animations: { tableView.reloadData() })
  230. }
  231. private func presentEditUserInfoController(for title: String,
  232. to saveHandler: @escaping (String) -> Void) {
  233. let editController = UIAlertController(
  234. title: "Update \(title)",
  235. message: nil,
  236. preferredStyle: .alert
  237. )
  238. editController.addTextField { $0.placeholder = "New \(title)" }
  239. let saveHandler1: (UIAlertAction) -> Void = { _ in
  240. let text = editController.textFields!.first!.text!
  241. saveHandler(text)
  242. }
  243. let cancel: (UIAlertAction) -> Void = { _ in
  244. saveHandler("")
  245. }
  246. editController.addAction(UIAlertAction(title: "Save", style: .default, handler: saveHandler1))
  247. editController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: cancel))
  248. present(editController, animated: true, completion: nil)
  249. }
  250. private var originalOffset: CGFloat?
  251. private func adjustUserImageAlpha(_ offset: CGFloat) {
  252. originalOffset = originalOffset ?? offset
  253. let verticalOffset = offset - originalOffset!
  254. userImage.alpha = 1 - (verticalOffset * 0.05)
  255. }
  256. }
  257. // MARK: - Implementing Sign in with Apple for the Token Revocation Flow
  258. extension UserViewController: ASAuthorizationControllerDelegate,
  259. ASAuthorizationControllerPresentationContextProviding {
  260. // MARK: ASAuthorizationControllerDelegate
  261. // [START token_revocation]
  262. func authorizationController(controller: ASAuthorizationController,
  263. didCompleteWithAuthorization authorization: ASAuthorization) {
  264. guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential
  265. else {
  266. print("Unable to retrieve AppleIDCredential")
  267. return
  268. }
  269. guard let _ = currentNonce else {
  270. fatalError("Invalid state: A login callback was received, but no login request was sent.")
  271. }
  272. guard let appleAuthCode = appleIDCredential.authorizationCode else {
  273. print("Unable to fetch authorization code")
  274. return
  275. }
  276. guard let authCodeString = String(data: appleAuthCode, encoding: .utf8) else {
  277. print("Unable to serialize auth code string from data: \(appleAuthCode.debugDescription)")
  278. return
  279. }
  280. Task {
  281. do {
  282. try await AppManager.shared.auth().revokeToken(withAuthorizationCode: authCodeString)
  283. try await user?.delete()
  284. self.updateUI()
  285. } catch {
  286. self.displayError(error)
  287. }
  288. }
  289. }
  290. // [END token_revocation]
  291. func authorizationController(controller: ASAuthorizationController,
  292. didCompleteWithError error: Error) {
  293. // Ensure that you have:
  294. // - enabled `Sign in with Apple` on the Firebase console
  295. // - added the `Sign in with Apple` capability for this project
  296. print("Sign in with Apple failed: \(error)")
  297. }
  298. // MARK: ASAuthorizationControllerPresentationContextProviding
  299. func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
  300. return view.window!
  301. }
  302. }