AuthNotificationManager.swift 5.8 KB

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