AuthBackend.swift 26 KB

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