AccountLinkingViewController.swift 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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 FirebaseAuth
  15. import FirebaseCore
  16. import GameKit
  17. import UIKit
  18. // For Account Linking with Sign in with Google.
  19. import GoogleSignIn
  20. // For Account Linking with Sign in with Facebook.
  21. import FBSDKLoginKit
  22. // For Account Linking with Sign in with Apple.
  23. import AuthenticationServices
  24. import CryptoKit
  25. class AccountLinkingViewController: UIViewController, DataSourceProviderDelegate {
  26. var dataSourceProvider: DataSourceProvider<AuthMenuData>!
  27. var tableView: UITableView { view as! UITableView }
  28. override func loadView() {
  29. view = UITableView(frame: .zero, style: .insetGrouped)
  30. }
  31. let user: User
  32. /// Designated initializer requires a valid, non-nil Firebase user.
  33. /// - Parameter user: An instance of a Firebase `User`.
  34. init(for user: User) {
  35. self.user = user
  36. super.init(nibName: nil, bundle: nil)
  37. }
  38. @available(*, unavailable)
  39. required init?(coder: NSCoder) {
  40. fatalError("init(coder:) has not been implemented")
  41. }
  42. override func viewDidLoad() {
  43. super.viewDidLoad()
  44. configureNavigationBar()
  45. configureDataSourceProvider()
  46. registerForLoginNotifications()
  47. }
  48. override func viewWillAppear(_ animated: Bool) {
  49. super.viewWillAppear(animated)
  50. navigationController?.setTitleColor(.systemOrange)
  51. }
  52. // MARK: - DataSourceProviderDelegate
  53. func didSelectRowAt(_ indexPath: IndexPath, on tableView: UITableView) {
  54. let item = dataSourceProvider.item(at: indexPath)
  55. let providerName = item.title!
  56. guard let provider = AuthMenu(rawValue: providerName) else {
  57. // The row tapped has no affiliated action.
  58. return
  59. }
  60. // If the item's affiliated provider is currently linked with the user,
  61. // unlink the provider from the user's account.
  62. if item.isChecked {
  63. Task { await unlinkFromProvider(provider.id) }
  64. return
  65. }
  66. switch provider {
  67. case .google:
  68. performGoogleAccountLink()
  69. case .apple:
  70. Task { await performAppleAccountLink() }
  71. case .facebook:
  72. performFacebookAccountLink()
  73. case .twitter, .microsoft, .gitHub, .yahoo, .linkedIn:
  74. performOAuthAccountLink(for: provider)
  75. case .gameCenter:
  76. performGameCenterAccountLink()
  77. case .emailPassword:
  78. performEmailPasswordAccountLink()
  79. case .passwordless:
  80. performPasswordlessAccountLink()
  81. case .phoneNumber:
  82. performPhoneNumberAccountLink()
  83. default:
  84. break
  85. }
  86. }
  87. // MARK: Firebase 🔥
  88. /// Wrapper method that uses Firebase's `link(with:)` API to link a user to another auth provider.
  89. /// Used when linking a user to each of the following auth providers.
  90. /// This method will update the UI upon the linking's completion.
  91. /// - Parameter authCredential: The credential used to link the user with the auth provider.
  92. private func linkAccount(authCredential: AuthCredential) {
  93. user.link(with: authCredential) { result, error in
  94. guard error == nil else { return self.displayError(error) }
  95. self.updateUI()
  96. }
  97. }
  98. /// Used for Sign in with Apple token revocation flow.
  99. private var continuation: CheckedContinuation<ASAuthorizationAppleIDCredential, Error>?
  100. /// Wrapper method that uses Firebase's `unlink(fromProvider:)` API to unlink a user from an auth
  101. /// provider.
  102. /// This method will update the UI upon the unlinking's completion.
  103. /// - Parameter providerID: The string id of the auth provider.
  104. private func unlinkFromProvider(_ providerID: String) async {
  105. if providerID == AuthProviderID.apple.rawValue {
  106. // Needs SiwA token revocation.
  107. do {
  108. let needsTokenRevocation = user.providerData
  109. .contains { $0.providerID == AuthProviderID.apple.rawValue }
  110. if needsTokenRevocation {
  111. let appleIDCredential = try await signInWithApple()
  112. guard let appleIDToken = appleIDCredential.identityToken else {
  113. print("Unable to fetch identify token.")
  114. return
  115. }
  116. guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
  117. print("Unable to serialise token string from data: \(appleIDToken.debugDescription)")
  118. return
  119. }
  120. let nonce = try CryptoUtils.randomNonceString()
  121. let credential = OAuthProvider.credential(providerID: .apple,
  122. idToken: idTokenString,
  123. rawNonce: nonce)
  124. try await user.reauthenticate(with: credential)
  125. if
  126. let authorizationCode = appleIDCredential.authorizationCode,
  127. let authCodeString = String(data: authorizationCode, encoding: .utf8) {
  128. try await Auth.auth().revokeToken(withAuthorizationCode: authCodeString)
  129. }
  130. }
  131. } catch {
  132. displayError(error)
  133. }
  134. }
  135. do {
  136. _ = try await user.unlink(fromProvider: providerID)
  137. updateUI()
  138. } catch {
  139. displayError(error)
  140. }
  141. }
  142. // MARK: - Sign in with Google Account Linking 🔥
  143. /// This method will initate the Google Sign In flow.
  144. /// See this class's conformance to `GIDSignInDelegate` below for
  145. /// context on how the linking is made.
  146. private func performGoogleAccountLink() {
  147. guard let clientID = FirebaseApp.app()?.options.clientID else { return }
  148. // Create Google Sign In configuration object.
  149. // TODO: Move configuration to Info.plist
  150. let config = GIDConfiguration(clientID: clientID)
  151. GIDSignIn.sharedInstance.configuration = config
  152. // Start the sign in flow!
  153. GIDSignIn.sharedInstance.signIn(withPresenting: self) { [unowned self] result, error in
  154. guard error == nil else { return displayError(error) }
  155. guard
  156. let user = result?.user,
  157. let idToken = user.idToken?.tokenString
  158. else {
  159. let error = NSError(
  160. domain: "GIDSignInError",
  161. code: -1,
  162. userInfo: [
  163. NSLocalizedDescriptionKey: "Unexpected sign in result: required authentication data is missing.",
  164. ]
  165. )
  166. return displayError(error)
  167. }
  168. let credential = GoogleAuthProvider.credential(withIDToken: idToken,
  169. accessToken: user.accessToken.tokenString)
  170. // Rather than use the credential to sign in the user, we will use it to link to the currently
  171. // signed in user's account.
  172. linkAccount(authCredential: credential)
  173. }
  174. }
  175. // MARK: - Sign in with Apple Account Linking 🔥
  176. /// This method will initate the Sign In with Apple flow.
  177. /// See this class's conformance to `ASAuthorizationControllerDelegate` below for
  178. /// context on how the linking is made.
  179. private func performAppleAccountLink() async {
  180. do {
  181. let appleIDCredential = try await signInWithApple()
  182. guard let appleIDToken = appleIDCredential.identityToken else {
  183. fatalError("Unable to fetch identify token.")
  184. }
  185. guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
  186. fatalError("Unable to serialise token string from data: \(appleIDToken.debugDescription)")
  187. }
  188. let nonce = try CryptoUtils.randomNonceString()
  189. let credential = OAuthProvider.credential(providerID: .apple,
  190. idToken: idTokenString,
  191. rawNonce: nonce)
  192. linkAccount(authCredential: credential)
  193. } catch {
  194. displayError(error)
  195. }
  196. }
  197. // MARK: - Twitter, Microsoft, GitHub, Yahoo, LinkedIn Account Linking 🔥
  198. // Maintain a strong reference to an OAuthProvider for login
  199. private var oauthProvider: OAuthProvider!
  200. private func performOAuthAccountLink(for provider: AuthMenu) {
  201. oauthProvider = OAuthProvider(providerID: provider.id)
  202. oauthProvider.getCredentialWith(nil) { [weak self] credential, error in
  203. guard let strongSelf = self else { return }
  204. guard error == nil else { return strongSelf.displayError(error) }
  205. guard let credential = credential else { return }
  206. strongSelf.linkAccount(authCredential: credential)
  207. }
  208. }
  209. // MARK: - Sign in with Facebook Account Linking 🔥
  210. private func performFacebookAccountLink() {
  211. // The following config can also be stored in the project's .plist
  212. Settings.shared.appID = "ENTER APP ID HERE"
  213. Settings.shared.displayName = "AuthenticationExample"
  214. // Create a Facebook `LoginManager` instance
  215. let loginManager = LoginManager()
  216. loginManager.logIn(permissions: ["email"], from: self) { [weak self] result, error in
  217. guard let strongSelf = self else { return }
  218. guard error == nil else { return strongSelf.displayError(error) }
  219. guard let accessToken = AccessToken.current else { return }
  220. let credential = FacebookAuthProvider.credential(withAccessToken: accessToken.tokenString)
  221. strongSelf.linkAccount(authCredential: credential)
  222. }
  223. }
  224. private func performGameCenterAccountLink() {
  225. // Step 1: Ensure Game Center Authentication
  226. guard GKLocalPlayer.local.isAuthenticated else {
  227. print("Error: Player not authenticated with Game Center.")
  228. return
  229. }
  230. // Step 2: Get Game Center Credential for Linking
  231. GameCenterAuthProvider.getCredential { credential, error in
  232. if let error = error {
  233. print("Error getting Game Center credential: \(error.localizedDescription)")
  234. return
  235. }
  236. guard let credential = credential else {
  237. print("Error: Missing Game Center credential")
  238. return
  239. }
  240. // Step 3: Link Credential with Current Firebase User
  241. Auth.auth().currentUser?.link(with: credential) { authResult, error in
  242. if let error = error {
  243. print("Error linking Game Center to Firebase: \(error.localizedDescription)")
  244. return
  245. }
  246. }
  247. }
  248. }
  249. // MARK: - Email & Password Login Account Linking 🔥
  250. private func performEmailPasswordAccountLink() {
  251. presentEmailPasswordLinkAlertController { [weak self] email, password in
  252. guard let strongSelf = self else { return }
  253. let credential = EmailAuthProvider.credential(withEmail: email, password: password)
  254. strongSelf.linkAccount(authCredential: credential)
  255. }
  256. }
  257. // MARK: - Phone Number Account Linking 🔥
  258. public func performPhoneNumberAccountLink() {
  259. presentPhoneNumberAlertController { [weak self] phoneNumber in
  260. let phoneNumber = String(format: "+%@", phoneNumber)
  261. PhoneAuthProvider.provider()
  262. .verifyPhoneNumber(phoneNumber, uiDelegate: nil) { verificationID, error in
  263. guard let strongSelf = self else { return }
  264. guard error == nil else { return strongSelf.displayError(error) }
  265. guard let verificationID = verificationID else { return }
  266. strongSelf.presentPhoneLinkAlertController { verificationCode in
  267. let credential = PhoneAuthProvider.provider()
  268. .credential(withVerificationID: verificationID, verificationCode: verificationCode)
  269. strongSelf.linkAccount(authCredential: credential)
  270. }
  271. }
  272. }
  273. }
  274. private func presentPhoneNumberAlertController(linkHandler: @escaping (String) -> Void) {
  275. presentTextFieldAlertController(
  276. title: "Link with Phone Auth",
  277. message: "Example input for +1 (123)456-7890 would be 11234567890",
  278. textfieldPlaceholder: "Enter a phone number.",
  279. saveHandler: linkHandler
  280. )
  281. }
  282. private func presentPhoneLinkAlertController(saveHandler: @escaping (String) -> Void) {
  283. presentTextFieldAlertController(
  284. title: "Link with Phone Auth",
  285. textfieldPlaceholder: "Enter verification code.",
  286. saveHandler: saveHandler
  287. )
  288. }
  289. // MARK: - Email Link/Passwordless Account Linking 🔥
  290. /// Similar to in `PasswordlessViewController`, enter the authorized domain.
  291. /// Please refer to this Quickstart's README for more information.
  292. private let authorizedDomain: String = "ENTER AUTHORIZED DOMAIN"
  293. /// This is the replacement for customized dynamic link domain.
  294. private let customDomain: String = "ENTER AUTHORIZED HOSTING DOMAIN"
  295. /// Maintain a reference to the email entered for linking user to Passwordless.
  296. private var email: String?
  297. private func performPasswordlessAccountLink() {
  298. presentPasswordlessAlertController { [weak self] email in
  299. guard let strongSelf = self else { return }
  300. strongSelf.sendSignInLink(to: email)
  301. }
  302. }
  303. private func presentPasswordlessAlertController(saveHandler: @escaping (String) -> Void) {
  304. presentTextFieldAlertController(
  305. title: "Link with Passwordless Login",
  306. message: "Leave this view up while you check your email for the verification link.",
  307. textfieldPlaceholder: "Enter a valid email address.",
  308. saveHandler: saveHandler
  309. )
  310. }
  311. private func sendSignInLink(to email: String) {
  312. let actionCodeSettings = ActionCodeSettings()
  313. let stringURL = "https://\(authorizedDomain).firebaseapp.com/login?email=\(email)"
  314. actionCodeSettings.url = URL(string: stringURL)
  315. // The sign-in operation must be completed in the app.
  316. actionCodeSettings.handleCodeInApp = true
  317. actionCodeSettings.setIOSBundleID(Bundle.main.bundleIdentifier!)
  318. actionCodeSettings.linkDomain = customDomain
  319. AppManager.shared.auth()
  320. .sendSignInLink(toEmail: email, actionCodeSettings: actionCodeSettings) { error in
  321. guard error == nil else { return self.displayError(error) }
  322. // Set `email` property as it will be used to complete sign in after opening email link
  323. self.email = email
  324. }
  325. }
  326. @objc
  327. private func passwordlessSignIn() {
  328. // Retrieve link that we stored in user defaults in `SceneDelegate`.
  329. guard let email = email,
  330. let link = UserDefaults.standard.value(forKey: "Link") as? String else { return }
  331. let credential = EmailAuthProvider.credential(withEmail: email, link: link)
  332. linkAccount(authCredential: credential)
  333. self.email = nil
  334. }
  335. private func registerForLoginNotifications() {
  336. NotificationCenter.default.addObserver(
  337. self,
  338. selector: #selector(passwordlessSignIn),
  339. name: Notification.Name("PasswordlessEmailNotificationSuccess"),
  340. object: nil
  341. )
  342. }
  343. // MARK: - UI Configuration
  344. private func configureNavigationBar() {
  345. navigationItem.title = "Account Linking"
  346. navigationItem.backBarButtonItem?.tintColor = .systemYellow
  347. navigationController?.navigationBar.prefersLargeTitles = true
  348. }
  349. private func presentTextFieldAlertController(title: String? = nil,
  350. message: String? = nil,
  351. textfieldPlaceholder: String? = nil,
  352. saveHandler: @escaping (String) -> Void) {
  353. let textFieldAlertController = UIAlertController(
  354. title: title,
  355. message: message,
  356. preferredStyle: .alert
  357. )
  358. textFieldAlertController.addTextField { textfield in
  359. textfield.placeholder = textfieldPlaceholder
  360. textfield.textContentType = .oneTimeCode
  361. }
  362. let onContinue: (UIAlertAction) -> Void = { _ in
  363. let text = textFieldAlertController.textFields!.first!.text!
  364. saveHandler(text)
  365. }
  366. textFieldAlertController.addAction(
  367. UIAlertAction(title: "Continue", style: .default, handler: onContinue)
  368. )
  369. textFieldAlertController.addAction(
  370. UIAlertAction(title: "Cancel", style: .cancel)
  371. )
  372. present(textFieldAlertController, animated: true, completion: nil)
  373. }
  374. private func presentEmailPasswordLinkAlertController(linkHandler: @escaping (String, String)
  375. -> Void) {
  376. let loginAlertController = UIAlertController(
  377. title: "Link Password Auth",
  378. message: "Enter a valid email and password to link",
  379. preferredStyle: .alert
  380. )
  381. for placeholder in ["Email", "Password"] {
  382. loginAlertController.addTextField { textfield in
  383. textfield.placeholder = placeholder
  384. }
  385. }
  386. let onContinue: (UIAlertAction) -> Void = { _ in
  387. let email = loginAlertController.textFields![0].text!
  388. let password = loginAlertController.textFields![1].text!
  389. linkHandler(email, password)
  390. }
  391. loginAlertController
  392. .addAction(UIAlertAction(title: "Continue", style: .default, handler: onContinue))
  393. loginAlertController.addAction(UIAlertAction(title: "Cancel", style: .cancel))
  394. present(loginAlertController, animated: true, completion: nil)
  395. }
  396. // MARK: - TableView Configuration & Refresh
  397. private func configureDataSourceProvider() {
  398. dataSourceProvider = DataSourceProvider(
  399. dataSource: sections,
  400. tableView: tableView
  401. )
  402. dataSourceProvider.delegate = self
  403. }
  404. @MainActor private func updateUI() {
  405. configureDataSourceProvider()
  406. animateUpdates(for: tableView)
  407. }
  408. private func animateUpdates(for tableView: UITableView) {
  409. UIView.transition(with: tableView, duration: 0.05,
  410. options: .transitionCrossDissolve,
  411. animations: { tableView.reloadData() })
  412. }
  413. }
  414. // MARK: DataSourceProvidable
  415. extension AccountLinkingViewController: DataSourceProvidable {
  416. var sections: [Section] { buildSections() }
  417. private func buildSections() -> [Section] {
  418. var section = AuthMenuData.authLinkSections.first!
  419. section.items = section.items.compactMap { item -> Item? in
  420. var item = item
  421. item.hasNestedContent = false
  422. item.isChecked = userProviderDataContains(item: item)
  423. return ["Anonymous Authentication", "Custom Auth System"].contains(item.title) ? nil : item
  424. }
  425. return [section]
  426. }
  427. private func userProviderDataContains(item: Item) -> Bool {
  428. guard let authProvider = AuthMenu(rawValue: item.title ?? "") else { return false }
  429. return user.providerData.map { $0.providerID }.contains(authProvider.id)
  430. }
  431. }
  432. // MARK: - Implementing Sign in with Apple with Firebase
  433. extension AccountLinkingViewController: ASAuthorizationControllerDelegate,
  434. ASAuthorizationControllerPresentationContextProviding {
  435. // MARK: ASAuthorizationControllerDelegate
  436. func signInWithApple() async throws -> ASAuthorizationAppleIDCredential {
  437. return try await withCheckedThrowingContinuation { continuation in
  438. self.continuation = continuation
  439. let appleIDProvider = ASAuthorizationAppleIDProvider()
  440. let request = appleIDProvider.createRequest()
  441. request.requestedScopes = [.fullName, .email]
  442. let authorizationController = ASAuthorizationController(authorizationRequests: [request])
  443. authorizationController.delegate = self
  444. authorizationController.performRequests()
  445. }
  446. }
  447. func authorizationController(controller: ASAuthorizationController,
  448. didCompleteWithAuthorization authorization: ASAuthorization) {
  449. if case let appleIDCredential as ASAuthorizationAppleIDCredential = authorization.credential {
  450. continuation?.resume(returning: appleIDCredential)
  451. } else {
  452. fatalError("Unexpected authorization credential type.")
  453. }
  454. }
  455. func authorizationController(controller: ASAuthorizationController,
  456. didCompleteWithError error: any Error) {
  457. // Ensure that you have:
  458. // - enabled `Sign in with Apple` on the Firebase console
  459. // - added the `Sign in with Apple` capability for this project
  460. continuation?.resume(throwing: error)
  461. }
  462. // MARK: ASAuthorizationControllerPresentationContextProviding
  463. func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
  464. return view.window!
  465. }
  466. }