FunctionsContext.swift 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. // Copyright 2022 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 FirebaseAppCheckInterop
  15. import FirebaseAuthInterop
  16. import FirebaseMessagingInterop
  17. import Foundation
  18. /// `FunctionsContext` is a helper object that holds metadata for a function call.
  19. struct FunctionsContext {
  20. let authToken: String?
  21. let fcmToken: String?
  22. let appCheckToken: String?
  23. let limitedUseAppCheckToken: String?
  24. }
  25. struct FunctionsContextProvider {
  26. private let auth: AuthInterop?
  27. private let messaging: MessagingInterop?
  28. private let appCheck: AppCheckInterop?
  29. init(auth: AuthInterop?, messaging: MessagingInterop?, appCheck: AppCheckInterop?) {
  30. self.auth = auth
  31. self.messaging = messaging
  32. self.appCheck = appCheck
  33. }
  34. @available(iOS 13, macCatalyst 13, macOS 10.15, tvOS 13, watchOS 7, *)
  35. func context(options: HTTPSCallableOptions?) async throws -> FunctionsContext {
  36. async let authToken = auth?.getToken(forcingRefresh: false)
  37. async let appCheckToken = getAppCheckToken(options: options)
  38. async let limitedUseAppCheckToken = getLimitedUseAppCheckToken(options: options)
  39. // Only `authToken` is throwing, but the formatter script removes the `try`
  40. // from `try authToken` and puts it in front of the initializer call.
  41. return try await FunctionsContext(
  42. authToken: authToken,
  43. fcmToken: messaging?.fcmToken,
  44. appCheckToken: appCheckToken,
  45. limitedUseAppCheckToken: limitedUseAppCheckToken
  46. )
  47. }
  48. @available(iOS 13, macCatalyst 13, macOS 10.15, tvOS 13, watchOS 7, *)
  49. private func getAppCheckToken(options: HTTPSCallableOptions?) async -> String? {
  50. guard
  51. options?.requireLimitedUseAppCheckTokens != true,
  52. let tokenResult = await appCheck?.getToken(forcingRefresh: false),
  53. tokenResult.error == nil
  54. else { return nil }
  55. return tokenResult.token
  56. }
  57. @available(iOS 13, macCatalyst 13, macOS 10.15, tvOS 13, watchOS 7, *)
  58. private func getLimitedUseAppCheckToken(options: HTTPSCallableOptions?) async -> String? {
  59. // At the moment, `await` doesn’t get along with Objective-C’s optional protocol methods.
  60. await withCheckedContinuation { (continuation: CheckedContinuation<String?, Never>) in
  61. guard
  62. options?.requireLimitedUseAppCheckTokens == true,
  63. let appCheck,
  64. // `getLimitedUseToken(completion:)` is an optional protocol method. Optional binding
  65. // is performed to make sure `continuation` is called even if the method’s not implemented.
  66. let limitedUseTokenClosure = appCheck.getLimitedUseToken
  67. else {
  68. return continuation.resume(returning: nil)
  69. }
  70. limitedUseTokenClosure { tokenResult in
  71. // Make sure there’s no error and the token is valid:
  72. guard tokenResult.error == nil else { return continuation.resume(returning: nil) }
  73. continuation.resume(returning: tokenResult.token)
  74. }
  75. }
  76. }
  77. func getContext(options: HTTPSCallableOptions? = nil,
  78. _ completion: @escaping ((FunctionsContext, Error?) -> Void)) {
  79. let dispatchGroup = DispatchGroup()
  80. var authToken: String?
  81. var appCheckToken: String?
  82. var error: Error?
  83. var limitedUseAppCheckToken: String?
  84. if let auth {
  85. dispatchGroup.enter()
  86. auth.getToken(forcingRefresh: false) { token, authError in
  87. authToken = token
  88. error = authError
  89. dispatchGroup.leave()
  90. }
  91. }
  92. if let appCheck {
  93. dispatchGroup.enter()
  94. if options?.requireLimitedUseAppCheckTokens == true {
  95. // `getLimitedUseToken(completion:)` is an optional protocol method.
  96. // If it’s not implemented, we still need to leave the dispatch group.
  97. if let limitedUseTokenClosure = appCheck.getLimitedUseToken {
  98. limitedUseTokenClosure { tokenResult in
  99. // Send only valid token to functions.
  100. if tokenResult.error == nil {
  101. limitedUseAppCheckToken = tokenResult.token
  102. }
  103. dispatchGroup.leave()
  104. }
  105. } else {
  106. dispatchGroup.leave()
  107. }
  108. } else {
  109. appCheck.getToken(forcingRefresh: false) { tokenResult in
  110. // Send only valid token to functions.
  111. if tokenResult.error == nil {
  112. appCheckToken = tokenResult.token
  113. }
  114. dispatchGroup.leave()
  115. }
  116. }
  117. }
  118. dispatchGroup.notify(queue: .main) {
  119. let context = FunctionsContext(authToken: authToken,
  120. fcmToken: self.messaging?.fcmToken,
  121. appCheckToken: appCheckToken,
  122. limitedUseAppCheckToken: limitedUseAppCheckToken)
  123. completion(context, error)
  124. }
  125. }
  126. }