AuthNotificationManager.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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) && !os(visionOS)
  15. import Foundation
  16. import UIKit
  17. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  18. class AuthNotificationManager: NSObject {
  19. /// The key to locate payload data in the remote notification.
  20. private let kNotificationDataKey = "com.google.firebase.auth"
  21. /// The key for the receipt in the remote notification payload data.
  22. private let kNotificationReceiptKey = "receipt"
  23. /// The key for the secret in the remote notification payload data.
  24. private let kNotificationSecretKey = "secret"
  25. /// The key for marking the prober in the remote notification payload data.
  26. private let kNotificationProberKey = "warning"
  27. /// Timeout for probing whether the app delegate forwards the remote notification to us.
  28. private let kProbingTimeout = 1.0
  29. /// The application.
  30. private let application: UIApplication
  31. /// The object to handle app credentials delivered via notification.
  32. private let appCredentialManager: AuthAppCredentialManager
  33. /// Whether notification forwarding has been checked or not.
  34. private var hasCheckedNotificationForwarding: Bool = false
  35. /// Whether or not notification is being forwarded
  36. private var isNotificationBeingForwarded: Bool = false
  37. /// The timeout for checking for notification forwarding.
  38. ///
  39. /// Only tests should access this property.
  40. let timeout: TimeInterval
  41. /// Disable callback waiting for tests.
  42. ///
  43. /// Only tests should access this property.
  44. var immediateCallbackForTestFaking: (() -> Bool)?
  45. /// All pending callbacks while a check is being performed.
  46. private var pendingCallbacks: [(Bool) -> Void]?
  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. }
  58. /// Checks whether or not remote notifications are being forwarded to this class.
  59. /// - Parameter callback: The block to be called either immediately or in future once a result
  60. /// is available.
  61. func checkNotificationForwardingInternal(withCallback callback: @escaping (Bool) -> Void) {
  62. if pendingCallbacks != nil {
  63. pendingCallbacks?.append(callback)
  64. return
  65. }
  66. if let getValueFunc = immediateCallbackForTestFaking {
  67. callback(getValueFunc())
  68. return
  69. }
  70. if hasCheckedNotificationForwarding {
  71. callback(isNotificationBeingForwarded)
  72. return
  73. }
  74. hasCheckedNotificationForwarding = true
  75. pendingCallbacks = [callback]
  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 if let delegate = self.application.delegate,
  87. delegate
  88. .responds(to: #selector(UIApplicationDelegate
  89. .application(_:didReceiveRemoteNotification:))) {
  90. delegate.application?(self.application,
  91. didReceiveRemoteNotification: proberNotification)
  92. } else {
  93. AuthLog.logWarning(
  94. code: "I-AUT000015",
  95. message: "The UIApplicationDelegate must handle " +
  96. "remote notification for phone number authentication to work."
  97. )
  98. }
  99. kAuthGlobalWorkQueue.asyncAfter(deadline: .now() + .seconds(Int(self.timeout))) {
  100. self.callback()
  101. }
  102. }
  103. }
  104. func checkNotificationForwarding() async -> Bool {
  105. return await withCheckedContinuation { continuation in
  106. checkNotificationForwardingInternal { value in
  107. continuation.resume(returning: value)
  108. }
  109. }
  110. }
  111. /// Attempts to handle the remote notification.
  112. /// - Parameter notification: The notification in question.
  113. /// - Returns: Whether or the notification has been handled.
  114. func canHandle(notification: [AnyHashable: Any]) -> Bool {
  115. var stringDictionary: [String: Any]?
  116. let data = notification[kNotificationDataKey]
  117. if let jsonString = data as? String {
  118. // Deserialize in case the data is a JSON string.
  119. guard let jsonData = jsonString.data(using: .utf8),
  120. let dictionary = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any]
  121. else {
  122. return false
  123. }
  124. stringDictionary = dictionary
  125. }
  126. guard let dictionary = stringDictionary ?? data as? [String: Any] else {
  127. return false
  128. }
  129. if dictionary[kNotificationProberKey] != nil {
  130. if pendingCallbacks == nil {
  131. // The prober notification probably comes from another instance, so pass it along.
  132. return false
  133. }
  134. isNotificationBeingForwarded = true
  135. callback()
  136. return true
  137. }
  138. guard let receipt = dictionary[kNotificationReceiptKey] as? String,
  139. let secret = dictionary[kNotificationSecretKey] as? String else {
  140. return false
  141. }
  142. return appCredentialManager.canFinishVerification(withReceipt: receipt, secret: secret)
  143. }
  144. // MARK: Internal methods
  145. private func callback() {
  146. guard let pendingCallbacks else {
  147. return
  148. }
  149. self.pendingCallbacks = nil
  150. for callback in pendingCallbacks {
  151. callback(isNotificationBeingForwarded)
  152. }
  153. }
  154. }
  155. #endif