AuthViewController.swift 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. @testable import FirebaseAuth
  2. // Copyright 2020 Google LLC
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License");
  5. // you may not use this file except in compliance with the License.
  6. // You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. // [START auth_import]
  16. import FirebaseCore
  17. import SwiftUI
  18. // For Sign in with Facebook
  19. import FBSDKLoginKit
  20. // For Sign in with Game Center
  21. import GameKit
  22. // For Sign in with Google
  23. // [START google_import]
  24. import GoogleSignIn
  25. import UIKit
  26. import SwiftUI
  27. // For Sign in with Apple
  28. import AuthenticationServices
  29. import CryptoKit
  30. private let kFacebookAppID = "ENTER APP ID HERE"
  31. private let kContinueUrl = "Enter URL"
  32. class AuthViewController: UIViewController, DataSourceProviderDelegate {
  33. var dataSourceProvider: DataSourceProvider<AuthMenuData>!
  34. var authStateDidChangeListeners: [AuthStateDidChangeListenerHandle] = []
  35. var IDTokenDidChangeListeners: [IDTokenDidChangeListenerHandle] = []
  36. var actionCodeContinueURL: URL?
  37. var actionCodeLinkDomain: String?
  38. var actionCodeRequestType: ActionCodeRequestType = .inApp
  39. let spinner = UIActivityIndicatorView(style: .medium)
  40. var tableView: UITableView { view as! UITableView }
  41. override func loadView() {
  42. view = UITableView(frame: .zero, style: .insetGrouped)
  43. }
  44. override func viewDidLoad() {
  45. super.viewDidLoad()
  46. configureNavigationBar()
  47. configureDataSourceProvider()
  48. }
  49. private func showSpinner() {
  50. spinner.center = view.center
  51. spinner.startAnimating()
  52. view.addSubview(spinner)
  53. }
  54. private func hideSpinner() {
  55. spinner.stopAnimating()
  56. spinner.removeFromSuperview()
  57. }
  58. private func actionCodeSettings() -> ActionCodeSettings {
  59. let settings = ActionCodeSettings()
  60. settings.url = actionCodeContinueURL
  61. settings.handleCodeInApp = (actionCodeRequestType == .inApp)
  62. settings.linkDomain = actionCodeLinkDomain
  63. return settings
  64. }
  65. // MARK: - DataSourceProviderDelegate
  66. func didSelectRowAt(_ indexPath: IndexPath, on tableView: UITableView) {
  67. let item = dataSourceProvider.item(at: indexPath)
  68. guard let providerName = item.title else {
  69. fatalError("Invalid item name")
  70. }
  71. guard let provider = AuthMenu(rawValue: providerName) else {
  72. // The row tapped has no affiliated action.
  73. return
  74. }
  75. switch provider {
  76. case .settings:
  77. performSettings()
  78. case .google:
  79. performGoogleSignInFlow()
  80. case .apple:
  81. performAppleSignInFlow()
  82. case .facebook:
  83. performFacebookSignInFlow()
  84. case .twitter, .microsoft, .gitHub, .yahoo, .linkedIn:
  85. performOAuthLoginFlow(for: provider)
  86. case .gameCenter:
  87. performGameCenterLoginFlow()
  88. case .emailPassword:
  89. performDemoEmailPasswordLoginFlow()
  90. case .passwordless:
  91. performPasswordlessLoginFlow()
  92. case .phoneNumber:
  93. performPhoneNumberLoginFlow()
  94. case .anonymous:
  95. performAnonymousLoginFlow()
  96. case .custom:
  97. performCustomAuthLoginFlow()
  98. case .initRecaptcha:
  99. performInitRecaptcha()
  100. case .customAuthDomain:
  101. performCustomAuthDomainFlow()
  102. case .getToken:
  103. getUserTokenResult(force: false)
  104. case .getTokenForceRefresh:
  105. getUserTokenResult(force: true)
  106. case .addAuthStateChangeListener:
  107. addAuthStateListener()
  108. case .removeLastAuthStateChangeListener:
  109. removeAuthStateListener()
  110. case .addIdTokenChangeListener:
  111. addIDTokenListener()
  112. case .removeLastIdTokenChangeListener:
  113. removeIDTokenListener()
  114. case .verifyClient:
  115. verifyClient()
  116. case .deleteApp:
  117. deleteApp()
  118. case .actionType:
  119. toggleActionCodeRequestType(at: indexPath)
  120. case .continueURL:
  121. changeActionCodeContinueURL(at: indexPath)
  122. case .linkDomain:
  123. changeActionCodeLinkDomain(at: indexPath)
  124. case .requestVerifyEmail:
  125. requestVerifyEmail()
  126. case .requestPasswordReset:
  127. requestPasswordReset()
  128. case .resetPassword:
  129. resetPassword()
  130. case .checkActionCode:
  131. checkActionCode()
  132. case .applyActionCode:
  133. applyActionCode()
  134. case .verifyPasswordResetCode:
  135. verifyPasswordResetCode()
  136. case .phoneEnroll:
  137. phoneEnroll()
  138. case .totpEnroll:
  139. Task { await totpEnroll() }
  140. case .multifactorUnenroll:
  141. mfaUnenroll()
  142. case .exchangeToken:
  143. callExchangeToken()
  144. }
  145. }
  146. // MARK: - Firebase 🔥
  147. private func performSettings() {
  148. let settingsController = SettingsViewController()
  149. navigationController?.pushViewController(settingsController, animated: true)
  150. }
  151. private func performGoogleSignInFlow() {
  152. // [START headless_google_auth]
  153. guard let clientID = FirebaseApp.app()?.options.clientID else { return }
  154. // Create Google Sign In configuration object.
  155. // [START_EXCLUDE silent]
  156. // TODO: Move configuration to Info.plist
  157. // [END_EXCLUDE]
  158. let config = GIDConfiguration(clientID: clientID)
  159. GIDSignIn.sharedInstance.configuration = config
  160. Task {
  161. do {
  162. let result = try await GIDSignIn.sharedInstance.signIn(withPresenting: self)
  163. let user = result.user
  164. guard let idToken = user.idToken?.tokenString
  165. else {
  166. // [START_EXCLUDE]
  167. let error = NSError(
  168. domain: "GIDSignInError",
  169. code: -1,
  170. userInfo: [
  171. NSLocalizedDescriptionKey: "Unexpected sign in result: required authentication data is missing.",
  172. ]
  173. )
  174. return displayError(error)
  175. // [END_EXCLUDE]
  176. }
  177. let credential = GoogleAuthProvider.credential(withIDToken: idToken,
  178. accessToken: user.accessToken.tokenString)
  179. try await signIn(with: credential)
  180. } catch {
  181. return displayError(error)
  182. }
  183. // [END_EXCLUDE]
  184. }
  185. // [END headless_google_auth]
  186. }
  187. func signIn(with credential: AuthCredential) async throws {
  188. do {
  189. _ = try await AppManager.shared.auth().signIn(with: credential)
  190. transitionToUserViewController()
  191. } catch {
  192. let authError = error as NSError
  193. if authError.code == AuthErrorCode.secondFactorRequired.rawValue {
  194. let resolver = authError
  195. .userInfo[AuthErrorUserInfoMultiFactorResolverKey] as! MultiFactorResolver
  196. performMfaLoginFlow(resolver: resolver)
  197. } else {
  198. return displayError(error)
  199. }
  200. }
  201. }
  202. // For Sign in with Apple
  203. var currentNonce: String?
  204. private func performAppleSignInFlow() {
  205. do {
  206. let nonce = try CryptoUtils.randomNonceString()
  207. currentNonce = nonce
  208. let appleIDProvider = ASAuthorizationAppleIDProvider()
  209. let request = appleIDProvider.createRequest()
  210. request.requestedScopes = [.fullName, .email]
  211. request.nonce = CryptoUtils.sha256(nonce)
  212. let authorizationController = ASAuthorizationController(authorizationRequests: [request])
  213. authorizationController.delegate = self
  214. authorizationController.presentationContextProvider = self
  215. authorizationController.performRequests()
  216. } catch {
  217. // In the unlikely case that nonce generation fails, show error view.
  218. displayError(error)
  219. }
  220. }
  221. private func performFacebookSignInFlow() {
  222. // The following config can also be stored in the project's .plist
  223. Settings.shared.appID = kFacebookAppID
  224. Settings.shared.displayName = "AuthenticationExample"
  225. // Create a Facebook `LoginManager` instance
  226. let loginManager = LoginManager()
  227. loginManager.logIn(permissions: ["email"], from: self) { result, error in
  228. guard error == nil else { return self.displayError(error) }
  229. guard let accessToken = AccessToken.current else { return }
  230. let credential = FacebookAuthProvider.credential(withAccessToken: accessToken.tokenString)
  231. self.signin(with: credential)
  232. }
  233. }
  234. // Maintain a strong reference to an OAuthProvider for login
  235. private var oauthProvider: OAuthProvider!
  236. private func performOAuthLoginFlow(for provider: AuthMenu) {
  237. oauthProvider = OAuthProvider(providerID: provider.id)
  238. oauthProvider.getCredentialWith(nil) { credential, error in
  239. guard error == nil else { return self.displayError(error) }
  240. guard let credential = credential else { return }
  241. self.signin(with: credential)
  242. }
  243. }
  244. private func performGameCenterLoginFlow() {
  245. // Step 1: System Game Center Login
  246. GKLocalPlayer.local.authenticateHandler = { viewController, error in
  247. if let error = error {
  248. // Handle Game Center login error
  249. print("Error logging into Game Center: \(error.localizedDescription)")
  250. } else if let authViewController = viewController {
  251. // Present Game Center login UI if needed
  252. self.present(authViewController, animated: true)
  253. } else {
  254. // Game Center login successful, proceed to Firebase
  255. self.linkGameCenterToFirebase()
  256. }
  257. }
  258. }
  259. // Step 2: Link to Firebase
  260. private func linkGameCenterToFirebase() {
  261. GameCenterAuthProvider.getCredential { credential, error in
  262. if let error = error {
  263. // Handle Firebase credential retrieval error
  264. print("Error getting Game Center credential: \(error.localizedDescription)")
  265. } else if let credential = credential {
  266. Auth.auth().signIn(with: credential) { authResult, error in
  267. if let error = error {
  268. // Handle Firebase sign-in error
  269. print("Error signing into Firebase with Game Center: \(error.localizedDescription)")
  270. } else {
  271. // Firebase sign-in successful
  272. print("Successfully linked Game Center to Firebase")
  273. }
  274. }
  275. }
  276. }
  277. }
  278. private func performDemoEmailPasswordLoginFlow() {
  279. let loginView = LoginView(delegate: self)
  280. let hostingController = UIHostingController(rootView: loginView)
  281. hostingController.title = "Email/Password Auth"
  282. navigationController?.pushViewController(hostingController, animated: true)
  283. }
  284. private func performPasswordlessLoginFlow() {
  285. let passwordlessViewController = PasswordlessViewController()
  286. passwordlessViewController.delegate = self
  287. let navPasswordlessAuthController =
  288. UINavigationController(rootViewController: passwordlessViewController)
  289. navigationController?.present(navPasswordlessAuthController, animated: true)
  290. }
  291. private func performPhoneNumberLoginFlow() {
  292. let phoneAuthViewController = PhoneAuthViewController()
  293. phoneAuthViewController.delegate = self
  294. let navPhoneAuthController = UINavigationController(rootViewController: phoneAuthViewController)
  295. navigationController?.present(navPhoneAuthController, animated: true)
  296. }
  297. private func performMfaLoginFlow(resolver: MultiFactorResolver) {
  298. let mfaLoginController = UIHostingController(rootView: MFALoginView(
  299. resolver: resolver,
  300. delegate: self
  301. ))
  302. present(mfaLoginController, animated: true)
  303. }
  304. private func performAnonymousLoginFlow() {
  305. AppManager.shared.auth().signInAnonymously { result, error in
  306. guard error == nil else { return self.displayError(error) }
  307. self.transitionToUserViewController()
  308. }
  309. }
  310. private func performCustomAuthLoginFlow() {
  311. let customAuthController = CustomAuthViewController()
  312. customAuthController.delegate = self
  313. let navCustomAuthController = UINavigationController(rootViewController: customAuthController)
  314. navigationController?.present(navCustomAuthController, animated: true)
  315. }
  316. private func signin(with credential: AuthCredential) {
  317. AppManager.shared.auth().signIn(with: credential) { result, error in
  318. guard error == nil else { return self.displayError(error) }
  319. self.transitionToUserViewController()
  320. }
  321. }
  322. private func performInitRecaptcha() {
  323. Task {
  324. do {
  325. try await AppManager.shared.auth().initializeRecaptchaConfig()
  326. print("Initializing Recaptcha config succeeded.")
  327. } catch {
  328. print("Initializing Recaptcha config failed: \(error).")
  329. }
  330. }
  331. }
  332. private func performCustomAuthDomainFlow() {
  333. showTextInputPrompt(with: "Enter Custom Auth Domain For Auth: ", completion: { newDomain in
  334. AppManager.shared.auth().customAuthDomain = newDomain
  335. })
  336. }
  337. private func getUserTokenResult(force: Bool) {
  338. guard let currentUser = Auth.auth().currentUser else {
  339. print("Error: No user logged in")
  340. return
  341. }
  342. currentUser.getIDTokenResult(forcingRefresh: force, completion: { tokenResult, error in
  343. if error != nil {
  344. print("Error: Error refreshing token")
  345. return // Handle error case, returning early
  346. }
  347. if let tokenResult = tokenResult {
  348. let claims = tokenResult.claims
  349. var message = "Token refresh succeeded\n\n"
  350. for (key, value) in claims {
  351. message += "\(key): \(value)\n"
  352. }
  353. self.displayInfo(title: "Info", message: message, style: .alert)
  354. } else {
  355. print("Error: Unable to access claims.")
  356. }
  357. })
  358. }
  359. private func addAuthStateListener() {
  360. weak var weakSelf = self
  361. let index = authStateDidChangeListeners.count
  362. print("Auth State Did Change Listener #\(index) was added.")
  363. let handle = Auth.auth().addStateDidChangeListener { [weak weakSelf] auth, user in
  364. guard weakSelf != nil else { return }
  365. print("Auth State Did Change Listener #\(index) was invoked on user '\(user?.uid ?? "nil")'")
  366. }
  367. authStateDidChangeListeners.append(handle)
  368. }
  369. private func removeAuthStateListener() {
  370. guard !authStateDidChangeListeners.isEmpty else {
  371. print("No remaining Auth State Did Change Listeners.")
  372. return
  373. }
  374. let index = authStateDidChangeListeners.count - 1
  375. let handle = authStateDidChangeListeners.last!
  376. Auth.auth().removeStateDidChangeListener(handle)
  377. authStateDidChangeListeners.removeLast()
  378. print("Auth State Did Change Listener #\(index) was removed.")
  379. }
  380. private func addIDTokenListener() {
  381. weak var weakSelf = self
  382. let index = IDTokenDidChangeListeners.count
  383. print("ID Token Did Change Listener #\(index) was added.")
  384. let handle = Auth.auth().addIDTokenDidChangeListener { [weak weakSelf] auth, user in
  385. guard weakSelf != nil else { return }
  386. print("ID Token Did Change Listener #\(index) was invoked on user '\(user?.uid ?? "")'.")
  387. }
  388. IDTokenDidChangeListeners.append(handle)
  389. }
  390. private func removeIDTokenListener() {
  391. guard !IDTokenDidChangeListeners.isEmpty else {
  392. print("No remaining ID Token Did Change Listeners.")
  393. return
  394. }
  395. let index = IDTokenDidChangeListeners.count - 1
  396. let handle = IDTokenDidChangeListeners.last!
  397. Auth.auth().removeIDTokenDidChangeListener(handle)
  398. IDTokenDidChangeListeners.removeLast()
  399. print("ID Token Did Change Listener #\(index) was removed.")
  400. }
  401. private func verifyClient() {
  402. AppManager.shared.auth().tokenManager.getTokenInternal { result in
  403. guard case let .success(token) = result else {
  404. print("Verify iOS Client failed.")
  405. return
  406. }
  407. let request = VerifyClientRequest(
  408. withAppToken: token.string,
  409. isSandbox: token.type == .sandbox,
  410. requestConfiguration: AppManager.shared.auth().requestConfiguration
  411. )
  412. Task {
  413. do {
  414. let verifyResponse = try await AppManager.shared.auth().backend.call(with: request)
  415. guard let receipt = verifyResponse.receipt,
  416. let timeoutDate = verifyResponse.suggestedTimeOutDate else {
  417. print("Internal Auth Error: invalid VerifyClientResponse.")
  418. return
  419. }
  420. let timeout = timeoutDate.timeIntervalSinceNow
  421. do {
  422. let credential = await AppManager.shared.auth().appCredentialManager
  423. .didStartVerification(
  424. withReceipt: receipt,
  425. timeout: timeout
  426. )
  427. guard credential.secret != nil else {
  428. print("Failed to receive remote notification to verify App ID.")
  429. return
  430. }
  431. let testPhoneNumber = "+16509964692"
  432. let request = SendVerificationCodeRequest(
  433. phoneNumber: testPhoneNumber,
  434. codeIdentity: CodeIdentity.credential(credential),
  435. requestConfiguration: AppManager.shared.auth().requestConfiguration
  436. )
  437. do {
  438. _ = try await AppManager.shared.auth().backend.call(with: request)
  439. print("Verify iOS client succeeded")
  440. } catch {
  441. print("Verify iOS Client failed: \(error.localizedDescription)")
  442. }
  443. }
  444. } catch {
  445. print("Verify iOS Client failed: \(error.localizedDescription)")
  446. }
  447. }
  448. }
  449. }
  450. private func deleteApp() {
  451. AppManager.shared.app.delete { success in
  452. if success {
  453. print("App deleted successfully.")
  454. } else {
  455. print("Failed to delete app.")
  456. }
  457. }
  458. }
  459. private func toggleActionCodeRequestType(at indexPath: IndexPath) {
  460. switch actionCodeRequestType {
  461. case .inApp:
  462. actionCodeRequestType = .continue
  463. case .continue:
  464. actionCodeRequestType = .email
  465. case .email:
  466. actionCodeRequestType = .inApp
  467. }
  468. dataSourceProvider.updateItem(
  469. at: indexPath,
  470. item: Item(title: AuthMenu.actionType.name, detailTitle: actionCodeRequestType.name)
  471. )
  472. tableView.reloadData()
  473. }
  474. private func changeActionCodeContinueURL(at indexPath: IndexPath) {
  475. showTextInputPrompt(with: "Continue URL:", completion: { newContinueURL in
  476. self.actionCodeContinueURL = URL(string: newContinueURL)
  477. print("Successfully set Continue URL to: \(newContinueURL)")
  478. self.dataSourceProvider.updateItem(
  479. at: indexPath,
  480. item: Item(
  481. title: AuthMenu.continueURL.name,
  482. detailTitle: self.actionCodeContinueURL?.absoluteString,
  483. isEditable: true
  484. )
  485. )
  486. self.tableView.reloadData()
  487. })
  488. }
  489. private func changeActionCodeLinkDomain(at indexPath: IndexPath) {
  490. showTextInputPrompt(with: "Link Domain:", completion: { newLinkDomain in
  491. self.actionCodeLinkDomain = newLinkDomain
  492. print("Successfully set Link Domain to: \(newLinkDomain)")
  493. self.dataSourceProvider.updateItem(
  494. at: indexPath,
  495. item: Item(
  496. title: AuthMenu.linkDomain.name,
  497. detailTitle: self.actionCodeLinkDomain,
  498. isEditable: true
  499. )
  500. )
  501. self.tableView.reloadData()
  502. })
  503. }
  504. private func requestVerifyEmail() {
  505. showSpinner()
  506. let completionHandler: ((any Error)?) -> Void = { [weak self] error in
  507. guard let self = self else { return }
  508. self.hideSpinner()
  509. if let error = error {
  510. let errorMessage = "Error sending verification email: \(error.localizedDescription)"
  511. showAlert(for: errorMessage)
  512. print(errorMessage)
  513. } else {
  514. let successMessage = "Verification email sent successfully!"
  515. showAlert(for: successMessage)
  516. print(successMessage)
  517. }
  518. }
  519. if actionCodeRequestType == .email {
  520. AppManager.shared.auth().currentUser?.sendEmailVerification(completion: completionHandler)
  521. } else {
  522. if actionCodeContinueURL == nil {
  523. print("Error: Action code continue URL is nil.")
  524. return
  525. }
  526. AppManager.shared.auth().currentUser?.sendEmailVerification(
  527. with: actionCodeSettings(),
  528. completion: completionHandler
  529. )
  530. }
  531. }
  532. func requestPasswordReset() {
  533. showTextInputPrompt(with: "Email:", completion: { email in
  534. print("Sending password reset link to: \(email)")
  535. self.showSpinner()
  536. let completionHandler: ((any Error)?) -> Void = { [weak self] error in
  537. guard let self = self else { return }
  538. self.hideSpinner()
  539. if let error = error {
  540. print("Request password reset failed: \(error)")
  541. showAlert(for: error.localizedDescription)
  542. return
  543. }
  544. print("Request password reset succeeded.")
  545. showAlert(for: "Sent!")
  546. }
  547. if self.actionCodeRequestType == .email {
  548. AppManager.shared.auth().sendPasswordReset(withEmail: email, completion: completionHandler)
  549. } else {
  550. guard self.actionCodeContinueURL != nil else {
  551. print("Error: Action code continue URL is nil.")
  552. return
  553. }
  554. AppManager.shared.auth().sendPasswordReset(
  555. withEmail: email,
  556. actionCodeSettings: self.actionCodeSettings(),
  557. completion: completionHandler
  558. )
  559. }
  560. })
  561. }
  562. private func resetPassword() {
  563. showSpinner()
  564. let completionHandler: ((any Error)?) -> Void = { [weak self] error in
  565. guard let self = self else { return }
  566. self.hideSpinner()
  567. if let error = error {
  568. print("Password reset failed \(error)")
  569. showAlert(for: error.localizedDescription)
  570. return
  571. }
  572. print("Password reset succeeded")
  573. showAlert(for: "Password reset succeeded!")
  574. }
  575. showTextInputPrompt(with: "OOB Code:") {
  576. code in
  577. self.showTextInputPrompt(with: "New Password") {
  578. password in
  579. AppManager.shared.auth().confirmPasswordReset(
  580. withCode: code,
  581. newPassword: password,
  582. completion: completionHandler
  583. )
  584. }
  585. }
  586. }
  587. private func nameForActionCodeOperation(_ operation: ActionCodeOperation) -> String {
  588. switch operation {
  589. case .verifyEmail:
  590. return "Verify Email"
  591. case .recoverEmail:
  592. return "Recover Email"
  593. case .passwordReset:
  594. return "Password Reset"
  595. case .emailLink:
  596. return "Email Sign-In Link"
  597. case .verifyAndChangeEmail:
  598. return "Verify Before Change Email"
  599. case .revertSecondFactorAddition:
  600. return "Revert Second Factor Addition"
  601. case .unknown:
  602. return "Unknown action"
  603. }
  604. }
  605. private func checkActionCode() {
  606. showSpinner()
  607. let completionHandler: (ActionCodeInfo?, (any Error)?) -> Void = { [weak self] info, error in
  608. guard let self = self else { return }
  609. self.hideSpinner()
  610. if let error = error {
  611. print("Check action code failed: \(error)")
  612. showAlert(for: error.localizedDescription)
  613. return
  614. }
  615. guard let info = info else { return }
  616. print("Check action code succeeded")
  617. let email = info.email
  618. let previousEmail = info.previousEmail
  619. let operation = self.nameForActionCodeOperation(info.operation)
  620. showAlert(for: operation, message: previousEmail ?? email)
  621. }
  622. showTextInputPrompt(with: "OOB Code:") {
  623. oobCode in
  624. AppManager.shared.auth().checkActionCode(oobCode, completion: completionHandler)
  625. }
  626. }
  627. private func applyActionCode() {
  628. showSpinner()
  629. let completionHandler: ((any Error)?) -> Void = { [weak self] error in
  630. guard let self = self else { return }
  631. self.hideSpinner()
  632. if let error = error {
  633. print("Apply action code failed \(error)")
  634. showAlert(for: error.localizedDescription)
  635. return
  636. }
  637. print("Apply action code succeeded")
  638. showAlert(for: "Action code was properly applied")
  639. }
  640. showTextInputPrompt(with: "OOB Code: ") {
  641. oobCode in
  642. AppManager.shared.auth().applyActionCode(oobCode, completion: completionHandler)
  643. }
  644. }
  645. private func verifyPasswordResetCode() {
  646. showSpinner()
  647. let completionHandler: (String?, (any Error)?) -> Void = { [weak self] email, error in
  648. guard let self = self else { return }
  649. self.hideSpinner()
  650. if let error = error {
  651. print("Verify password reset code failed \(error)")
  652. showAlert(for: error.localizedDescription)
  653. return
  654. }
  655. print("Verify password resest code succeeded.")
  656. showAlert(for: "Code verified for email: \(email ?? "missing email")")
  657. }
  658. showTextInputPrompt(with: "OOB Code: ") {
  659. oobCode in
  660. AppManager.shared.auth().verifyPasswordResetCode(oobCode, completion: completionHandler)
  661. }
  662. }
  663. private func phoneEnroll() {
  664. guard let user = AppManager.shared.auth().currentUser else {
  665. showAlert(for: "No user logged in!")
  666. print("Error: User must be logged in first.")
  667. return
  668. }
  669. showTextInputPrompt(with: "Phone Number:") { phoneNumber in
  670. user.multiFactor.getSessionWithCompletion { session, error in
  671. guard let session = session else { return }
  672. guard error == nil else {
  673. self.showAlert(for: "Enrollment failed")
  674. print("Multi factor start enroll failed. Error: \(error!)")
  675. return
  676. }
  677. PhoneAuthProvider.provider()
  678. .verifyPhoneNumber(phoneNumber, multiFactorSession: session) { verificationID, error in
  679. guard error == nil else {
  680. self.showAlert(for: "Enrollment failed")
  681. print("Multi factor start enroll failed. Error: \(error!)")
  682. return
  683. }
  684. self.showTextInputPrompt(with: "Verification Code: ") { verificationCode in
  685. let credential = PhoneAuthProvider.provider().credential(
  686. withVerificationID: verificationID!,
  687. verificationCode: verificationCode
  688. )
  689. let assertion = PhoneMultiFactorGenerator.assertion(with: credential)
  690. self.showTextInputPrompt(with: "Display Name:") { displayName in
  691. user.multiFactor.enroll(with: assertion, displayName: displayName) { error in
  692. if let error = error {
  693. self.showAlert(for: "Enrollment failed")
  694. print("Multi factor finalize enroll failed. Error: \(error)")
  695. } else {
  696. self.showAlert(for: "Successfully enrolled: \(displayName)")
  697. print("Multi factor finalize enroll succeeded.")
  698. }
  699. }
  700. }
  701. }
  702. }
  703. }
  704. }
  705. }
  706. private func totpEnroll() async {
  707. guard
  708. let user = AppManager.shared.auth().currentUser,
  709. let accountName = user.email
  710. else {
  711. showAlert(for: "Enrollment failed: User must be logged and have email address.")
  712. return
  713. }
  714. guard let issuer = AppManager.shared.auth().app?.name else {
  715. showAlert(for: "Enrollment failed: Firebase app is missing name.")
  716. return
  717. }
  718. do {
  719. let session = try await user.multiFactor.session()
  720. let secret = try await TOTPMultiFactorGenerator.generateSecret(with: session)
  721. print("Secret: " + secret.sharedSecretKey())
  722. let url = secret.generateQRCodeURL(withAccountName: accountName, issuer: issuer)
  723. guard !url.isEmpty else {
  724. showAlert(for: "Enrollment failed")
  725. print("Multi factor finalize enroll failed. Could not generate URL.")
  726. return
  727. }
  728. secret.openInOTPApp(withQRCodeURL: url)
  729. guard
  730. let oneTimePassword = await showTextInputPrompt(with: "Enter the one time passcode.")
  731. else {
  732. showAlert(for: "Enrollment failed: one time passcode not entered.")
  733. return
  734. }
  735. let assertion = TOTPMultiFactorGenerator.assertionForEnrollment(
  736. with: secret,
  737. oneTimePassword: oneTimePassword
  738. )
  739. // TODO(nickcooke): Provide option to enter display name.
  740. try await user.multiFactor.enroll(with: assertion, displayName: "TOTP")
  741. showAlert(for: "Successfully enrolled: TOTP")
  742. print("Multi factor finalize enroll succeeded.")
  743. } catch {
  744. print(error)
  745. showAlert(for: "Enrollment failed: \(error.localizedDescription)")
  746. }
  747. }
  748. func mfaUnenroll() {
  749. var displayNames: [String] = []
  750. guard let currentUser = Auth.auth().currentUser else {
  751. print("Error: No current user")
  752. return
  753. }
  754. for factorInfo in currentUser.multiFactor.enrolledFactors {
  755. if let displayName = factorInfo.displayName {
  756. displayNames.append(displayName)
  757. }
  758. }
  759. let alertController = UIAlertController(
  760. title: "Select Multi Factor to Unenroll",
  761. message: nil,
  762. preferredStyle: .actionSheet
  763. )
  764. for displayName in displayNames {
  765. let action = UIAlertAction(title: displayName, style: .default) { _ in
  766. self.unenrollFactor(with: displayName)
  767. }
  768. alertController.addAction(action)
  769. }
  770. let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
  771. alertController.addAction(cancelAction)
  772. present(alertController, animated: true, completion: nil)
  773. }
  774. private func unenrollFactor(with displayName: String) {
  775. guard let currentUser = Auth.auth().currentUser else {
  776. showAlert(for: "User must be logged in")
  777. print("Error: No current user")
  778. return
  779. }
  780. var factorInfoToUnenroll: MultiFactorInfo?
  781. for factorInfo in currentUser.multiFactor.enrolledFactors {
  782. if factorInfo.displayName == displayName {
  783. factorInfoToUnenroll = factorInfo
  784. break
  785. }
  786. }
  787. if let factorInfo = factorInfoToUnenroll {
  788. currentUser.multiFactor.unenroll(withFactorUID: factorInfo.uid) { error in
  789. if let error = error {
  790. self.showAlert(for: "Failed to unenroll factor: \(displayName)")
  791. print("Multi factor unenroll failed. Error: \(error.localizedDescription)")
  792. } else {
  793. self.showAlert(for: "Successfully unenrolled: \(displayName)")
  794. print("Multi factor unenroll succeeded.")
  795. }
  796. }
  797. }
  798. }
  799. // MARK: - Private Helpers
  800. private func showTextInputPrompt(with message: String, completion: ((String) -> Void)? = nil) {
  801. let editController = UIAlertController(
  802. title: message,
  803. message: nil,
  804. preferredStyle: .alert
  805. )
  806. editController.addTextField()
  807. let saveHandler: (UIAlertAction) -> Void = { _ in
  808. let text = editController.textFields?.first?.text ?? ""
  809. if let completion {
  810. completion(text)
  811. }
  812. }
  813. let cancelHandler: (UIAlertAction) -> Void = { _ in
  814. if let completion {
  815. completion("")
  816. }
  817. }
  818. editController.addAction(UIAlertAction(title: "Save", style: .default, handler: saveHandler))
  819. editController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: cancelHandler))
  820. // Assuming `self` is a view controller
  821. present(editController, animated: true, completion: nil)
  822. }
  823. private func showTextInputPrompt(with message: String) async -> String? {
  824. await withCheckedContinuation { continuation in
  825. showTextInputPrompt(with: message) { inputText in
  826. continuation.resume(returning: inputText.isEmpty ? nil : inputText)
  827. }
  828. }
  829. }
  830. // Function to generate QR code from a string
  831. private func generateQRCode(from string: String) -> UIImage? {
  832. let data = string.data(using: String.Encoding.ascii)
  833. if let filter = CIFilter(name: "CIQRCodeGenerator") {
  834. filter.setValue(data, forKey: "inputMessage")
  835. let transform = CGAffineTransform(scaleX: 10, y: 10)
  836. if let output = filter.outputImage?.transformed(by: transform) {
  837. return UIImage(ciImage: output)
  838. }
  839. }
  840. return nil
  841. }
  842. func showAlert(for title: String, message: String? = nil) {
  843. let alertController = UIAlertController(
  844. title: message,
  845. message: nil,
  846. preferredStyle: .alert
  847. )
  848. alertController.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default))
  849. }
  850. private func configureDataSourceProvider() {
  851. dataSourceProvider = DataSourceProvider(
  852. dataSource: AuthMenuData.sections,
  853. tableView: tableView
  854. )
  855. dataSourceProvider.delegate = self
  856. }
  857. private func configureNavigationBar() {
  858. navigationItem.title = "Firebase Auth"
  859. guard let navigationBar = navigationController?.navigationBar else { return }
  860. navigationBar.prefersLargeTitles = true
  861. navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  862. navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  863. }
  864. private func transitionToUserViewController() {
  865. // UserViewController is at index 1 in the tabBarController.viewControllers array
  866. tabBarController?.transitionToViewController(atIndex: 1)
  867. }
  868. }
  869. // MARK: - LoginDelegate
  870. extension AuthViewController: LoginDelegate {
  871. public func loginDidOccur(resolver: MultiFactorResolver?) {
  872. if let resolver {
  873. performMfaLoginFlow(resolver: resolver)
  874. } else {
  875. transitionToUserViewController()
  876. }
  877. }
  878. }
  879. // MARK: - Implementing Sign in with Apple with Firebase
  880. extension AuthViewController: ASAuthorizationControllerDelegate,
  881. ASAuthorizationControllerPresentationContextProviding {
  882. // MARK: ASAuthorizationControllerDelegate
  883. func authorizationController(controller: ASAuthorizationController,
  884. didCompleteWithAuthorization authorization: ASAuthorization) {
  885. guard let appleIDCredential = authorization.credential as? ASAuthorizationAppleIDCredential
  886. else {
  887. print("Unable to retrieve AppleIDCredential")
  888. return
  889. }
  890. guard let nonce = currentNonce else {
  891. fatalError("Invalid state: A login callback was received, but no login request was sent.")
  892. }
  893. guard let appleIDToken = appleIDCredential.identityToken else {
  894. print("Unable to fetch identity token")
  895. return
  896. }
  897. guard let appleAuthCode = appleIDCredential.authorizationCode else {
  898. print("Unable to fetch authorization code")
  899. return
  900. }
  901. guard let idTokenString = String(data: appleIDToken, encoding: .utf8) else {
  902. print("Unable to serialize token string from data: \(appleIDToken.debugDescription)")
  903. return
  904. }
  905. guard let _ = String(data: appleAuthCode, encoding: .utf8) else {
  906. print("Unable to serialize auth code string from data: \(appleAuthCode.debugDescription)")
  907. return
  908. }
  909. // use this call to create the authentication credential and set the user's full name
  910. let credential = OAuthProvider.appleCredential(withIDToken: idTokenString,
  911. rawNonce: nonce,
  912. fullName: appleIDCredential.fullName)
  913. AppManager.shared.auth().signIn(with: credential) { result, error in
  914. // Error. If error.code == .MissingOrInvalidNonce, make sure
  915. // you're sending the SHA256-hashed nonce as a hex string with
  916. // your request to Apple.
  917. guard error == nil else { return self.displayError(error) }
  918. // At this point, our user is signed in
  919. // so we advance to the User View Controller
  920. self.transitionToUserViewController()
  921. }
  922. }
  923. func authorizationController(controller: ASAuthorizationController,
  924. didCompleteWithError error: any Error) {
  925. // Ensure that you have:
  926. // - enabled `Sign in with Apple` on the Firebase console
  927. // - added the `Sign in with Apple` capability for this project
  928. print("Sign in with Apple failed: \(error)")
  929. }
  930. // MARK: ASAuthorizationControllerPresentationContextProviding
  931. func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
  932. return view.window!
  933. }
  934. /// Orchestrates the UI flow to demonstrate the OIDC token exchange feature.
  935. ///
  936. /// This function sequentially prompts the user for the necessary inputs (idpConfigID and custom
  937. /// token) using async/await with UIAlerts. If both inputs are provided,
  938. /// it calls the Auth.exchangeToken API and displays the result to the user.
  939. private func callExchangeToken() {
  940. Task {
  941. do {
  942. // 1. Prompt for the IDP Config ID and await user input.
  943. guard let idpConfigId = await showTextInputPrompt(with: "Enter IDP Config ID:") else {
  944. print("Token exchange cancelled: IDP Config ID was not provided.")
  945. // Present an alert on the main thread to indicate cancellation.
  946. DispatchQueue.main.async {
  947. let alert = UIAlertController(title: "Cancelled",
  948. message: "An IDP Config ID is required to proceed.",
  949. preferredStyle: .alert)
  950. alert.addAction(UIAlertAction(title: "OK", style: .default))
  951. self.present(alert, animated: true)
  952. }
  953. return
  954. }
  955. // 2. Prompt for the custom OIDC token and await user input.
  956. guard let idToken = await showTextInputPrompt(with: "Enter OIDC Token:") else {
  957. print("Token exchange cancelled: OIDC Token was not provided.")
  958. // Present an alert on the main thread to indicate cancellation.
  959. DispatchQueue.main.async {
  960. let alert = UIAlertController(title: "Cancelled",
  961. message: "An OIDC Token is required to proceed.",
  962. preferredStyle: .alert)
  963. alert.addAction(UIAlertAction(title: "OK", style: .default))
  964. self.present(alert, animated: true)
  965. }
  966. return
  967. }
  968. // 3. With both inputs, call the exchangeToken API.
  969. // The `auth()` instance is pre-configured with a regional tenant in AppManager.
  970. print("Attempting to exchange token...")
  971. let result = try await AppManager.shared.auth().exchangeToken(
  972. idToken: idToken,
  973. idpConfigId: idpConfigId,
  974. useStaging: true
  975. )
  976. // 4. Handle the success case by presenting an alert on the main thread.
  977. print("Token exchange successful. Access Token: \(result.token)")
  978. DispatchQueue.main.async {
  979. let fullToken = result.token
  980. let truncatedToken = self.truncateString(fullToken, maxLength: 20)
  981. let message = "Firebase Access Token:\n\(truncatedToken)"
  982. let alert = UIAlertController(
  983. title: "Token Exchange Succeeded",
  984. message: message,
  985. preferredStyle: .alert
  986. )
  987. // Action to copy the token
  988. let copyAction = UIAlertAction(title: "Copy Token", style: .default) { _ in
  989. UIPasteboard.general.string = fullToken
  990. // Show a brief confirmation
  991. self.showCopyConfirmation()
  992. }
  993. alert.addAction(copyAction)
  994. alert.addAction(UIAlertAction(title: "OK", style: .default))
  995. self.present(alert, animated: true)
  996. }
  997. } catch {
  998. // 5. Handle any errors during the process by presenting an alert on the main thread.
  999. print("Failed to exchange token: \(error)")
  1000. DispatchQueue.main.async {
  1001. let alert = UIAlertController(
  1002. title: "Token Exchange Error",
  1003. message: error.localizedDescription,
  1004. preferredStyle: .alert
  1005. )
  1006. alert.addAction(UIAlertAction(title: "OK", style: .default))
  1007. self.present(alert, animated: true)
  1008. }
  1009. }
  1010. }
  1011. }
  1012. // Helper function to truncate strings
  1013. private func truncateString(_ string: String, maxLength: Int) -> String {
  1014. if string.count > maxLength {
  1015. return String(string.prefix(maxLength)) + "..."
  1016. } else {
  1017. return string
  1018. }
  1019. }
  1020. // Helper function to show copy confirmation
  1021. private func showCopyConfirmation() {
  1022. let confirmationAlert = UIAlertController(
  1023. title: "Copied!",
  1024. message: "Token copied to clipboard.",
  1025. preferredStyle: .alert
  1026. )
  1027. present(confirmationAlert, animated: true)
  1028. // Automatically dismiss the confirmation after a short delay
  1029. DispatchQueue.main.asyncAfter(deadline: .now() + 1.5) {
  1030. confirmationAlert.dismiss(animated: true, completion: nil)
  1031. }
  1032. }
  1033. }