StorageTokenAuthorizer.swift 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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 Foundation
  15. import FirebaseAppCheckInterop
  16. import FirebaseAuthInterop
  17. import FirebaseCore
  18. internal import FirebaseCoreExtension
  19. #if COCOAPODS
  20. import GTMSessionFetcher
  21. #else
  22. import GTMSessionFetcherCore
  23. #endif
  24. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  25. class StorageTokenAuthorizer: NSObject, GTMSessionFetcherAuthorizer {
  26. func authorizeRequest(_ request: NSMutableURLRequest?,
  27. completionHandler handler: @escaping (Error?) -> Void) {
  28. // Set version header on each request
  29. let versionString = "ios/\(FirebaseVersion())"
  30. request?.setValue(versionString, forHTTPHeaderField: "x-firebase-storage-version")
  31. // Set GMP ID on each request
  32. request?.setValue(googleAppID, forHTTPHeaderField: "x-firebase-gmpid")
  33. var tokenError: NSError?
  34. let fetchTokenGroup = DispatchGroup()
  35. if let auth {
  36. fetchTokenGroup.enter()
  37. auth.getToken(forcingRefresh: false) { token, error in
  38. if let error = error as? NSError {
  39. var errorDictionary = error.userInfo
  40. errorDictionary["ResponseErrorDomain"] = error.domain
  41. errorDictionary["ResponseErrorCode"] = error.code
  42. tokenError = StorageError.unauthenticated(serverError: errorDictionary) as NSError
  43. } else if let token {
  44. let firebaseToken = "Firebase \(token)"
  45. request?.setValue(firebaseToken, forHTTPHeaderField: "Authorization")
  46. }
  47. fetchTokenGroup.leave()
  48. }
  49. }
  50. if let appCheck {
  51. fetchTokenGroup.enter()
  52. appCheck.getToken(forcingRefresh: false) { tokenResult in
  53. request?.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
  54. if let error = tokenResult.error {
  55. FirebaseLogger.log(
  56. level: .debug,
  57. service: "[FirebaseStorage]",
  58. code: "I-STR000001",
  59. message: "Failed to fetch AppCheck token. Error: \(error)"
  60. )
  61. }
  62. fetchTokenGroup.leave()
  63. }
  64. }
  65. fetchTokenGroup.notify(queue: callbackQueue) {
  66. handler(tokenError)
  67. }
  68. }
  69. func authorizeRequest(_ request: NSMutableURLRequest?, delegate: Any, didFinish sel: Selector) {
  70. fatalError("Internal error: Should not call old authorizeRequest")
  71. }
  72. // Note that stopAuthorization, isAuthorizingRequest, and userEmail
  73. // aren't relevant with the Firebase App/Auth implementation of tokens,
  74. // and thus aren't implemented. Token refresh is handled transparently
  75. // for us, and we don't allow the auth request to be stopped.
  76. // Auth is also not required so the world doesn't stop.
  77. func stopAuthorization() {}
  78. func stopAuthorization(for request: URLRequest) {}
  79. func isAuthorizingRequest(_ request: URLRequest) -> Bool {
  80. return false
  81. }
  82. func isAuthorizedRequest(_ request: URLRequest) -> Bool {
  83. guard let authHeader = request.allHTTPHeaderFields?["Authorization"] else {
  84. return false
  85. }
  86. return authHeader.hasPrefix("Firebase")
  87. }
  88. var userEmail: String?
  89. let callbackQueue: DispatchQueue
  90. private let googleAppID: String
  91. private let auth: AuthInterop?
  92. private let appCheck: AppCheckInterop?
  93. private let serialAuthArgsQueue = DispatchQueue(label: "com.google.firebasestorage.authorizer")
  94. init(googleAppID: String,
  95. callbackQueue: DispatchQueue = DispatchQueue.main,
  96. authProvider: AuthInterop?,
  97. appCheck: AppCheckInterop?) {
  98. self.googleAppID = googleAppID
  99. self.callbackQueue = callbackQueue
  100. auth = authProvider
  101. self.appCheck = appCheck
  102. }
  103. }