SettingsViewController.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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 setAuthLanguage = "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 .setAuthLanguage:
  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. do {
  100. if AppManager.shared.auth().userAccessGroup == nil {
  101. guard let bundleDictionary = Bundle.main.infoDictionary,
  102. let group = bundleDictionary["AppIdentifierPrefix"] as? String else {
  103. fatalError("Configure AppIdentifierPrefix in the plist")
  104. }
  105. try AppManager.shared.auth().useUserAccessGroup(group +
  106. "com.google.firebase.auth.keychainGroup1")
  107. } else {
  108. try AppManager.shared.auth().useUserAccessGroup(nil)
  109. }
  110. } catch {
  111. fatalError("Failed to set userAccessGroup with error \(error)")
  112. }
  113. }
  114. func clearAPNSToken() {
  115. guard let token = AppManager.shared.auth().tokenManager.token else {
  116. return
  117. }
  118. let tokenType = token.type == .prod ? "Production" : "Sandbox"
  119. let message = "token: \(token.string)\ntype: \(tokenType)"
  120. let prompt = UIAlertController(title: "Clear APNs Token?", message: message,
  121. preferredStyle: .alert)
  122. let okAction = UIAlertAction(title: "OK", style: .default) { action in
  123. AppManager.shared.auth().tokenManager.token = nil
  124. self.updateUI()
  125. }
  126. prompt.addAction(okAction)
  127. present(prompt, animated: true)
  128. }
  129. func clearAppCredential() {
  130. if let credential = AppManager.shared.auth().appCredentialManager.credential {
  131. let message = "receipt:\(credential.receipt) secret:\(credential.secret ?? "nil")"
  132. let prompt = UIAlertController(title: "Clear App Credential", message: message,
  133. preferredStyle: .alert)
  134. let okAction = UIAlertAction(title: "OK", style: .default) { action in
  135. AppManager.shared.auth().appCredentialManager.clearCredential()
  136. self.updateUI()
  137. }
  138. prompt.addAction(okAction)
  139. present(prompt, animated: true)
  140. }
  141. }
  142. private func setAuthLanguage() {
  143. let prompt = UIAlertController(title: nil, message: "Enter Language Code For Auth:",
  144. preferredStyle: .alert)
  145. prompt.addTextField()
  146. let okAction = UIAlertAction(title: "OK", style: .default) { action in
  147. AppManager.shared.auth().languageCode = prompt.textFields?[0].text ?? ""
  148. self.updateUI()
  149. }
  150. prompt.addAction(okAction)
  151. present(prompt, animated: true)
  152. }
  153. // MARK: - Private Helpers
  154. private func configureNavigationBar() {
  155. navigationItem.title = "Settings"
  156. guard let navigationBar = navigationController?.navigationBar else { return }
  157. navigationBar.prefersLargeTitles = true
  158. navigationBar.titleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  159. navigationBar.largeTitleTextAttributes = [.foregroundColor: UIColor.systemOrange]
  160. }
  161. private func configureDataSourceProvider() {
  162. dataSourceProvider = DataSourceProvider(
  163. dataSource: settings?.sections,
  164. emptyStateView: SignedOutView(),
  165. tableView: tableView
  166. )
  167. dataSourceProvider.delegate = self
  168. }
  169. private func updateUI() {
  170. configureDataSourceProvider()
  171. animateUpdates(for: tableView)
  172. }
  173. private func animateUpdates(for tableView: UITableView) {
  174. UIView.transition(with: tableView, duration: 0.2,
  175. options: .transitionCrossDissolve,
  176. animations: { tableView.reloadData() })
  177. }
  178. }
  179. // MARK: - Extending a `AuthSettings` to conform to `DataSourceProvidable`
  180. extension AuthSettings: DataSourceProvidable {
  181. private var versionSection: Section {
  182. let items = [Item(title: FirebaseVersion(), detailTitle: "FirebaseAuth")]
  183. return Section(headerDescription: "Versions", items: items)
  184. }
  185. private var apiHostSection: Section {
  186. let items = [Item(title: IdentityToolkitRequest.host, detailTitle: "Identity Toolkit"),
  187. Item(title: SecureTokenRequest.host, detailTitle: "Secure Token")]
  188. return Section(headerDescription: "API Hosts", items: items)
  189. }
  190. private var appsSection: Section {
  191. let items = [Item(title: AppManager.shared.app.options.projectID, detailTitle: "Active App")]
  192. return Section(headerDescription: "Firebase Apps", items: items)
  193. }
  194. private var keychainSection: Section {
  195. let items = [Item(title: AppManager.shared.auth().userAccessGroup ?? "[none]",
  196. detailTitle: "Current Access Group")]
  197. return Section(headerDescription: "Keychain Access Groups", items: items)
  198. }
  199. func truncatedString(string: String, length: Int) -> String {
  200. guard string.count > length else { return string }
  201. let half = (length - 3) / 2
  202. let startIndex = string.startIndex
  203. let midIndex = string.index(startIndex, offsetBy: half) // Ensure correct mid index
  204. let endIndex = string.index(startIndex, offsetBy: string.count - half)
  205. return "\(string[startIndex ..< midIndex])...\(string[endIndex...])"
  206. }
  207. // TODO: Add ability to click and clear both of these fields.
  208. private var phoneAuthSection: Section {
  209. let items = [Item(title: APNSTokenString(), detailTitle: "APNs Token"),
  210. Item(title: appCredentialString(), detailTitle: "App Credential")]
  211. return Section(headerDescription: "Phone Auth", items: items)
  212. }
  213. func APNSTokenString() -> String {
  214. guard let token = AppManager.shared.auth().tokenManager.token else {
  215. return "No APNs token"
  216. }
  217. let truncatedToken = truncatedString(string: token.string, length: 19)
  218. let tokenType = token.type == .prod ? "Production" : "Sandbox"
  219. return "\(truncatedToken)(\(tokenType))"
  220. }
  221. func appCredentialString() -> String {
  222. if let credential = AppManager.shared.auth().appCredentialManager.credential {
  223. let truncatedReceipt = truncatedString(string: credential.receipt, length: 13)
  224. let truncatedSecret = truncatedString(string: credential.secret ?? "", length: 13)
  225. return "\(truncatedReceipt)/\(truncatedSecret)"
  226. } else {
  227. return "No App Credential"
  228. }
  229. }
  230. private var languageSection: Section {
  231. let languageCode = AppManager.shared.auth().languageCode
  232. let items = [Item(title: languageCode ?? "[none]", detailTitle: "Auth Language"),
  233. Item(title: "Click to Use App Language", detailTitle: "Use App Language")]
  234. return Section(headerDescription: "Language", items: items)
  235. }
  236. private var disableSection: Section {
  237. guard let settings = AppManager.shared.auth().settings else {
  238. fatalError("Missing auth settings")
  239. }
  240. let disabling = settings.isAppVerificationDisabledForTesting ? "YES" : "NO"
  241. let items = [Item(title: disabling, detailTitle: "Disable App Verification (Phone)")]
  242. return Section(headerDescription: "Auth Settings", items: items)
  243. }
  244. var sections: [Section] {
  245. [
  246. versionSection,
  247. apiHostSection,
  248. appsSection,
  249. keychainSection,
  250. phoneAuthSection,
  251. languageSection,
  252. disableSection,
  253. ]
  254. }
  255. }