AccountLinkingViewController.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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:
  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 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. // TODO: Handle the 'not authenticated' scenario (e.g., prompt the user)
  197. return
  198. }
  199. // Step 2: Get Game Center Credential for Linking
  200. GameCenterAuthProvider.getCredential { credential, error in
  201. if let error = error {
  202. print("Error getting Game Center credential: \(error.localizedDescription)")
  203. // TODO: Handle the credential error
  204. return
  205. }
  206. guard let credential = credential else {
  207. print("Error: Missing Game Center credential")
  208. // TODO: Handle the missing credential case
  209. return
  210. }
  211. // Step 3: Link Credential with Current Firebase User
  212. Auth.auth().currentUser?.link(with: credential) { authResult, error in
  213. if let error = error {
  214. print("Error linking Game Center to Firebase: \(error.localizedDescription)")
  215. // TODO: Handle the linking error
  216. return
  217. }
  218. // Linking successful
  219. print("Successfully linked Game Center to Firebase")
  220. }
  221. }
  222. }
  223. // MARK: - Email & Password Login Account Linking 🔥
  224. private func performEmailPasswordAccountLink() {
  225. presentEmailPasswordLinkAlertController { [weak self] email, password in
  226. guard let strongSelf = self else { return }
  227. let credential = EmailAuthProvider.credential(withEmail: email, password: password)
  228. strongSelf.linkAccount(authCredential: credential)
  229. }
  230. }
  231. // MARK: - Phone Number Account Linking 🔥
  232. public func performPhoneNumberAccountLink() {
  233. presentPhoneNumberAlertController { [weak self] phoneNumber in
  234. let phoneNumber = String(format: "+%@", phoneNumber)
  235. PhoneAuthProvider.provider()
  236. .verifyPhoneNumber(phoneNumber, uiDelegate: nil) { verificationID, error in
  237. guard let strongSelf = self else { return }
  238. guard error == nil else { return strongSelf.displayError(error) }
  239. guard let verificationID = verificationID else { return }
  240. strongSelf.presentPhoneLinkAlertController { verificationCode in
  241. let credential = PhoneAuthProvider.provider()
  242. .credential(withVerificationID: verificationID, verificationCode: verificationCode)
  243. strongSelf.linkAccount(authCredential: credential)
  244. }
  245. }
  246. }
  247. }
  248. private func presentPhoneNumberAlertController(linkHandler: @escaping (String) -> Void) {
  249. presentTextFieldAlertController(
  250. title: "Link with Phone Auth",
  251. message: "Example input for +1 (123)456-7890 would be 11234567890",
  252. textfieldPlaceholder: "Enter a phone number.",
  253. saveHandler: linkHandler
  254. )
  255. }
  256. private func presentPhoneLinkAlertController(saveHandler: @escaping (String) -> Void) {
  257. presentTextFieldAlertController(
  258. title: "Link with Phone Auth",
  259. textfieldPlaceholder: "Enter verification code.",
  260. saveHandler: saveHandler
  261. )
  262. }
  263. // MARK: - Email Link/Passwordless Account Linking 🔥
  264. /// Similar to in `PasswordlessViewController`, enter the authorized domain.
  265. /// Please refer to this Quickstart's README for more information.
  266. private let authorizedDomain: String = "ENTER AUTHORIZED DOMAIN"
  267. /// Maintain a reference to the email entered for linking user to Passwordless.
  268. private var email: String?
  269. private func performPasswordlessAccountLink() {
  270. presentPasswordlessAlertController { [weak self] email in
  271. guard let strongSelf = self else { return }
  272. strongSelf.sendSignInLink(to: email)
  273. }
  274. }
  275. private func presentPasswordlessAlertController(saveHandler: @escaping (String) -> Void) {
  276. presentTextFieldAlertController(
  277. title: "Link with Passwordless Login",
  278. message: "Leave this view up while you check your email for the verification link.",
  279. textfieldPlaceholder: "Enter a valid email address.",
  280. saveHandler: saveHandler
  281. )
  282. }
  283. private func sendSignInLink(to email: String) {
  284. let actionCodeSettings = ActionCodeSettings()
  285. let stringURL = "https://\(authorizedDomain).firebaseapp.com/login?email=\(email)"
  286. actionCodeSettings.url = URL(string: stringURL)
  287. // The sign-in operation must be completed in the app.
  288. actionCodeSettings.handleCodeInApp = true
  289. actionCodeSettings.setIOSBundleID(Bundle.main.bundleIdentifier!)
  290. AppManager.shared.auth()
  291. .sendSignInLink(toEmail: email, actionCodeSettings: actionCodeSettings) { error in
  292. guard error == nil else { return self.displayError(error) }
  293. // Set `email` property as it will be used to complete sign in after opening email link
  294. self.email = email
  295. }
  296. }
  297. @objc
  298. private func passwordlessSignIn() {
  299. // Retrieve link that we stored in user defaults in `SceneDelegate`.
  300. guard let email = email,
  301. let link = UserDefaults.standard.value(forKey: "Link") as? String else { return }
  302. let credential = EmailAuthProvider.credential(withEmail: email, link: link)
  303. linkAccount(authCredential: credential)
  304. self.email = nil
  305. }
  306. private func registerForLoginNotifications() {
  307. NotificationCenter.default.addObserver(
  308. self,
  309. selector: #selector(passwordlessSignIn),
  310. name: Notification.Name("PasswordlessEmailNotificationSuccess"),
  311. object: nil
  312. )
  313. }
  314. // MARK: - UI Configuration
  315. private func configureNavigationBar() {
  316. navigationItem.title = "Account Linking"
  317. navigationItem.backBarButtonItem?.tintColor = .systemYellow
  318. navigationController?.navigationBar.prefersLargeTitles = true
  319. }
  320. private func presentTextFieldAlertController(title: String? = nil,
  321. message: String? = nil,
  322. textfieldPlaceholder: String? = nil,
  323. saveHandler: @escaping (String) -> Void) {
  324. let textFieldAlertController = UIAlertController(
  325. title: title,
  326. message: message,
  327. preferredStyle: .alert
  328. )
  329. textFieldAlertController.addTextField { textfield in
  330. textfield.placeholder = textfieldPlaceholder
  331. textfield.textContentType = .oneTimeCode
  332. }
  333. let onContinue: (UIAlertAction) -> Void = { _ in
  334. let text = textFieldAlertController.textFields!.first!.text!
  335. saveHandler(text)
  336. }
  337. textFieldAlertController.addAction(
  338. UIAlertAction(title: "Continue", style: .default, handler: onContinue)
  339. )
  340. textFieldAlertController.addAction(
  341. UIAlertAction(title: "Cancel", style: .cancel)
  342. )
  343. present(textFieldAlertController, animated: true, completion: nil)
  344. }
  345. private func presentEmailPasswordLinkAlertController(linkHandler: @escaping (String, String)
  346. -> Void) {
  347. let loginAlertController = UIAlertController(
  348. title: "Link Password Auth",
  349. message: "Enter a valid email and password to link",
  350. preferredStyle: .alert
  351. )
  352. ["Email", "Password"].forEach { placeholder in
  353. loginAlertController.addTextField { textfield in
  354. textfield.placeholder = placeholder
  355. }
  356. }
  357. let onContinue: (UIAlertAction) -> Void = { _ in
  358. let email = loginAlertController.textFields![0].text!
  359. let password = loginAlertController.textFields![1].text!
  360. linkHandler(email, password)
  361. }
  362. loginAlertController
  363. .addAction(UIAlertAction(title: "Continue", style: .default, handler: onContinue))
  364. loginAlertController.addAction(UIAlertAction(title: "Cancel", style: .cancel))
  365. present(loginAlertController, animated: true, completion: nil)
  366. }
  367. // MARK: - TableView Configuration & Refresh
  368. private func configureDataSourceProvider() {
  369. dataSourceProvider = DataSourceProvider(
  370. dataSource: sections,
  371. tableView: tableView
  372. )
  373. dataSourceProvider.delegate = self
  374. }
  375. private func updateUI() {
  376. configureDataSourceProvider()
  377. animateUpdates(for: tableView)
  378. }
  379. private func animateUpdates(for tableView: UITableView) {
  380. UIView.transition(with: tableView, duration: 0.05,
  381. options: .transitionCrossDissolve,
  382. animations: { tableView.reloadData() })
  383. }
  384. }
  385. // MARK: DataSourceProvidable
  386. extension AccountLinkingViewController: DataSourceProvidable {
  387. var sections: [Section] { buildSections() }
  388. private func buildSections() -> [Section] {
  389. var section = AuthMenuData.authLinkSections.first!
  390. section.items = section.items.compactMap { item -> Item? in
  391. var item = item
  392. item.hasNestedContent = false
  393. item.isChecked = userProviderDataContains(item: item)
  394. return ["Anonymous Authentication", "Custom Auth System"].contains(item.title) ? nil : item
  395. }
  396. return [section]
  397. }
  398. private func userProviderDataContains(item: Item) -> Bool {
  399. guard let authProvider = AuthMenu(rawValue: item.title ?? "") else { return false }
  400. return user.providerData.map { $0.providerID }.contains(authProvider.id)
  401. }
  402. }
  403. // MARK: - Implementing Sign in with Apple with Firebase
  404. extension AccountLinkingViewController: ASAuthorizationControllerDelegate,
  405. ASAuthorizationControllerPresentationContextProviding {
  406. // MARK: ASAuthorizationControllerDelegate
  407. func authorizationController(controller: ASAuthorizationController,
  408. didCompleteWithAuthorization authorization: ASAuthorization) {
  409. guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential
  410. else {
  411. print("Unable to retrieve AppleIDCredential")
  412. return
  413. }
  414. guard let nonce = currentNonce else {
  415. fatalError("Invalid state: A login callback was received, but no login request was sent.")
  416. }
  417. guard let appleIDToken = appleIDCredential.identityToken else {
  418. print("Unable to fetch identity token")
  419. return
  420. }
  421. guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
  422. print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
  423. return
  424. }
  425. let credential = OAuthProvider.credential(withProviderID: "apple.com",
  426. idToken: idTokenString,
  427. rawNonce: nonce)
  428. // Once we have created the above `credential`, we can link accounts to it.
  429. linkAccount(authCredential: credential)
  430. }
  431. func authorizationController(controller: ASAuthorizationController,
  432. didCompleteWithError error: Error) {
  433. // Ensure that you have:
  434. // - enabled `Sign in with Apple` on the Firebase console
  435. // - added the `Sign in with Apple` capability for this project
  436. print("Sign in with Apple errored: \(error)")
  437. }
  438. // MARK: ASAuthorizationControllerPresentationContextProviding
  439. func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
  440. return view.window!
  441. }
  442. }