StorageTokenAuthorizer.swift 4.3 KB

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