SettingsViewController.swift 10 KB

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