AuthNotificationManager.swift 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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. #if !os(macOS) && !os(watchOS)
  15. import Foundation
  16. import UIKit
  17. /// A class represents a credential that proves the identity of the app.
  18. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  19. @preconcurrency
  20. class AuthNotificationManager {
  21. /// The key to locate payload data in the remote notification.
  22. private let kNotificationDataKey = "com.google.firebase.auth"
  23. /// The key for the receipt in the remote notification payload data.
  24. private let kNotificationReceiptKey = "receipt"
  25. /// The key for the secret in the remote notification payload data.
  26. private let kNotificationSecretKey = "secret"
  27. /// The key for marking the prober in the remote notification payload data.
  28. private let kNotificationProberKey = "warning"
  29. /// Timeout for probing whether the app delegate forwards the remote notification to us.
  30. private let kProbingTimeout = 1.0
  31. /// The application.
  32. private let application: UIApplication
  33. /// The object to handle app credentials delivered via notification.
  34. private let appCredentialManager: AuthAppCredentialManager
  35. /// Whether notification forwarding has been checked or not.
  36. private var hasCheckedNotificationForwarding: Bool = false
  37. /// Whether or not notification is being forwarded
  38. private var isNotificationBeingForwarded: Bool = false
  39. /// The timeout for checking for notification forwarding.
  40. ///
  41. /// Only tests should access this property.
  42. let timeout: TimeInterval
  43. /// Disable callback waiting for tests.
  44. ///
  45. /// Only tests should access this property.
  46. var immediateCallbackForTestFaking: (() -> Bool)?
  47. private let condition: AuthCondition
  48. /// Initializes the instance.
  49. /// - Parameter application: The application.
  50. /// - Parameter appCredentialManager: The object to handle app credentials delivered via
  51. /// notification.
  52. /// - Returns: The initialized instance.
  53. init(withApplication application: UIApplication,
  54. appCredentialManager: AuthAppCredentialManager) {
  55. self.application = application
  56. self.appCredentialManager = appCredentialManager
  57. timeout = kProbingTimeout
  58. condition = AuthCondition()
  59. }
  60. private actor PendingCount {
  61. private var count = 0
  62. func increment() -> Int {
  63. count = count + 1
  64. return count
  65. }
  66. }
  67. private let pendingCount = PendingCount()
  68. /// Checks whether or not remote notifications are being forwarded to this class.
  69. func checkNotificationForwarding() async -> Bool {
  70. if let getValueFunc = immediateCallbackForTestFaking {
  71. return getValueFunc()
  72. }
  73. if hasCheckedNotificationForwarding {
  74. return isNotificationBeingForwarded
  75. }
  76. if await pendingCount.increment() == 1 {
  77. DispatchQueue.main.async {
  78. let proberNotification = [self.kNotificationDataKey: [self.kNotificationProberKey:
  79. "This fake notification should be forwarded to Firebase Auth."]]
  80. if let delegate = self.application.delegate,
  81. delegate
  82. .responds(to: #selector(UIApplicationDelegate
  83. .application(_:didReceiveRemoteNotification:fetchCompletionHandler:))) {
  84. delegate.application?(self.application,
  85. didReceiveRemoteNotification: proberNotification) { _ in
  86. }
  87. } else {
  88. AuthLog.logWarning(
  89. code: "I-AUT000015",
  90. message: "The UIApplicationDelegate must handle " +
  91. "remote notification for phone number authentication to work."
  92. )
  93. }
  94. kAuthGlobalWorkQueue.asyncAfter(deadline: .now() + .seconds(Int(self.timeout))) {
  95. self.condition.signal()
  96. }
  97. }
  98. }
  99. await condition.wait()
  100. hasCheckedNotificationForwarding = true
  101. return isNotificationBeingForwarded
  102. }
  103. /// Attempts to handle the remote notification.
  104. /// - Parameter notification: The notification in question.
  105. /// - Returns: Whether or the notification has been handled.
  106. func canHandle(notification: [AnyHashable: Any]) -> Bool {
  107. var stringDictionary: [String: Any]?
  108. let data = notification[kNotificationDataKey]
  109. if let jsonString = data as? String {
  110. // Deserialize in case the data is a JSON string.
  111. guard let jsonData = jsonString.data(using: .utf8),
  112. let dictionary = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any]
  113. else {
  114. return false
  115. }
  116. stringDictionary = dictionary
  117. }
  118. guard let dictionary = stringDictionary ?? data as? [String: Any] else {
  119. return false
  120. }
  121. if dictionary[kNotificationProberKey] != nil {
  122. if hasCheckedNotificationForwarding {
  123. // The prober notification probably comes from another instance, so pass it along.
  124. return false
  125. }
  126. isNotificationBeingForwarded = true
  127. condition.signal()
  128. return true
  129. }
  130. guard let receipt = dictionary[kNotificationReceiptKey] as? String,
  131. let secret = dictionary[kNotificationSecretKey] as? String else {
  132. return false
  133. }
  134. return appCredentialManager.canFinishVerification(withReceipt: receipt, secret: secret)
  135. }
  136. }
  137. #endif