AuthBackend.swift 25 KB

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