AuthBackend.swift 24 KB

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