AuthBackend.swift 25 KB

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