AccountLinkingViewController.swift 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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. unlinkFromProvider(provider.id)
  64. return
  65. }
  66. switch provider {
  67. case .google:
  68. performGoogleAccountLink()
  69. case .apple:
  70. 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. /// Wrapper method that uses Firebase's `unlink(fromProvider:)` API to unlink a user from an auth
  99. /// provider.
  100. /// This method will update the UI upon the unlinking's completion.
  101. /// - Parameter providerID: The string id of the auth provider.
  102. private func unlinkFromProvider(_ providerID: String) {
  103. user.unlink(fromProvider: providerID) { user, error in
  104. guard error == nil else { return self.displayError(error) }
  105. print("Unlinked user from auth provider: \(providerID)")
  106. self.updateUI()
  107. }
  108. }
  109. // MARK: - Sign in with Google Account Linking 🔥
  110. /// This method will initate the Google Sign In flow.
  111. /// See this class's conformance to `GIDSignInDelegate` below for
  112. /// context on how the linking is made.
  113. private func performGoogleAccountLink() {
  114. guard let clientID = FirebaseApp.app()?.options.clientID else { return }
  115. // Create Google Sign In configuration object.
  116. // TODO: Move configuration to Info.plist
  117. let config = GIDConfiguration(clientID: clientID)
  118. GIDSignIn.sharedInstance.configuration = config
  119. // Start the sign in flow!
  120. GIDSignIn.sharedInstance.signIn(withPresenting: self) { [unowned self] result, error in
  121. guard error == nil else { return displayError(error) }
  122. guard
  123. let user = result?.user,
  124. let idToken = user.idToken?.tokenString
  125. else {
  126. let error = NSError(
  127. domain: "GIDSignInError",
  128. code: -1,
  129. userInfo: [
  130. NSLocalizedDescriptionKey: "Unexpected sign in result: required authentication data is missing.",
  131. ]
  132. )
  133. return displayError(error)
  134. }
  135. let credential = GoogleAuthProvider.credential(withIDToken: idToken,
  136. accessToken: user.accessToken.tokenString)
  137. // Rather than use the credential to sign in the user, we will use it to link to the currently
  138. // signed in user's account.
  139. linkAccount(authCredential: credential)
  140. }
  141. }
  142. // MARK: - Sign in with Apple Account Linking 🔥
  143. // For Sign in with Apple
  144. var currentNonce: String?
  145. /// This method will initate the Sign In with Apple flow.
  146. /// See this class's conformance to `ASAuthorizationControllerDelegate` below for
  147. /// context on how the linking is made.
  148. private func performAppleAccountLink() {
  149. do {
  150. let nonce = try CryptoUtils.randomNonceString()
  151. currentNonce = nonce
  152. let appleIDProvider = ASAuthorizationAppleIDProvider()
  153. let request = appleIDProvider.createRequest()
  154. request.requestedScopes = [.fullName, .email]
  155. request.nonce = CryptoUtils.sha256(nonce)
  156. let authorizationController = ASAuthorizationController(authorizationRequests: [request])
  157. authorizationController.delegate = self
  158. authorizationController.presentationContextProvider = self
  159. authorizationController.performRequests()
  160. } catch {
  161. // In the unlikely case that nonce generation fails, show error view.
  162. displayError(error)
  163. }
  164. }
  165. // MARK: - Twitter, Microsoft, GitHub, Yahoo, LinkedIn Account Linking 🔥
  166. // Maintain a strong reference to an OAuthProvider for login
  167. private var oauthProvider: OAuthProvider!
  168. private func performOAuthAccountLink(for provider: AuthMenu) {
  169. oauthProvider = OAuthProvider(providerID: provider.id)
  170. oauthProvider.getCredentialWith(nil) { [weak self] credential, error in
  171. guard let strongSelf = self else { return }
  172. guard error == nil else { return strongSelf.displayError(error) }
  173. guard let credential = credential else { return }
  174. strongSelf.linkAccount(authCredential: credential)
  175. }
  176. }
  177. // MARK: - Sign in with Facebook Account Linking 🔥
  178. private func performFacebookAccountLink() {
  179. // The following config can also be stored in the project's .plist
  180. Settings.shared.appID = "ENTER APP ID HERE"
  181. Settings.shared.displayName = "AuthenticationExample"
  182. // Create a Facebook `LoginManager` instance
  183. let loginManager = LoginManager()
  184. loginManager.logIn(permissions: ["email"], from: self) { [weak self] result, error in
  185. guard let strongSelf = self else { return }
  186. guard error == nil else { return strongSelf.displayError(error) }
  187. guard let accessToken = AccessToken.current else { return }
  188. let credential = FacebookAuthProvider.credential(withAccessToken: accessToken.tokenString)
  189. strongSelf.linkAccount(authCredential: credential)
  190. }
  191. }
  192. private func performGameCenterAccountLink() {
  193. // Step 1: Ensure Game Center Authentication
  194. guard GKLocalPlayer.local.isAuthenticated else {
  195. print("Error: Player not authenticated with Game Center.")
  196. return
  197. }
  198. // Step 2: Get Game Center Credential for Linking
  199. GameCenterAuthProvider.getCredential { credential, error in
  200. if let error = error {
  201. print("Error getting Game Center credential: \(error.localizedDescription)")
  202. return
  203. }
  204. guard let credential = credential else {
  205. print("Error: Missing Game Center credential")
  206. return
  207. }
  208. // Step 3: Link Credential with Current Firebase User
  209. Auth.auth().currentUser?.link(with: credential) { authResult, error in
  210. if let error = error {
  211. print("Error linking Game Center to Firebase: \(error.localizedDescription)")
  212. return
  213. }
  214. }
  215. }
  216. }
  217. // MARK: - Email & Password Login Account Linking 🔥
  218. private func performEmailPasswordAccountLink() {
  219. presentEmailPasswordLinkAlertController { [weak self] email, password in
  220. guard let strongSelf = self else { return }
  221. let credential = EmailAuthProvider.credential(withEmail: email, password: password)
  222. strongSelf.linkAccount(authCredential: credential)
  223. }
  224. }
  225. // MARK: - Phone Number Account Linking 🔥
  226. public func performPhoneNumberAccountLink() {
  227. presentPhoneNumberAlertController { [weak self] phoneNumber in
  228. let phoneNumber = String(format: "+%@", phoneNumber)
  229. PhoneAuthProvider.provider()
  230. .verifyPhoneNumber(phoneNumber, uiDelegate: nil) { verificationID, error in
  231. guard let strongSelf = self else { return }
  232. guard error == nil else { return strongSelf.displayError(error) }
  233. guard let verificationID = verificationID else { return }
  234. strongSelf.presentPhoneLinkAlertController { verificationCode in
  235. let credential = PhoneAuthProvider.provider()
  236. .credential(withVerificationID: verificationID, verificationCode: verificationCode)
  237. strongSelf.linkAccount(authCredential: credential)
  238. }
  239. }
  240. }
  241. }
  242. private func presentPhoneNumberAlertController(linkHandler: @escaping (String) -> Void) {
  243. presentTextFieldAlertController(
  244. title: "Link with Phone Auth",
  245. message: "Example input for +1 (123)456-7890 would be 11234567890",
  246. textfieldPlaceholder: "Enter a phone number.",
  247. saveHandler: linkHandler
  248. )
  249. }
  250. private func presentPhoneLinkAlertController(saveHandler: @escaping (String) -> Void) {
  251. presentTextFieldAlertController(
  252. title: "Link with Phone Auth",
  253. textfieldPlaceholder: "Enter verification code.",
  254. saveHandler: saveHandler
  255. )
  256. }
  257. // MARK: - Email Link/Passwordless Account Linking 🔥
  258. /// Similar to in `PasswordlessViewController`, enter the authorized domain.
  259. /// Please refer to this Quickstart's README for more information.
  260. private let authorizedDomain: String = "ENTER AUTHORIZED DOMAIN"
  261. /// Maintain a reference to the email entered for linking user to Passwordless.
  262. private var email: String?
  263. private func performPasswordlessAccountLink() {
  264. presentPasswordlessAlertController { [weak self] email in
  265. guard let strongSelf = self else { return }
  266. strongSelf.sendSignInLink(to: email)
  267. }
  268. }
  269. private func presentPasswordlessAlertController(saveHandler: @escaping (String) -> Void) {
  270. presentTextFieldAlertController(
  271. title: "Link with Passwordless Login",
  272. message: "Leave this view up while you check your email for the verification link.",
  273. textfieldPlaceholder: "Enter a valid email address.",
  274. saveHandler: saveHandler
  275. )
  276. }
  277. private func sendSignInLink(to email: String) {
  278. let actionCodeSettings = ActionCodeSettings()
  279. let stringURL = "https://\(authorizedDomain).firebaseapp.com/login?email=\(email)"
  280. actionCodeSettings.url = URL(string: stringURL)
  281. // The sign-in operation must be completed in the app.
  282. actionCodeSettings.handleCodeInApp = true
  283. actionCodeSettings.setIOSBundleID(Bundle.main.bundleIdentifier!)
  284. AppManager.shared.auth()
  285. .sendSignInLink(toEmail: email, actionCodeSettings: actionCodeSettings) { error in
  286. guard error == nil else { return self.displayError(error) }
  287. // Set `email` property as it will be used to complete sign in after opening email link
  288. self.email = email
  289. }
  290. }
  291. @objc
  292. private func passwordlessSignIn() {
  293. // Retrieve link that we stored in user defaults in `SceneDelegate`.
  294. guard let email = email,
  295. let link = UserDefaults.standard.value(forKey: "Link") as? String else { return }
  296. let credential = EmailAuthProvider.credential(withEmail: email, link: link)
  297. linkAccount(authCredential: credential)
  298. self.email = nil
  299. }
  300. private func registerForLoginNotifications() {
  301. NotificationCenter.default.addObserver(
  302. self,
  303. selector: #selector(passwordlessSignIn),
  304. name: Notification.Name("PasswordlessEmailNotificationSuccess"),
  305. object: nil
  306. )
  307. }
  308. // MARK: - UI Configuration
  309. private func configureNavigationBar() {
  310. navigationItem.title = "Account Linking"
  311. navigationItem.backBarButtonItem?.tintColor = .systemYellow
  312. navigationController?.navigationBar.prefersLargeTitles = true
  313. }
  314. private func presentTextFieldAlertController(title: String? = nil,
  315. message: String? = nil,
  316. textfieldPlaceholder: String? = nil,
  317. saveHandler: @escaping (String) -> Void) {
  318. let textFieldAlertController = UIAlertController(
  319. title: title,
  320. message: message,
  321. preferredStyle: .alert
  322. )
  323. textFieldAlertController.addTextField { textfield in
  324. textfield.placeholder = textfieldPlaceholder
  325. textfield.textContentType = .oneTimeCode
  326. }
  327. let onContinue: (UIAlertAction) -> Void = { _ in
  328. let text = textFieldAlertController.textFields!.first!.text!
  329. saveHandler(text)
  330. }
  331. textFieldAlertController.addAction(
  332. UIAlertAction(title: "Continue", style: .default, handler: onContinue)
  333. )
  334. textFieldAlertController.addAction(
  335. UIAlertAction(title: "Cancel", style: .cancel)
  336. )
  337. present(textFieldAlertController, animated: true, completion: nil)
  338. }
  339. private func presentEmailPasswordLinkAlertController(linkHandler: @escaping (String, String)
  340. -> Void) {
  341. let loginAlertController = UIAlertController(
  342. title: "Link Password Auth",
  343. message: "Enter a valid email and password to link",
  344. preferredStyle: .alert
  345. )
  346. for placeholder in ["Email", "Password"] {
  347. loginAlertController.addTextField { textfield in
  348. textfield.placeholder = placeholder
  349. }
  350. }
  351. let onContinue: (UIAlertAction) -> Void = { _ in
  352. let email = loginAlertController.textFields![0].text!
  353. let password = loginAlertController.textFields![1].text!
  354. linkHandler(email, password)
  355. }
  356. loginAlertController
  357. .addAction(UIAlertAction(title: "Continue", style: .default, handler: onContinue))
  358. loginAlertController.addAction(UIAlertAction(title: "Cancel", style: .cancel))
  359. present(loginAlertController, animated: true, completion: nil)
  360. }
  361. // MARK: - TableView Configuration & Refresh
  362. private func configureDataSourceProvider() {
  363. dataSourceProvider = DataSourceProvider(
  364. dataSource: sections,
  365. tableView: tableView
  366. )
  367. dataSourceProvider.delegate = self
  368. }
  369. private func updateUI() {
  370. configureDataSourceProvider()
  371. animateUpdates(for: tableView)
  372. }
  373. private func animateUpdates(for tableView: UITableView) {
  374. UIView.transition(with: tableView, duration: 0.05,
  375. options: .transitionCrossDissolve,
  376. animations: { tableView.reloadData() })
  377. }
  378. }
  379. // MARK: DataSourceProvidable
  380. extension AccountLinkingViewController: DataSourceProvidable {
  381. var sections: [Section] { buildSections() }
  382. private func buildSections() -> [Section] {
  383. var section = AuthMenuData.authLinkSections.first!
  384. section.items = section.items.compactMap { item -> Item? in
  385. var item = item
  386. item.hasNestedContent = false
  387. item.isChecked = userProviderDataContains(item: item)
  388. return ["Anonymous Authentication", "Custom Auth System"].contains(item.title) ? nil : item
  389. }
  390. return [section]
  391. }
  392. private func userProviderDataContains(item: Item) -> Bool {
  393. guard let authProvider = AuthMenu(rawValue: item.title ?? "") else { return false }
  394. return user.providerData.map { $0.providerID }.contains(authProvider.id)
  395. }
  396. }
  397. // MARK: - Implementing Sign in with Apple with Firebase
  398. extension AccountLinkingViewController: ASAuthorizationControllerDelegate,
  399. ASAuthorizationControllerPresentationContextProviding {
  400. // MARK: ASAuthorizationControllerDelegate
  401. func authorizationController(controller: ASAuthorizationController,
  402. didCompleteWithAuthorization authorization: ASAuthorization) {
  403. guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential
  404. else {
  405. print("Unable to retrieve AppleIDCredential")
  406. return
  407. }
  408. guard let nonce = currentNonce else {
  409. fatalError("Invalid state: A login callback was received, but no login request was sent.")
  410. }
  411. guard let appleIDToken = appleIDCredential.identityToken else {
  412. print("Unable to fetch identity token")
  413. return
  414. }
  415. guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
  416. print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
  417. return
  418. }
  419. let credential = OAuthProvider.credential(withProviderID: "apple.com",
  420. idToken: idTokenString,
  421. rawNonce: nonce)
  422. // Once we have created the above `credential`, we can link accounts to it.
  423. linkAccount(authCredential: credential)
  424. }
  425. func authorizationController(controller: ASAuthorizationController,
  426. didCompleteWithError error: any Error) {
  427. // Ensure that you have:
  428. // - enabled `Sign in with Apple` on the Firebase console
  429. // - added the `Sign in with Apple` capability for this project
  430. print("Sign in with Apple errored: \(error)")
  431. }
  432. // MARK: ASAuthorizationControllerPresentationContextProviding
  433. func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
  434. return view.window!
  435. }
  436. }