AuthBackend.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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. 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<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 asyncPostToURL<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. @objc(FIRAuthBackend2) public 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. /// Calls the RPC using HTTP POST.
  89. /// - Note:Possible error responses:
  90. /// @see FIRAuthInternalErrorCodeRPCRequestEncodingError // TODO FIX THESE
  91. /// @see FIRAuthInternalErrorCodeJSONSerializationError
  92. /// @see FIRAuthInternalErrorCodeNetworkError
  93. /// @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  94. /// @see FIRAuthInternalErrorCodeUnexpectedResponse
  95. /// @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  96. class func post<T: AuthRPCRequest>(with request: T,
  97. callback: @escaping ((T.Response?, Error?)
  98. -> Void)) {
  99. implementation().post(with: request, callback: callback)
  100. }
  101. // TODO: Why does this need to be public to be visible by unit tests?
  102. public class func request(withURL url: URL,
  103. contentType: String,
  104. requestConfiguration: AuthRequestConfiguration,
  105. completion: @escaping (URLRequest) -> Void) {
  106. var request = URLRequest(url: url)
  107. request.setValue(contentType, forHTTPHeaderField: "Content-Type")
  108. let additionalFrameworkMarker = requestConfiguration
  109. .additionalFrameworkMarker ?? "FirebaseCore-iOS"
  110. let clientVersion = "iOS/FirebaseSDK/\(FirebaseVersion())/\(additionalFrameworkMarker)"
  111. request.setValue(clientVersion, forHTTPHeaderField: "X-Client-Version")
  112. request.setValue(Bundle.main.bundleIdentifier, forHTTPHeaderField: "X-Ios-Bundle-Identifier")
  113. request.setValue(requestConfiguration.appID, forHTTPHeaderField: "X-Firebase-GMPID")
  114. // TODO: Enable for SPM. Can we directly call the Swift library?
  115. #if COCOAPODS
  116. if let heartbeatLogger = requestConfiguration.heartbeatLogger {
  117. request.setValue(
  118. FIRHeaderValueFromHeartbeatsPayload(heartbeatLogger.flushHeartbeatsIntoPayload()),
  119. forHTTPHeaderField: "X-Firebase-Client"
  120. )
  121. }
  122. #endif
  123. let preferredLocalizations = Bundle.main.preferredLocalizations
  124. if preferredLocalizations.count > 0 {
  125. request.setValue(preferredLocalizations.first, forHTTPHeaderField: "Accept-Language")
  126. }
  127. if let languageCode = requestConfiguration.languageCode,
  128. languageCode.count > 0 {
  129. request.setValue(languageCode, forHTTPHeaderField: "X-Firebase-Locale")
  130. }
  131. if let appCheck = requestConfiguration.appCheck {
  132. appCheck.getToken(forcingRefresh: false) { tokenResult in
  133. if let error = tokenResult.error {
  134. AuthLog.logWarning(code: "I-AUT000018",
  135. message: "Error getting App Check token; using placeholder " +
  136. "token instead. Error: \(error)")
  137. }
  138. request.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
  139. completion(request)
  140. }
  141. } else {
  142. completion(request)
  143. }
  144. }
  145. }
  146. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  147. protocol AuthBackendImplementation {
  148. func post<T: AuthRPCRequest>(with request: T,
  149. callback: @escaping ((T.Response?, Error?) -> Void))
  150. func post<T: AuthRPCRequest>(with request: T,
  151. response: T.Response,
  152. callback: @escaping (Error?) -> Void)
  153. }
  154. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  155. private class AuthBackendRPCImplementation: NSObject, AuthBackendImplementation {
  156. var rpcIssuer: AuthBackendRPCIssuer
  157. override init() {
  158. rpcIssuer = AuthBackendRPCIssuerImplementation()
  159. }
  160. /** @fn postWithRequest:response:callback:
  161. @brief Calls the RPC using HTTP POST.
  162. @remarks Possible error responses:
  163. @see FIRAuthInternalErrorCodeRPCRequestEncodingError
  164. @see FIRAuthInternalErrorCodeJSONSerializationError
  165. @see FIRAuthInternalErrorCodeNetworkError
  166. @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  167. @see FIRAuthInternalErrorCodeUnexpectedResponse
  168. @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  169. @param request The request.
  170. @param response The empty response to be filled.
  171. @param callback The callback for both success and failure.
  172. */
  173. fileprivate func post<T: AuthRPCRequest>(with request: T,
  174. callback: @escaping ((T.Response?, Error?)
  175. -> Void)) {
  176. let response = T.Response()
  177. post(with: request, response: response) { error in
  178. if let error = error {
  179. callback(nil, error)
  180. } else if let auth = request.requestConfiguration().auth,
  181. let mfaError = AuthBackendRPCImplementation
  182. .generateMFAError(response: response, auth: auth) {
  183. callback(nil, mfaError)
  184. } else if let error = AuthBackendRPCImplementation.phoneCredentialInUse(response: response) {
  185. callback(nil, error)
  186. } else {
  187. callback(response, nil)
  188. }
  189. }
  190. }
  191. #if os(iOS)
  192. private class func generateMFAError(response: AuthRPCResponse, auth: Auth) -> Error? {
  193. if let mfaResponse = response as? EmailLinkSignInResponse,
  194. mfaResponse.idToken == nil,
  195. let enrollments = mfaResponse.MFAInfo {
  196. var info: [MultiFactorInfo] = []
  197. for enrollment in enrollments {
  198. info.append(MultiFactorInfo(proto: enrollment))
  199. }
  200. return AuthErrorUtils.secondFactorRequiredError(
  201. pendingCredential: mfaResponse.MFAPendingCredential,
  202. hints: info,
  203. auth: auth
  204. )
  205. } else {
  206. return nil
  207. }
  208. }
  209. #else
  210. private class func generateMFAError(response: AuthRPCResponse, auth: Auth?) -> Error? {
  211. return nil
  212. }
  213. #endif
  214. #if os(iOS)
  215. // Check whether or not the successful response is actually the special case phone
  216. // auth flow that returns a temporary proof and phone number.
  217. private class func phoneCredentialInUse(response: AuthRPCResponse) -> Error? {
  218. if let phoneAuthResponse = response as? VerifyPhoneNumberResponse,
  219. let phoneNumber = phoneAuthResponse.phoneNumber,
  220. phoneNumber.count > 0,
  221. let temporaryProof = phoneAuthResponse.temporaryProof,
  222. temporaryProof.count > 0 {
  223. let credential = PhoneAuthCredential(withTemporaryProof: temporaryProof,
  224. phoneNumber: phoneNumber,
  225. providerID: PhoneAuthProvider.id)
  226. return AuthErrorUtils.credentialAlreadyInUseError(message: nil,
  227. credential: credential,
  228. email: nil)
  229. } else {
  230. return nil
  231. }
  232. }
  233. #else
  234. private class func phoneCredentialInUse(response: AuthRPCResponse) -> Error? {
  235. return nil
  236. }
  237. #endif
  238. /** @fn postWithRequest:response:callback:
  239. @brief Calls the RPC using HTTP POST.
  240. @remarks Possible error responses:
  241. @see FIRAuthInternalErrorCodeRPCRequestEncodingError
  242. @see FIRAuthInternalErrorCodeJSONSerializationError
  243. @see FIRAuthInternalErrorCodeNetworkError
  244. @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  245. @see FIRAuthInternalErrorCodeUnexpectedResponse
  246. @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  247. @param request The request.
  248. @param response The empty response to be filled.
  249. @param callback The callback for both success and failure.
  250. */
  251. fileprivate func post<T: AuthRPCRequest>(with request: T,
  252. response: T.Response,
  253. callback: @escaping (Error?) -> Void) {
  254. var bodyData: Data?
  255. if request.containsPostBody {
  256. do {
  257. // TODO: Can unencodedHTTPRequestBody ever throw?
  258. // They don't today, but there are a few fatalErrors that might better be implemented as
  259. // thrown errors.. Although perhaps the case of 'containsPostBody' returning false could
  260. // perhaps be modeled differently so that the failing unencodedHTTPRequestBody could only
  261. // be called when a body exists...
  262. let postBody = try request.unencodedHTTPRequestBody()
  263. var JSONWritingOptions: JSONSerialization.WritingOptions = .init(rawValue: 0)
  264. #if DEBUG
  265. JSONWritingOptions = JSONSerialization.WritingOptions.prettyPrinted
  266. #endif
  267. guard JSONSerialization.isValidJSONObject(postBody) else {
  268. callback(AuthErrorUtils.JSONSerializationErrorForUnencodableType())
  269. return
  270. }
  271. bodyData = try? JSONSerialization.data(
  272. withJSONObject: postBody,
  273. options: JSONWritingOptions
  274. )
  275. if bodyData == nil {
  276. // This is an untested case. This happens exclusively when there is an error in the
  277. // framework implementation of dataWithJSONObject:options:error:. This shouldn't normally
  278. // occur as isValidJSONObject: should return NO in any case we should encounter an error.
  279. callback(AuthErrorUtils.JSONSerializationErrorForUnencodableType())
  280. return
  281. }
  282. } catch {
  283. callback(AuthErrorUtils.RPCRequestEncodingError(underlyingError: error))
  284. return
  285. }
  286. }
  287. rpcIssuer
  288. .asyncPostToURL(with: request, body: bodyData, contentType: "application/json") {
  289. data, error in
  290. // If there is an error with no body data at all, then this must be a
  291. // network error.
  292. guard let data = data else {
  293. if let error = error {
  294. callback(AuthErrorUtils.networkError(underlyingError: error))
  295. return
  296. } else {
  297. // TODO: this was ignored before
  298. fatalError("Internal error")
  299. }
  300. }
  301. // Try to decode the HTTP response data which may contain either a
  302. // successful response or error message.
  303. var dictionary: [String: AnyHashable]
  304. do {
  305. let rawDecode = try JSONSerialization.jsonObject(with: data,
  306. options: JSONSerialization.ReadingOptions
  307. .mutableLeaves)
  308. guard let decodedDictionary = rawDecode as? [String: AnyHashable] else {
  309. if error != nil {
  310. callback(AuthErrorUtils.unexpectedErrorResponse(deserializedResponse: rawDecode,
  311. underlyingError: error))
  312. } else {
  313. callback(AuthErrorUtils.unexpectedResponse(deserializedResponse: rawDecode))
  314. }
  315. return
  316. }
  317. dictionary = decodedDictionary
  318. } catch let jsonError {
  319. if error != nil {
  320. // We have an error, but we couldn't decode the body, so we have no
  321. // additional information other than the raw response and the
  322. // original NSError (the jsonError is inferred by the error code
  323. // (AuthErrorCodeUnexpectedHTTPResponse, and is irrelevant.)
  324. callback(AuthErrorUtils.unexpectedErrorResponse(data: data, underlyingError: error))
  325. return
  326. } else {
  327. // This is supposed to be a "successful" response, but we couldn't
  328. // deserialize the body.
  329. callback(AuthErrorUtils.unexpectedResponse(data: data, underlyingError: jsonError))
  330. return
  331. }
  332. }
  333. // At this point we either have an error with successfully decoded
  334. // details in the body, or we have a response which must pass further
  335. // validation before we know it's truly successful. We deal with the
  336. // case where we have an error with successfully decoded error details
  337. // first:
  338. if error != nil {
  339. if let errorDictionary = dictionary["error"] as? [String: AnyHashable] {
  340. if let errorMessage = errorDictionary["message"] as? String {
  341. if let clientError = AuthBackendRPCImplementation.clientError(
  342. withServerErrorMessage: errorMessage,
  343. errorDictionary: errorDictionary,
  344. response: response,
  345. error: error
  346. ) {
  347. callback(clientError)
  348. return
  349. }
  350. }
  351. // Not a message we know, return the message directly.
  352. callback(AuthErrorUtils.unexpectedErrorResponse(
  353. deserializedResponse: errorDictionary,
  354. underlyingError: error
  355. ))
  356. return
  357. }
  358. // No error message at all, return the decoded response.
  359. callback(AuthErrorUtils
  360. .unexpectedErrorResponse(deserializedResponse: dictionary, underlyingError: error))
  361. return
  362. }
  363. // Finally, we try to populate the response object with the JSON
  364. // values.
  365. do {
  366. try response.setFields(dictionary: dictionary)
  367. } catch {
  368. callback(AuthErrorUtils
  369. .RPCResponseDecodingError(deserializedResponse: dictionary, underlyingError: error))
  370. return
  371. }
  372. // In case returnIDPCredential of a verifyAssertion request is set to
  373. // @YES, the server may return a 200 with a response that may contain a
  374. // server error.
  375. if let verifyAssertionRequest = request as? VerifyAssertionRequest {
  376. if verifyAssertionRequest.returnIDPCredential {
  377. if let errorMessage = dictionary["errorMessage"] as? String {
  378. let clientError = AuthBackendRPCImplementation.clientError(
  379. withServerErrorMessage: errorMessage,
  380. errorDictionary: dictionary,
  381. response: response,
  382. error: error
  383. )
  384. callback(clientError)
  385. return
  386. }
  387. }
  388. }
  389. callback(nil)
  390. }
  391. }
  392. private class func clientError(withServerErrorMessage serverErrorMessage: String,
  393. errorDictionary: [String: Any],
  394. response: AuthRPCResponse,
  395. error: Error?) -> Error? {
  396. let split = serverErrorMessage.split(separator: ":")
  397. let shortErrorMessage = split.first?.trimmingCharacters(in: .whitespacesAndNewlines)
  398. let serverDetailErrorMessage = String(split.count > 1 ? split[1] : "")
  399. .trimmingCharacters(in: .whitespacesAndNewlines)
  400. switch shortErrorMessage {
  401. case "USER_NOT_FOUND": return AuthErrorUtils
  402. .userNotFoundError(message: serverDetailErrorMessage)
  403. case "MISSING_CONTINUE_URI": return AuthErrorUtils
  404. .missingContinueURIError(message: serverDetailErrorMessage)
  405. // "INVALID_IDENTIFIER" can be returned by createAuthURI RPC. Considering email addresses are
  406. // currently the only identifiers, we surface the FIRAuthErrorCodeInvalidEmail error code in
  407. // this case.
  408. case "INVALID_IDENTIFIER": return AuthErrorUtils
  409. .invalidEmailError(message: serverDetailErrorMessage)
  410. case "INVALID_ID_TOKEN": return AuthErrorUtils
  411. .invalidUserTokenError(message: serverDetailErrorMessage)
  412. case "CREDENTIAL_TOO_OLD_LOGIN_AGAIN": return AuthErrorUtils
  413. .requiresRecentLoginError(message: serverDetailErrorMessage)
  414. case "EMAIL_EXISTS": return AuthErrorUtils
  415. .emailAlreadyInUseError(email: nil)
  416. case "OPERATION_NOT_ALLOWED": return AuthErrorUtils
  417. .operationNotAllowedError(message: serverDetailErrorMessage)
  418. case "PASSWORD_LOGIN_DISABLED": return AuthErrorUtils
  419. .operationNotAllowedError(message: serverDetailErrorMessage)
  420. case "USER_DISABLED": return AuthErrorUtils
  421. .userDisabledError(message: serverDetailErrorMessage)
  422. case "INVALID_EMAIL": return AuthErrorUtils
  423. .invalidEmailError(message: serverDetailErrorMessage)
  424. case "EXPIRED_OOB_CODE": return AuthErrorUtils
  425. .expiredActionCodeError(message: serverDetailErrorMessage)
  426. case "INVALID_OOB_CODE": return AuthErrorUtils
  427. .invalidActionCodeError(message: serverDetailErrorMessage)
  428. case "INVALID_MESSAGE_PAYLOAD": return AuthErrorUtils
  429. .invalidMessagePayloadError(message: serverDetailErrorMessage)
  430. case "INVALID_SENDER": return AuthErrorUtils
  431. .invalidSenderError(message: serverDetailErrorMessage)
  432. case "INVALID_RECIPIENT_EMAIL": return AuthErrorUtils
  433. .invalidRecipientEmailError(message: serverDetailErrorMessage)
  434. case "WEAK_PASSWORD": return AuthErrorUtils
  435. .weakPasswordError(serverResponseReason: serverDetailErrorMessage)
  436. case "TOO_MANY_ATTEMPTS_TRY_LATER": return AuthErrorUtils
  437. .tooManyRequestsError(message: serverDetailErrorMessage)
  438. case "EMAIL_NOT_FOUND": return AuthErrorUtils
  439. .userNotFoundError(message: serverDetailErrorMessage)
  440. case "MISSING_EMAIL": return AuthErrorUtils
  441. .missingEmailError(message: serverDetailErrorMessage)
  442. case "MISSING_IOS_BUNDLE_ID": return AuthErrorUtils
  443. .missingIosBundleIDError(message: serverDetailErrorMessage)
  444. case "MISSING_ANDROID_PACKAGE_NAME": return AuthErrorUtils
  445. .missingAndroidPackageNameError(message: serverDetailErrorMessage)
  446. case "UNAUTHORIZED_DOMAIN": return AuthErrorUtils
  447. .unauthorizedDomainError(message: serverDetailErrorMessage)
  448. case "INVALID_CONTINUE_URI": return AuthErrorUtils
  449. .invalidContinueURIError(message: serverDetailErrorMessage)
  450. case "INVALID_PASSWORD": return AuthErrorUtils
  451. .wrongPasswordError(message: serverDetailErrorMessage)
  452. case "INVALID_IDP_RESPONSE": return AuthErrorUtils
  453. .invalidCredentialError(message: serverDetailErrorMessage)
  454. case "INVALID_PENDING_TOKEN": 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. }