AuthComponent.swift 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. import Foundation
  15. @_implementationOnly import FirebaseAppCheckInterop
  16. import FirebaseCore
  17. // Avoids exposing internal FirebaseCore APIs to Swift users.
  18. @_implementationOnly import FirebaseCoreExtension
  19. @objc(FIRAuthProvider) public protocol AuthProvider {
  20. @objc func auth() -> Auth
  21. }
  22. @objc(FIRAuthComponent) class AuthComponent: NSObject, Library, AuthProvider {
  23. // MARK: - Private Variables
  24. /// The app associated with all Auth instances in this container.
  25. /// This is `unowned` instead of `weak` so it can be used without unwrapping in `auth()`
  26. private unowned let app: FirebaseApp
  27. /// A map of active instances, grouped by app. Keys are FirebaseApp names and values are arrays
  28. /// containing all instances of Auth associated with the given app.
  29. private var instances: [String: Auth] = [:]
  30. /// Lock to manage access to the instances array to avoid race conditions.
  31. private var instancesLock: os_unfair_lock = .init()
  32. // MARK: - Initializers
  33. required init(app: FirebaseApp) {
  34. self.app = app
  35. }
  36. // MARK: - Library conformance
  37. static func componentsToRegister() -> [Component] {
  38. let appCheckInterop = Dependency(with: AppCheckInterop.self, isRequired: false)
  39. return [Component(AuthProvider.self,
  40. instantiationTiming: .alwaysEager,
  41. dependencies: [
  42. appCheckInterop,
  43. ]) { container, isCacheable in
  44. guard let app = container.app else { return nil }
  45. isCacheable.pointee = true
  46. return self.init(app: app)
  47. }]
  48. }
  49. // MARK: - AuthProvider conformance
  50. func auth() -> Auth {
  51. os_unfair_lock_lock(&instancesLock)
  52. // Unlock before the function returns.
  53. defer { os_unfair_lock_unlock(&instancesLock) }
  54. if let instance = instances[app.name] {
  55. return instance
  56. }
  57. let newInstance = FirebaseAuth.Auth(app: app)
  58. instances[app.name] = newInstance
  59. return newInstance
  60. }
  61. }