AuthBackend.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. import Foundation
  15. import FirebaseCore
  16. import FirebaseCoreExtension
  17. import FirebaseCoreInternal
  18. #if COCOAPODS
  19. import GTMSessionFetcher
  20. #else
  21. import GTMSessionFetcherCore
  22. #endif
  23. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  24. public protocol AuthBackendRPCIssuer: NSObjectProtocol {
  25. /** @fn
  26. @brief Asynchronously sends a POST request.
  27. @param requestConfiguration The request to be made.
  28. @param URL The request URL.
  29. @param body Request body.
  30. @param contentType Content type of the body.
  31. @param handler provided that handles POST response. Invoked asynchronously on the auth global
  32. work queue in the future.
  33. */
  34. func asyncPostToURL(withRequest request: AuthRPCRequest,
  35. body: Data?,
  36. contentType: String,
  37. completionHandler: @escaping ((Data?, Error?) -> Void))
  38. }
  39. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  40. public class AuthBackendRPCIssuerImplementation: NSObject, AuthBackendRPCIssuer {
  41. let fetcherService: GTMSessionFetcherService
  42. override init() {
  43. fetcherService = GTMSessionFetcherService()
  44. fetcherService.userAgent = AuthBackend.authUserAgent()
  45. fetcherService.callbackQueue = kAuthGlobalWorkQueue
  46. // Avoid reusing the session to prevent
  47. // https://github.com/firebase/firebase-ios-sdk/issues/1261
  48. fetcherService.reuseSession = false
  49. }
  50. public func asyncPostToURL(withRequest request: AuthRPCRequest,
  51. body: Data?,
  52. contentType: String,
  53. completionHandler: @escaping ((Data?, Error?) -> Void)) {
  54. let requestConfiguration = request.requestConfiguration()
  55. AuthBackend.request(withURL: request.requestURL(),
  56. contentType: contentType,
  57. requestConfiguration: requestConfiguration) { request in
  58. let fetcher = self.fetcherService.fetcher(with: request)
  59. if let _ = requestConfiguration.emulatorHostAndPort {
  60. fetcher.allowLocalhostRequest = true
  61. fetcher.allowedInsecureSchemes = ["http"]
  62. }
  63. fetcher.bodyData = body
  64. fetcher.beginFetch(completionHandler: completionHandler)
  65. }
  66. }
  67. }
  68. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  69. @objc(FIRAuthBackend2) public class AuthBackend: NSObject {
  70. static func authUserAgent() -> String {
  71. return "FirebaseAuth.iOS/\(FirebaseVersion()) \(GTMFetcherStandardUserAgentString(nil))"
  72. }
  73. private static var gBackendImplementation: AuthBackendImplementation?
  74. class func setDefaultBackendImplementationWithRPCIssuer(issuer: AuthBackendRPCIssuer?) {
  75. let defaultImplementation = AuthBackendRPCImplementation()
  76. if let issuer = issuer {
  77. defaultImplementation.rpcIssuer = issuer
  78. }
  79. gBackendImplementation = defaultImplementation
  80. }
  81. class func implementation() -> AuthBackendImplementation {
  82. if gBackendImplementation == nil {
  83. gBackendImplementation = AuthBackendRPCImplementation()
  84. }
  85. return (gBackendImplementation)!
  86. }
  87. /** @fn postWithRequest:response:callback:
  88. @brief Calls the RPC using HTTP POST.
  89. @remarks Possible error responses:
  90. @see FIRAuthInternalErrorCodeRPCRequestEncodingError
  91. @see FIRAuthInternalErrorCodeJSONSerializationError
  92. @see FIRAuthInternalErrorCodeNetworkError
  93. @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  94. @see FIRAuthInternalErrorCodeUnexpectedResponse
  95. @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  96. @param request The request.
  97. @param callback The callback for both success and failure.
  98. */
  99. @objc public class func post(withRequest request: AuthRPCRequest,
  100. callback: @escaping ((AuthRPCResponse?, Error?) -> Void)) {
  101. implementation().post(withRequest: request, callback: callback)
  102. }
  103. // TODO: Why does this need to be public to be visible by unit tests?
  104. public class func request(withURL url: URL,
  105. contentType: String,
  106. requestConfiguration: AuthRequestConfiguration,
  107. completion: @escaping (URLRequest) -> Void) {
  108. var request = URLRequest(url: url)
  109. request.setValue(contentType, forHTTPHeaderField: "Content-Type")
  110. let additionalFrameworkMarker = requestConfiguration
  111. .additionalFrameworkMarker ?? "FirebaseCore-iOS"
  112. let clientVersion = "iOS/FirebaseSDK/\(FirebaseVersion())/\(additionalFrameworkMarker)"
  113. request.setValue(clientVersion, forHTTPHeaderField: "X-Client-Version")
  114. request.setValue(Bundle.main.bundleIdentifier, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
  115. request.setValue(requestConfiguration.appID, forHTTPHeaderField: "X-Firebase-GMPID")
  116. // TODO: Enable for SPM. Can we directly call the Swift library?
  117. #if COCOAPODS
  118. if let heartbeatLogger = requestConfiguration.heartbeatLogger {
  119. request.setValue(
  120. FIRHeaderValueFromHeartbeatsPayload(heartbeatLogger.flushHeartbeatsIntoPayload()),
  121. forHTTPHeaderField: "X-Firebase-Client"
  122. )
  123. }
  124. #endif
  125. let preferredLocalizations = Bundle.main.preferredLocalizations
  126. if preferredLocalizations.count > 0 {
  127. request.setValue(preferredLocalizations.first, forHTTPHeaderField: "Accept-Language")
  128. }
  129. if let languageCode = requestConfiguration.languageCode,
  130. languageCode.count > 0 {
  131. request.setValue(languageCode, forHTTPHeaderField: "X-Firebase-Locale")
  132. }
  133. if let appCheck = requestConfiguration.appCheck {
  134. appCheck.getToken(forcingRefresh: false) { tokenResult in
  135. if let error = tokenResult.error {
  136. AuthLog.logWarning(code: "I-AUT000018",
  137. message: "Error getting App Check token; using placeholder " +
  138. "token instead. Error: \(error)")
  139. }
  140. request.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
  141. completion(request)
  142. }
  143. } else {
  144. completion(request)
  145. }
  146. }
  147. }
  148. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  149. protocol AuthBackendImplementation {
  150. func post(withRequest request: AuthRPCRequest,
  151. callback: @escaping ((AuthRPCResponse?, Error?) -> Void))
  152. func post(withRequest request: AuthRPCRequest,
  153. response: AuthRPCResponse,
  154. callback: @escaping ((Error?) -> Void))
  155. }
  156. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  157. private class AuthBackendRPCImplementation: NSObject, AuthBackendImplementation {
  158. var rpcIssuer: AuthBackendRPCIssuer
  159. override init() {
  160. rpcIssuer = AuthBackendRPCIssuerImplementation()
  161. }
  162. /** @fn postWithRequest:response:callback:
  163. @brief Calls the RPC using HTTP POST.
  164. @remarks Possible error responses:
  165. @see FIRAuthInternalErrorCodeRPCRequestEncodingError
  166. @see FIRAuthInternalErrorCodeJSONSerializationError
  167. @see FIRAuthInternalErrorCodeNetworkError
  168. @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  169. @see FIRAuthInternalErrorCodeUnexpectedResponse
  170. @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  171. @param request The request.
  172. @param response The empty response to be filled.
  173. @param callback The callback for both success and failure.
  174. */
  175. fileprivate func post(withRequest request: AuthRPCRequest,
  176. callback: @escaping ((AuthRPCResponse?, Error?) -> Void)) {
  177. let response = request.response
  178. post(withRequest: request, response: response) { error in
  179. if let error = error {
  180. callback(nil, error)
  181. } else if let auth = request.requestConfiguration().auth,
  182. let mfaError = AuthBackendRPCImplementation
  183. .generateMFAError(response: response, auth: auth) {
  184. callback(nil, mfaError)
  185. } else if let error = AuthBackendRPCImplementation.phoneCredentialInUse(response: response) {
  186. callback(nil, error)
  187. } else {
  188. callback(response, nil)
  189. }
  190. }
  191. }
  192. #if os(iOS)
  193. private class func generateMFAError(response: AuthRPCResponse, auth: Auth) -> Error? {
  194. if let mfaResponse = response as? EmailLinkSignInResponse,
  195. mfaResponse.idToken == nil,
  196. let enrollments = mfaResponse.MFAInfo {
  197. var info: [MultiFactorInfo] = []
  198. for enrollment in enrollments {
  199. info.append(MultiFactorInfo(proto: enrollment))
  200. }
  201. return AuthErrorUtils.secondFactorRequiredError(
  202. pendingCredential: mfaResponse.MFAPendingCredential,
  203. hints: info,
  204. auth: auth
  205. )
  206. } else {
  207. return nil
  208. }
  209. }
  210. #else
  211. private class func generateMFAError(response: AuthRPCResponse, auth: Auth?) -> Error? {
  212. return nil
  213. }
  214. #endif
  215. #if os(iOS)
  216. // Check whether or not the successful response is actually the special case phone
  217. // auth flow that returns a temporary proof and phone number.
  218. private class func phoneCredentialInUse(response: AuthRPCResponse) -> Error? {
  219. if let phoneAuthResponse = response as? VerifyPhoneNumberResponse,
  220. let phoneNumber = phoneAuthResponse.phoneNumber,
  221. phoneNumber.count > 0,
  222. let temporaryProof = phoneAuthResponse.temporaryProof,
  223. temporaryProof.count > 0 {
  224. let credential = PhoneAuthCredential(withTemporaryProof: temporaryProof,
  225. phoneNumber: phoneNumber,
  226. providerID: PhoneAuthProvider.id)
  227. return AuthErrorUtils.credentialAlreadyInUseError(message: nil,
  228. credential: credential,
  229. email: nil)
  230. } else {
  231. return nil
  232. }
  233. }
  234. #else
  235. private class func phoneCredentialInUse(response: AuthRPCResponse) -> Error? {
  236. return nil
  237. }
  238. #endif
  239. /** @fn postWithRequest:response:callback:
  240. @brief Calls the RPC using HTTP POST.
  241. @remarks Possible error responses:
  242. @see FIRAuthInternalErrorCodeRPCRequestEncodingError
  243. @see FIRAuthInternalErrorCodeJSONSerializationError
  244. @see FIRAuthInternalErrorCodeNetworkError
  245. @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  246. @see FIRAuthInternalErrorCodeUnexpectedResponse
  247. @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  248. @param request The request.
  249. @param response The empty response to be filled.
  250. @param callback The callback for both success and failure.
  251. */
  252. fileprivate func post(withRequest request: AuthRPCRequest,
  253. response: AuthRPCResponse,
  254. callback: @escaping ((Error?) -> Void)) {
  255. var bodyData: Data?
  256. if let contains = request.containsPostBody,
  257. contains() {
  258. do {
  259. // TODO: Can unencodedHTTPRequestBody ever throw?
  260. // They don't today, but there are a few fatalErrors that might better be implemented as
  261. // thrown errors.. Although perhaps the case of 'containsPostBody' returning false could
  262. // perhaps be modeled differently so that the failing unencodedHTTPRequestBody could only
  263. // be called when a body exists...
  264. let postBody = try request.unencodedHTTPRequestBody()
  265. var JSONWritingOptions: JSONSerialization.WritingOptions = .init(rawValue: 0)
  266. #if DEBUG
  267. JSONWritingOptions = JSONSerialization.WritingOptions.prettyPrinted
  268. #endif
  269. guard JSONSerialization.isValidJSONObject(postBody) else {
  270. callback(AuthErrorUtils.JSONSerializationErrorForUnencodableType())
  271. return
  272. }
  273. bodyData = try? JSONSerialization.data(
  274. withJSONObject: postBody,
  275. options: JSONWritingOptions
  276. )
  277. if bodyData == nil {
  278. // This is an untested case. This happens exclusively when there is an error in the
  279. // framework implementation of dataWithJSONObject:options:error:. This shouldn't normally
  280. // occur as isValidJSONObject: should return NO in any case we should encounter an error.
  281. callback(AuthErrorUtils.JSONSerializationErrorForUnencodableType())
  282. return
  283. }
  284. } catch {
  285. callback(AuthErrorUtils.RPCRequestEncodingError(underlyingError: error))
  286. return
  287. }
  288. }
  289. rpcIssuer
  290. .asyncPostToURL(withRequest: request, body: bodyData, contentType: "application/json") {
  291. data, error in
  292. // If there is an error with no body data at all, then this must be a
  293. // network error.
  294. guard let data = data else {
  295. if let error = error {
  296. callback(AuthErrorUtils.networkError(underlyingError: error))
  297. return
  298. } else {
  299. // TODO: this was ignored before
  300. fatalError("Internal error")
  301. }
  302. }
  303. // Try to decode the HTTP response data which may contain either a
  304. // successful response or error message.
  305. var dictionary: [String: AnyHashable]
  306. do {
  307. let rawDecode = try JSONSerialization.jsonObject(with: data,
  308. options: JSONSerialization.ReadingOptions
  309. .mutableLeaves)
  310. guard let decodedDictionary = rawDecode as? [String: AnyHashable] else {
  311. if error != nil {
  312. callback(AuthErrorUtils.unexpectedErrorResponse(deserializedResponse: rawDecode,
  313. underlyingError: error))
  314. } else {
  315. callback(AuthErrorUtils.unexpectedResponse(deserializedResponse: rawDecode))
  316. }
  317. return
  318. }
  319. dictionary = decodedDictionary
  320. } catch let jsonError {
  321. if error != nil {
  322. // We have an error, but we couldn't decode the body, so we have no
  323. // additional information other than the raw response and the
  324. // original NSError (the jsonError is inferred by the error code
  325. // (AuthErrorCodeUnexpectedHTTPResponse, and is irrelevant.)
  326. callback(AuthErrorUtils.unexpectedErrorResponse(data: data, underlyingError: error))
  327. return
  328. } else {
  329. // This is supposed to be a "successful" response, but we couldn't
  330. // deserialize the body.
  331. callback(AuthErrorUtils.unexpectedResponse(data: data, underlyingError: jsonError))
  332. return
  333. }
  334. }
  335. // At this point we either have an error with successfully decoded
  336. // details in the body, or we have a response which must pass further
  337. // validation before we know it's truly successful. We deal with the
  338. // case where we have an error with successfully decoded error details
  339. // first:
  340. if error != nil {
  341. if let errorDictionary = dictionary["error"] as? [String: AnyHashable] {
  342. if let errorMessage = errorDictionary["message"] as? String {
  343. if let clientError = AuthBackendRPCImplementation.clientError(
  344. withServerErrorMessage: errorMessage,
  345. errorDictionary: errorDictionary,
  346. response: response,
  347. error: error
  348. ) {
  349. callback(clientError)
  350. return
  351. }
  352. }
  353. // Not a message we know, return the message directly.
  354. callback(AuthErrorUtils.unexpectedErrorResponse(
  355. deserializedResponse: errorDictionary,
  356. underlyingError: error
  357. ))
  358. return
  359. }
  360. // No error message at all, return the decoded response.
  361. callback(AuthErrorUtils
  362. .unexpectedErrorResponse(deserializedResponse: dictionary, underlyingError: error))
  363. return
  364. }
  365. // Finally, we try to populate the response object with the JSON
  366. // values.
  367. do {
  368. try response.setFields(dictionary: dictionary)
  369. } catch {
  370. callback(AuthErrorUtils
  371. .RPCResponseDecodingError(deserializedResponse: dictionary, underlyingError: error))
  372. return
  373. }
  374. // In case returnIDPCredential of a verifyAssertion request is set to
  375. // @YES, the server may return a 200 with a response that may contain a
  376. // server error.
  377. if let verifyAssertionRequest = request as? VerifyAssertionRequest {
  378. if verifyAssertionRequest.returnIDPCredential {
  379. if let errorMessage = dictionary["errorMessage"] as? String {
  380. let clientError = AuthBackendRPCImplementation.clientError(
  381. withServerErrorMessage: errorMessage,
  382. errorDictionary: dictionary,
  383. response: response,
  384. error: error
  385. )
  386. callback(clientError)
  387. return
  388. }
  389. }
  390. }
  391. callback(nil)
  392. }
  393. }
  394. private class func clientError(withServerErrorMessage serverErrorMessage: String,
  395. errorDictionary: [String: Any],
  396. response: AuthRPCResponse,
  397. error: Error?) -> Error? {
  398. let split = serverErrorMessage.split(separator: ":")
  399. let shortErrorMessage = split.first?.trimmingCharacters(in: .whitespacesAndNewlines)
  400. let serverDetailErrorMessage = String(split.count > 1 ? split[1] : "")
  401. .trimmingCharacters(in: .whitespacesAndNewlines)
  402. switch shortErrorMessage {
  403. case "USER_NOT_FOUND": return AuthErrorUtils
  404. .userNotFoundError(message: serverDetailErrorMessage)
  405. case "MISSING_CONTINUE_URI": return AuthErrorUtils
  406. .missingContinueURIError(message: serverDetailErrorMessage)
  407. // "INVALID_IDENTIFIER" can be returned by createAuthURI RPC. Considering email addresses are
  408. // currently the only identifiers, we surface the FIRAuthErrorCodeInvalidEmail error code in this
  409. // case.
  410. case "INVALID_IDENTIFIER": return AuthErrorUtils
  411. .invalidEmailError(message: serverDetailErrorMessage)
  412. case "INVALID_ID_TOKEN": return AuthErrorUtils
  413. .invalidUserTokenError(message: serverDetailErrorMessage)
  414. case "CREDENTIAL_TOO_OLD_LOGIN_AGAIN": return AuthErrorUtils
  415. .requiresRecentLoginError(message: serverDetailErrorMessage)
  416. case "EMAIL_EXISTS": return AuthErrorUtils
  417. .emailAlreadyInUseError(email: nil)
  418. case "OPERATION_NOT_ALLOWED": return AuthErrorUtils
  419. .operationNotAllowedError(message: serverDetailErrorMessage)
  420. case "PASSWORD_LOGIN_DISABLED": return AuthErrorUtils
  421. .operationNotAllowedError(message: serverDetailErrorMessage)
  422. case "USER_DISABLED": return AuthErrorUtils
  423. .userDisabledError(message: serverDetailErrorMessage)
  424. case "INVALID_EMAIL": return AuthErrorUtils
  425. .invalidEmailError(message: serverDetailErrorMessage)
  426. case "EXPIRED_OOB_CODE": return AuthErrorUtils
  427. .expiredActionCodeError(message: serverDetailErrorMessage)
  428. case "INVALID_OOB_CODE": return AuthErrorUtils
  429. .invalidActionCodeError(message: serverDetailErrorMessage)
  430. case "INVALID_MESSAGE_PAYLOAD": return AuthErrorUtils
  431. .invalidMessagePayloadError(message: serverDetailErrorMessage)
  432. case "INVALID_SENDER": return AuthErrorUtils
  433. .invalidSenderError(message: serverDetailErrorMessage)
  434. case "INVALID_RECIPIENT_EMAIL": return AuthErrorUtils
  435. .invalidRecipientEmailError(message: serverDetailErrorMessage)
  436. case "WEAK_PASSWORD": return AuthErrorUtils
  437. .weakPasswordError(serverResponseReason: serverDetailErrorMessage)
  438. case "TOO_MANY_ATTEMPTS_TRY_LATER": return AuthErrorUtils
  439. .tooManyRequestsError(message: serverDetailErrorMessage)
  440. case "EMAIL_NOT_FOUND": return AuthErrorUtils
  441. .userNotFoundError(message: serverDetailErrorMessage)
  442. case "MISSING_EMAIL": return AuthErrorUtils
  443. .missingEmailError(message: serverDetailErrorMessage)
  444. case "MISSING_IOS_BUNDLE_ID": return AuthErrorUtils
  445. .missingIosBundleIDError(message: serverDetailErrorMessage)
  446. case "MISSING_ANDROID_PACKAGE_NAME": return AuthErrorUtils
  447. .missingAndroidPackageNameError(message: serverDetailErrorMessage)
  448. case "UNAUTHORIZED_DOMAIN": return AuthErrorUtils
  449. .unauthorizedDomainError(message: serverDetailErrorMessage)
  450. case "INVALID_CONTINUE_URI": return AuthErrorUtils
  451. .invalidContinueURIError(message: serverDetailErrorMessage)
  452. case "INVALID_PASSWORD": return AuthErrorUtils
  453. .wrongPasswordError(message: serverDetailErrorMessage)
  454. case "INVALID_IDP_RESPONSE": return AuthErrorUtils
  455. .invalidCredentialError(message: serverDetailErrorMessage)
  456. case "INVALID_PENDING_TOKEN": return AuthErrorUtils
  457. .invalidCredentialError(message: serverDetailErrorMessage)
  458. case "INVALID_CUSTOM_TOKEN": return AuthErrorUtils
  459. .invalidCustomTokenError(message: serverDetailErrorMessage)
  460. case "CREDENTIAL_MISMATCH": return AuthErrorUtils
  461. .customTokenMismatchError(message: serverDetailErrorMessage)
  462. case "INVALID_PHONE_NUMBER": return AuthErrorUtils
  463. .invalidPhoneNumberError(message: serverDetailErrorMessage)
  464. case "QUOTA_EXCEEDED": return AuthErrorUtils
  465. .quotaExceededError(message: serverDetailErrorMessage)
  466. case "APP_NOT_VERIFIED": return AuthErrorUtils
  467. .appNotVerifiedError(message: serverDetailErrorMessage)
  468. case "CAPTCHA_CHECK_FAILED": return AuthErrorUtils
  469. .captchaCheckFailedError(message: serverDetailErrorMessage)
  470. case "INVALID_APP_CREDENTIAL": return AuthErrorUtils
  471. .invalidAppCredential(message: serverDetailErrorMessage)
  472. case "MISSING_APP_CREDENTIAL": return AuthErrorUtils
  473. .missingAppCredential(message: serverDetailErrorMessage)
  474. case "INVALID_CODE": return AuthErrorUtils
  475. .invalidVerificationCodeError(message: serverDetailErrorMessage)
  476. case "INVALID_SESSION_INFO": return AuthErrorUtils
  477. .invalidVerificationIDError(message: serverDetailErrorMessage)
  478. case "SESSION_EXPIRED": return AuthErrorUtils
  479. .sessionExpiredError(message: serverDetailErrorMessage)
  480. case "ADMIN_ONLY_OPERATION": return AuthErrorUtils
  481. .error(code: AuthErrorCode.adminRestrictedOperation, message: serverDetailErrorMessage)
  482. case "BLOCKING_FUNCTION_ERROR_RESPONSE": return AuthErrorUtils
  483. .blockingCloudFunctionServerResponse(message: serverDetailErrorMessage)
  484. case "EMAIL_CHANGE_NEEDS_VERIFICATION": return AuthErrorUtils
  485. .error(code: AuthErrorCode.emailChangeNeedsVerification, message: serverDetailErrorMessage)
  486. case "INVALID_MFA_PENDING_CREDENTIAL": return AuthErrorUtils
  487. .error(code: AuthErrorCode.invalidMultiFactorSession, message: serverDetailErrorMessage)
  488. case "INVALID_PROVIDER_ID": return AuthErrorUtils
  489. .invalidProviderIDError(message: serverDetailErrorMessage)
  490. case "MFA_ENROLLMENT_NOT_FOUND": return AuthErrorUtils
  491. .error(code: AuthErrorCode.multiFactorInfoNotFound, message: serverDetailErrorMessage)
  492. case "MISSING_CLIENT_IDENTIFIER": return AuthErrorUtils
  493. .missingClientIdentifierError(message: serverDetailErrorMessage)
  494. case "MISSING_IOS_APP_TOKEN": return AuthErrorUtils
  495. .missingAppTokenError(underlyingError: nil)
  496. case "MISSING_MFA_ENROLLMENT_ID": return AuthErrorUtils
  497. .error(code: AuthErrorCode.missingMultiFactorInfo, message: serverDetailErrorMessage)
  498. case "MISSING_MFA_PENDING_CREDENTIAL": return AuthErrorUtils
  499. .error(code: AuthErrorCode.missingMultiFactorSession, message: serverDetailErrorMessage)
  500. case "MISSING_OR_INVALID_NONCE": return AuthErrorUtils
  501. .missingOrInvalidNonceError(message: serverDetailErrorMessage)
  502. case "SECOND_FACTOR_EXISTS": return AuthErrorUtils
  503. .error(code: AuthErrorCode.secondFactorAlreadyEnrolled, message: serverDetailErrorMessage)
  504. case "SECOND_FACTOR_LIMIT_EXCEEDED": return AuthErrorUtils
  505. .error(
  506. code: AuthErrorCode.maximumSecondFactorCountExceeded,
  507. message: serverDetailErrorMessage
  508. )
  509. case "TENANT_ID_MISMATCH": return AuthErrorUtils
  510. .tenantIDMismatchError()
  511. case "TOKEN_EXPIRED": return AuthErrorUtils
  512. .userTokenExpiredError(message: serverDetailErrorMessage)
  513. case "UNSUPPORTED_FIRST_FACTOR": return AuthErrorUtils
  514. .error(code: AuthErrorCode.unsupportedFirstFactor, message: serverDetailErrorMessage)
  515. case "UNSUPPORTED_TENANT_OPERATION": return AuthErrorUtils
  516. .unsupportedTenantOperationError()
  517. case "UNVERIFIED_EMAIL": return AuthErrorUtils
  518. .error(code: AuthErrorCode.unverifiedEmail, message: serverDetailErrorMessage)
  519. case "FEDERATED_USER_ID_ALREADY_LINKED":
  520. guard let verifyAssertion = response as? VerifyAssertionResponse else {
  521. return AuthErrorUtils.credentialAlreadyInUseError(
  522. message: serverDetailErrorMessage, credential: nil, email: nil
  523. )
  524. }
  525. let credential = OAuthCredential(withVerifyAssertionResponse: verifyAssertion)
  526. let email = verifyAssertion.email
  527. return AuthErrorUtils.credentialAlreadyInUseError(
  528. message: serverDetailErrorMessage, credential: credential, email: email
  529. )
  530. default:
  531. if let underlyingErrors = errorDictionary["errors"] as? [[String: String]] {
  532. for underlyingError in underlyingErrors {
  533. if let reason = underlyingError["reason"] {
  534. if reason.starts(with: "keyInvalid") {
  535. return AuthErrorUtils.invalidAPIKeyError()
  536. }
  537. if underlyingError["reason"] == "ipRefererBlocked" {
  538. return AuthErrorUtils.appNotAuthorizedError()
  539. }
  540. }
  541. }
  542. }
  543. }
  544. return nil
  545. }
  546. }