AuthNotificationManager.swift 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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. /// All pending callbacks while a check is being performed.
  47. private var pendingCallbacks: [(Bool) -> Void]?
  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. }
  59. /// Checks whether or not remote notifications are being forwarded to this class.
  60. /// - Parameter callback: The block to be called either immediately or in future once a result
  61. /// is available.
  62. func checkNotificationForwardingInternal(withCallback callback: @escaping (Bool) -> Void) {
  63. if pendingCallbacks != nil {
  64. pendingCallbacks?.append(callback)
  65. return
  66. }
  67. if let getValueFunc = immediateCallbackForTestFaking {
  68. callback(getValueFunc())
  69. return
  70. }
  71. if hasCheckedNotificationForwarding {
  72. callback(isNotificationBeingForwarded)
  73. return
  74. }
  75. hasCheckedNotificationForwarding = true
  76. pendingCallbacks = [callback]
  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.callback()
  96. }
  97. }
  98. }
  99. func checkNotificationForwarding() async -> Bool {
  100. return await withCheckedContinuation { continuation in
  101. checkNotificationForwardingInternal { value in
  102. continuation.resume(returning: value)
  103. }
  104. }
  105. }
  106. /// Attempts to handle the remote notification.
  107. /// - Parameter notification: The notification in question.
  108. /// - Returns: Whether or the notification has been handled.
  109. func canHandle(notification: [AnyHashable: Any]) -> Bool {
  110. var stringDictionary: [String: Any]?
  111. let data = notification[kNotificationDataKey]
  112. if let jsonString = data as? String {
  113. // Deserialize in case the data is a JSON string.
  114. guard let jsonData = jsonString.data(using: .utf8),
  115. let dictionary = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any]
  116. else {
  117. return false
  118. }
  119. stringDictionary = dictionary
  120. }
  121. guard let dictionary = stringDictionary ?? data as? [String: Any] else {
  122. return false
  123. }
  124. if dictionary[kNotificationProberKey] != nil {
  125. if pendingCallbacks == nil {
  126. // The prober notification probably comes from another instance, so pass it along.
  127. return false
  128. }
  129. isNotificationBeingForwarded = true
  130. callback()
  131. return true
  132. }
  133. guard let receipt = dictionary[kNotificationReceiptKey] as? String,
  134. let secret = dictionary[kNotificationSecretKey] as? String else {
  135. return false
  136. }
  137. return appCredentialManager.canFinishVerification(withReceipt: receipt, secret: secret)
  138. }
  139. // MARK: Internal methods
  140. private func callback() {
  141. guard let pendingCallbacks else {
  142. return
  143. }
  144. self.pendingCallbacks = nil
  145. for callback in pendingCallbacks {
  146. callback(isNotificationBeingForwarded)
  147. }
  148. }
  149. }
  150. #endif