StorageTokenAuthorizer.swift 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. FirebaseLogger.log(
  61. level: .debug,
  62. service: "[FirebaseStorage]",
  63. code: "I-STR000001",
  64. message: "Failed to fetch AppCheck token. Error: \(error)"
  65. )
  66. }
  67. fetchTokenGroup.leave()
  68. }
  69. }
  70. fetchTokenGroup.notify(queue: callbackQueue) {
  71. handler(tokenError)
  72. }
  73. }
  74. func authorizeRequest(_ request: NSMutableURLRequest?, delegate: Any, didFinish sel: Selector) {
  75. fatalError("Internal error: Should not call old authorizeRequest")
  76. }
  77. // Note that stopAuthorization, isAuthorizingRequest, and userEmail
  78. // aren't relevant with the Firebase App/Auth implementation of tokens,
  79. // and thus aren't implemented. Token refresh is handled transparently
  80. // for us, and we don't allow the auth request to be stopped.
  81. // Auth is also not required so the world doesn't stop.
  82. func stopAuthorization() {}
  83. func stopAuthorization(for request: URLRequest) {}
  84. func isAuthorizingRequest(_ request: URLRequest) -> Bool {
  85. return false
  86. }
  87. func isAuthorizedRequest(_ request: URLRequest) -> Bool {
  88. guard let authHeader = request.allHTTPHeaderFields?["Authorization"] else {
  89. return false
  90. }
  91. return authHeader.hasPrefix("Firebase")
  92. }
  93. var userEmail: String?
  94. internal let fetcherService: GTMSessionFetcherService
  95. private let googleAppID: String
  96. private let auth: AuthInterop?
  97. private let appCheck: AppCheckInterop?
  98. private let serialAuthArgsQueue = DispatchQueue(label: "com.google.firebasestorage.authorizer")
  99. init(googleAppID: String,
  100. fetcherService: GTMSessionFetcherService,
  101. authProvider: AuthInterop?,
  102. appCheck: AppCheckInterop?) {
  103. self.googleAppID = googleAppID
  104. self.fetcherService = fetcherService
  105. auth = authProvider
  106. self.appCheck = appCheck
  107. }
  108. }