AuthComponent.swift 2.4 KB

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