UserViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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. /// Used for Sign in with Apple token revocation flow.
  190. private var continuation: CheckedContinuation<ASAuthorizationAppleIDCredential, Error>?
  191. private func deleteCurrentUser() {
  192. Task {
  193. guard let user else { return }
  194. do {
  195. let needsTokenRevocation = user.providerData
  196. .contains { $0.providerID == AuthProviderID.apple.rawValue }
  197. if needsTokenRevocation {
  198. let appleIDCredential = try await signInWithApple()
  199. guard let appleIDToken = appleIDCredential.identityToken else {
  200. print("Unable to fetch identify token.")
  201. return
  202. }
  203. guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
  204. print("Unable to serialise token string from data: \(appleIDToken.debugDescription)")
  205. return
  206. }
  207. let nonce = try CryptoUtils.randomNonceString()
  208. let credential = OAuthProvider.credential(providerID: .apple,
  209. idToken: idTokenString,
  210. rawNonce: nonce)
  211. try await user.reauthenticate(with: credential)
  212. if
  213. let authorizationCode = appleIDCredential.authorizationCode,
  214. let authCodeString = String(data: authorizationCode, encoding: .utf8) {
  215. try await Auth.auth().revokeToken(withAuthorizationCode: authCodeString)
  216. }
  217. }
  218. try await user.delete()
  219. } catch {
  220. displayError(error)
  221. }
  222. }
  223. }
  224. // MARK: - Private Helpers
  225. private func getVerificationCode() async throws -> String {
  226. return try await withCheckedThrowingContinuation { continuation in
  227. self.presentEditUserInfoController(for: "Phone Auth Verification Code") { code in
  228. if code != "" {
  229. continuation.resume(returning: code)
  230. } else {
  231. // Cancelled
  232. continuation.resume(throwing: NSError())
  233. }
  234. }
  235. }
  236. }
  237. private func configureNavigationBar() {
  238. navigationItem.title = "User"
  239. guard let navigationBar = navigationController?.navigationBar else { return }
  240. navigationBar.prefersLargeTitles = true
  241. navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  242. navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  243. navigationBar.addProfilePic(userImage)
  244. }
  245. private func updateUserImage() {
  246. guard let photoURL = user?.photoURL else {
  247. let defaultImage = UIImage(systemName: "person.circle.fill")
  248. userImage.image = defaultImage?.withTintColor(.secondaryLabel, renderingMode: .alwaysOriginal)
  249. return
  250. }
  251. userImage.setImage(from: photoURL)
  252. }
  253. private func configureDataSourceProvider() {
  254. dataSourceProvider = DataSourceProvider(
  255. dataSource: user?.sections,
  256. emptyStateView: SignedOutView(),
  257. tableView: tableView
  258. )
  259. dataSourceProvider.delegate = self
  260. }
  261. private func updateUI() {
  262. configureDataSourceProvider()
  263. animateUpdates(for: tableView)
  264. updateUserImage()
  265. }
  266. private func animateUpdates(for tableView: UITableView) {
  267. UIView.transition(with: tableView, duration: 0.2,
  268. options: .transitionCrossDissolve,
  269. animations: { tableView.reloadData() })
  270. }
  271. private func presentEditUserInfoController(for title: String,
  272. to saveHandler: @escaping (String) -> Void) {
  273. let editController = UIAlertController(
  274. title: "Update \(title)",
  275. message: nil,
  276. preferredStyle: .alert
  277. )
  278. editController.addTextField { $0.placeholder = "New \(title)" }
  279. let saveHandler1: (UIAlertAction) -> Void = { _ in
  280. let text = editController.textFields!.first!.text!
  281. saveHandler(text)
  282. }
  283. let cancel: (UIAlertAction) -> Void = { _ in
  284. saveHandler("")
  285. }
  286. editController.addAction(UIAlertAction(title: "Save", style: .default, handler: saveHandler1))
  287. editController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: cancel))
  288. present(editController, animated: true, completion: nil)
  289. }
  290. private var originalOffset: CGFloat?
  291. private func adjustUserImageAlpha(_ offset: CGFloat) {
  292. originalOffset = originalOffset ?? offset
  293. let verticalOffset = offset - originalOffset!
  294. userImage.alpha = 1 - (verticalOffset * 0.05)
  295. }
  296. }
  297. // MARK: - Implementing Sign in with Apple for the Token Revocation Flow
  298. extension UserViewController: ASAuthorizationControllerDelegate,
  299. ASAuthorizationControllerPresentationContextProviding {
  300. // MARK: ASAuthorizationControllerDelegate
  301. func signInWithApple() async throws -> ASAuthorizationAppleIDCredential {
  302. return try await withCheckedThrowingContinuation { continuation in
  303. self.continuation = continuation
  304. let appleIDProvider = ASAuthorizationAppleIDProvider()
  305. let request = appleIDProvider.createRequest()
  306. request.requestedScopes = [.fullName, .email]
  307. let authorizationController = ASAuthorizationController(authorizationRequests: [request])
  308. authorizationController.delegate = self
  309. authorizationController.performRequests()
  310. }
  311. }
  312. func authorizationController(controller: ASAuthorizationController,
  313. didCompleteWithAuthorization authorization: ASAuthorization) {
  314. if case let appleIDCredential as ASAuthorizationAppleIDCredential = authorization.credential {
  315. continuation?.resume(returning: appleIDCredential)
  316. } else {
  317. fatalError("Unexpected authorization credential type.")
  318. }
  319. }
  320. func authorizationController(controller: ASAuthorizationController,
  321. didCompleteWithError error: Error) {
  322. continuation?.resume(throwing: error)
  323. }
  324. // MARK: ASAuthorizationControllerPresentationContextProviding
  325. func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
  326. return view.window!
  327. }
  328. }