AccountLinkingViewController.swift 17 KB

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