SettingsViewController.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // Copyright 2023 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. @testable import FirebaseAuth
  15. import FirebaseCore
  16. import UIKit
  17. /// Namespace for performable actions on a Auth Settings view
  18. enum SettingsAction: String {
  19. case toggleIdentityTokenAPI = "Identity Toolkit"
  20. case toggleSecureTokenAPI = "Secure Token"
  21. case toggleActiveApp = "Active App"
  22. case toggleAccessGroup = "Current Access Group"
  23. case setAuthLanugage = "Auth Language"
  24. case useAppLanguage = "Use App Language"
  25. case togglePhoneAppVerification = "Disable App Verification (Phone)"
  26. }
  27. class SettingsViewController: UIViewController, DataSourceProviderDelegate {
  28. var dataSourceProvider: DataSourceProvider<AuthSettings>!
  29. var tableView: UITableView { view as! UITableView }
  30. private var _settings: AuthSettings?
  31. var settings: AuthSettings? {
  32. get { AppManager.shared.auth().settings }
  33. set { _settings = newValue }
  34. }
  35. // MARK: - UIViewController Life Cycle
  36. override func loadView() {
  37. view = UITableView(frame: .zero, style: .insetGrouped)
  38. }
  39. override func viewDidLoad() {
  40. super.viewDidLoad()
  41. configureNavigationBar()
  42. }
  43. override func viewWillAppear(_ animated: Bool) {
  44. super.viewWillAppear(animated)
  45. configureDataSourceProvider()
  46. }
  47. // MARK: - DataSourceProviderDelegate
  48. func didSelectRowAt(_ indexPath: IndexPath, on tableView: UITableView) {
  49. let item = dataSourceProvider.item(at: indexPath)
  50. guard let actionName = item.detailTitle,
  51. let action = SettingsAction(rawValue: actionName) else {
  52. // The row tapped has no affiliated action.
  53. return
  54. }
  55. let auth = AppManager.shared.auth()
  56. switch action {
  57. case .toggleSecureTokenAPI:
  58. toggleSecureTokenAPI()
  59. case .toggleIdentityTokenAPI:
  60. toggleIdentityTokenAPI()
  61. case .toggleActiveApp:
  62. AppManager.shared.toggle()
  63. case .toggleAccessGroup:
  64. toggleAccessGroup()
  65. case .setAuthLanugage:
  66. setAuthLanguage()
  67. case .useAppLanguage:
  68. auth.useAppLanguage()
  69. case .togglePhoneAppVerification:
  70. guard let settings = auth.settings else {
  71. fatalError("Unset auth.settings")
  72. }
  73. settings.isAppVerificationDisabledForTesting = !settings.isAppVerificationDisabledForTesting
  74. }
  75. updateUI()
  76. }
  77. // MARK: - Firebase 🔥
  78. private func toggleIdentityTokenAPI() {
  79. if IdentityToolkitRequest.host == "www.googleapis.com" {
  80. IdentityToolkitRequest.setHost("staging-www.sandbox.googleapis.com")
  81. } else {
  82. IdentityToolkitRequest.setHost("www.googleapis.com")
  83. }
  84. }
  85. private func toggleSecureTokenAPI() {
  86. if SecureTokenRequest.host == "securetoken.googleapis.com" {
  87. SecureTokenRequest.setHost("staging-securetoken.sandbox.googleapis.com")
  88. } else {
  89. SecureTokenRequest.setHost("securetoken.googleapis.com")
  90. }
  91. }
  92. private func toggleAccessGroup() {
  93. if AppManager.shared.auth().userAccessGroup == nil {
  94. guard let bundleDictionary = Bundle.main.infoDictionary,
  95. let group = bundleDictionary["AppIdentifierPrefix"] as? String else {
  96. fatalError("Configure AppIdentifierPrefix in the plist")
  97. }
  98. AppManager.shared.auth().userAccessGroup = group + "com.google.firebase.auth.keychainGroup1"
  99. } else {
  100. AppManager.shared.auth().userAccessGroup = nil
  101. }
  102. }
  103. private func setAuthLanguage() {
  104. let prompt = UIAlertController(title: nil, message: "Enter Language Code For Auth:",
  105. preferredStyle: .alert)
  106. prompt.addTextField()
  107. let okAction = UIAlertAction(title: "OK", style: .default) { action in
  108. AppManager.shared.auth().languageCode = prompt.textFields?[0].text ?? ""
  109. self.updateUI()
  110. }
  111. prompt.addAction(okAction)
  112. present(prompt, animated: true)
  113. }
  114. // MARK: - Private Helpers
  115. private func configureNavigationBar() {
  116. navigationItem.title = "Settings"
  117. guard let navigationBar = navigationController?.navigationBar else { return }
  118. navigationBar.prefersLargeTitles = true
  119. navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  120. navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  121. }
  122. private func configureDataSourceProvider() {
  123. dataSourceProvider = DataSourceProvider(
  124. dataSource: settings?.sections,
  125. emptyStateView: SignedOutView(),
  126. tableView: tableView
  127. )
  128. dataSourceProvider.delegate = self
  129. }
  130. private func updateUI() {
  131. configureDataSourceProvider()
  132. animateUpdates(for: tableView)
  133. }
  134. private func animateUpdates(for tableView: UITableView) {
  135. UIView.transition(with: tableView, duration: 0.2,
  136. options: .transitionCrossDissolve,
  137. animations: { tableView.reloadData() })
  138. }
  139. }
  140. // MARK: - Extending a `AuthSettings` to conform to `DataSourceProvidable`
  141. extension AuthSettings: DataSourceProvidable {
  142. private var versionSection: Section {
  143. let items = [Item(title: FirebaseVersion(), detailTitle: "FirebaseAuth")]
  144. return Section(headerDescription: "Versions", items: items)
  145. }
  146. private var apiHostSection: Section {
  147. let items = [Item(title: IdentityToolkitRequest.host, detailTitle: "Identity Toolkit"),
  148. Item(title: SecureTokenRequest.host, detailTitle: "Secure Token")]
  149. return Section(headerDescription: "API Hosts", items: items)
  150. }
  151. private var appsSection: Section {
  152. let items = [Item(title: AppManager.shared.app.options.projectID, detailTitle: "Active App")]
  153. return Section(headerDescription: "Firebase Apps", items: items)
  154. }
  155. private var keychainSection: Section {
  156. let items = [Item(title: AppManager.shared.auth().userAccessGroup ?? "[none]",
  157. detailTitle: "Current Access Group")]
  158. return Section(headerDescription: "Keychain Access Groups", items: items)
  159. }
  160. func truncatedString(string: String, length: Int) -> String {
  161. guard string.count > length else { return string }
  162. let half = (length - 3) / 2
  163. let startIndex = string.startIndex
  164. let midIndex = string.index(startIndex, offsetBy: half) // Ensure correct mid index
  165. let endIndex = string.index(startIndex, offsetBy: string.count - half)
  166. return "\(string[startIndex ..< midIndex])...\(string[endIndex...])"
  167. }
  168. func showPromptWithTitle(_ title: String, message: String, showCancelButton: Bool,
  169. completion: @escaping (Bool, String?) -> Void) {
  170. let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
  171. alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in
  172. let userInput = alertController.textFields?.first?.text
  173. completion(true, userInput)
  174. }))
  175. if showCancelButton {
  176. alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in
  177. completion(false, nil)
  178. }))
  179. }
  180. alertController.addTextField(configurationHandler: nil)
  181. // Present the alert controller
  182. // Make sure to present it from a view controller
  183. // For example, if this code is inside a UIViewController, you can use
  184. // `self.present(alertController, animated: true, completion: nil)`
  185. }
  186. // TODO: Add ability to click and clear both of these fields.
  187. private var phoneAuthSection: Section {
  188. let items = [Item(title: APNSTokenString(), detailTitle: "APNs Token"),
  189. Item(title: appCredentialString(), detailTitle: "App Credential")]
  190. return Section(headerDescription: "Phone Auth - TODO toggle off", items: items)
  191. }
  192. func APNSTokenString() -> String {
  193. guard let token = AppManager.shared.auth().tokenManager.token else {
  194. return "No APNs token"
  195. }
  196. let truncatedToken = truncatedString(string: token.string, length: 19)
  197. let tokenType = token.type == .prod ? "P" : "S"
  198. return "\(truncatedToken)(\(tokenType))"
  199. }
  200. func clearAPNSToken() {
  201. guard let token = AppManager.shared.auth().tokenManager.token else {
  202. return
  203. }
  204. let tokenType = token.type == .prod ? "Production" : "Sandbox"
  205. let message = "token: \(token.string)\ntype: \(tokenType)"
  206. showPromptWithTitle("Clear APNs Token?", message: message,
  207. showCancelButton: true) { userPressedOK, userInput in
  208. if userPressedOK {
  209. AppManager.shared.auth().tokenManager.token = nil
  210. }
  211. }
  212. }
  213. func appCredentialString() -> String {
  214. if let credential = AppManager.shared.auth().appCredentialManager.credential {
  215. let truncatedReceipt = truncatedString(string: credential.receipt, length: 13)
  216. let truncatedSecret = truncatedString(string: credential.secret ?? "", length: 13)
  217. return "\(truncatedReceipt)/\(truncatedSecret)"
  218. } else {
  219. return "No App Credential"
  220. }
  221. }
  222. func clearAppCredential() {
  223. if let credential = AppManager.shared.auth().appCredentialManager.credential {
  224. let message = "receipt: \(credential.receipt)\nsecret: \(credential.secret)"
  225. showPromptWithTitle("Clear App Credential?", message: message,
  226. showCancelButton: true) { userPressedOK, _ in
  227. if userPressedOK {
  228. AppManager.shared.auth().appCredentialManager.clearCredential()
  229. }
  230. }
  231. }
  232. }
  233. private var languageSection: Section {
  234. let languageCode = AppManager.shared.auth().languageCode
  235. let items = [Item(title: languageCode ?? "[none]", detailTitle: "Auth Language"),
  236. Item(title: "Click to Use App Language", detailTitle: "Use App Language")]
  237. return Section(headerDescription: "Language", items: items)
  238. }
  239. private var disableSection: Section {
  240. guard let settings = AppManager.shared.auth().settings else {
  241. fatalError("Missing auth settings")
  242. }
  243. let disabling = settings.isAppVerificationDisabledForTesting ? "YES" : "NO"
  244. let items = [Item(title: disabling, detailTitle: "Disable App Verification (Phone)")]
  245. return Section(headerDescription: "Auth Settings", items: items)
  246. }
  247. var sections: [Section] {
  248. [
  249. versionSection,
  250. apiHostSection,
  251. appsSection,
  252. keychainSection,
  253. phoneAuthSection,
  254. languageSection,
  255. disableSection,
  256. ]
  257. }
  258. }