AuthBackend.swift 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 AuthBackendProtocol: Sendable {
  24. func call<T: AuthRPCRequest>(with request: T) async throws -> T.Response
  25. }
  26. @available(iOS 13, tvOS 13, macOS 10.15, macCatalyst 13, watchOS 7, *)
  27. final class AuthBackend: AuthBackendProtocol {
  28. static func authUserAgent() -> String {
  29. return "FirebaseAuth.iOS/\(FirebaseVersion()) \(GTMFetcherStandardUserAgentString(nil))"
  30. }
  31. private let rpcIssuer: any AuthBackendRPCIssuerProtocol
  32. init(rpcIssuer: any AuthBackendRPCIssuerProtocol) {
  33. self.rpcIssuer = rpcIssuer
  34. }
  35. public func startPasskeyEnrollment(request: StartPasskeyEnrollmentRequest) async throws -> StartPasskeyEnrollmentResponse {
  36. guard #available(iOS 16.0, macOS 12.0, tvOS 16.0, *) else {
  37. throw AuthErrorUtils.error(code: AuthErrorCode.operationNotAllowed, message: "OS version is not supported for this action.")
  38. }
  39. let response = try await call(with: request) as StartPasskeyEnrollmentResponse
  40. return response
  41. }
  42. public func finalizePasskeyEnrollment(request: FinalizePasskeyEnrollmentRequest) async throws -> FinalizePasskeyEnrollmentResponse {
  43. guard #available(iOS 16.0, macOS 12.0, tvOS 16.0, *) else {
  44. throw AuthErrorUtils.error(code: AuthErrorCode.operationNotAllowed, message: "OS version is not supported for this action.")
  45. }
  46. let response = try await call(with: request) as FinalizePasskeyEnrollmentResponse
  47. return response
  48. }
  49. public func startPasskeySignIn(request: StartPasskeySignInRequest) async throws -> StartPasskeySignInResponse {
  50. guard #available(iOS 16.0, macOS 12.0, tvOS 16.0, *) else {
  51. throw AuthErrorUtils.error(code: AuthErrorCode.operationNotAllowed, message: "OS version is not supported for this action.")
  52. }
  53. let response = try await call(with: request) as StartPasskeySignInResponse
  54. return response
  55. }
  56. public func finalizePasskeySignIn(request: FinalizePasskeySignInRequest) async throws -> FinalizePasskeySignInResponse {
  57. guard #available(iOS 16.0, macOS 12.0, tvOS 16.0, *) else{
  58. throw AuthErrorUtils.error(code: AuthErrorCode.operationNotAllowed, message: "OS version is not supported for this action.")
  59. }
  60. let response = try await call(with: request) as FinalizePasskeySignInResponse
  61. return response
  62. }
  63. /// Calls the RPC using HTTP request.
  64. /// Possible error responses:
  65. /// * See FIRAuthInternalErrorCodeRPCRequestEncodingError
  66. /// * See FIRAuthInternalErrorCodeJSONSerializationError
  67. /// * See FIRAuthInternalErrorCodeNetworkError
  68. /// * See FIRAuthInternalErrorCodeUnexpectedErrorResponse
  69. /// * See FIRAuthInternalErrorCodeUnexpectedResponse
  70. /// * See FIRAuthInternalErrorCodeRPCResponseDecodingError
  71. /// - Parameter request: The request.
  72. /// - Returns: The response.
  73. func call<T: AuthRPCRequest>(with request: T) async throws -> T.Response {
  74. let response = try await callInternal(with: request)
  75. if let auth = request.requestConfiguration().auth,
  76. let mfaError = Self.generateMFAError(response: response, auth: auth) {
  77. throw mfaError
  78. } else if let error = Self.phoneCredentialInUse(response: response) {
  79. throw error
  80. } else {
  81. return response
  82. }
  83. }
  84. static func request(for url: URL,
  85. httpMethod: String,
  86. contentType: String,
  87. requestConfiguration: AuthRequestConfiguration) async -> URLRequest {
  88. // Kick off tasks for the async header values.
  89. async let heartbeatsHeaderValue = requestConfiguration.heartbeatLogger?.asyncHeaderValue()
  90. async let appCheckTokenHeaderValue = requestConfiguration.appCheck?
  91. .getToken(forcingRefresh: true)
  92. var request = URLRequest(url: url)
  93. request.setValue(contentType, forHTTPHeaderField: "Content-Type")
  94. let additionalFrameworkMarker = requestConfiguration.additionalFrameworkMarker
  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. request.httpMethod = httpMethod
  100. let preferredLocalizations = Bundle.main.preferredLocalizations
  101. if preferredLocalizations.count > 0 {
  102. request.setValue(preferredLocalizations.first, forHTTPHeaderField: "Accept-Language")
  103. }
  104. if let languageCode = requestConfiguration.languageCode,
  105. languageCode.count > 0 {
  106. request.setValue(languageCode, forHTTPHeaderField: "X-Firebase-Locale")
  107. }
  108. // Wait for the async header values.
  109. await request.setValue(heartbeatsHeaderValue, forHTTPHeaderField: "X-Firebase-Client")
  110. if let tokenResult = await appCheckTokenHeaderValue {
  111. if let error = tokenResult.error {
  112. AuthLog.logWarning(code: "I-AUT000018",
  113. message: "Error getting App Check token; using placeholder " +
  114. "token instead. Error: \(error)")
  115. }
  116. request.setValue(tokenResult.token, forHTTPHeaderField: "X-Firebase-AppCheck")
  117. }
  118. return request
  119. }
  120. private static func generateMFAError(response: AuthRPCResponse, auth: Auth) -> Error? {
  121. #if !os(iOS)
  122. return nil
  123. #else
  124. if let mfaResponse = response as? AuthMFAResponse,
  125. mfaResponse.idToken == nil,
  126. let enrollments = mfaResponse.mfaInfo {
  127. var info: [MultiFactorInfo] = []
  128. for enrollment in enrollments {
  129. // check which MFA factors are enabled.
  130. if let _ = enrollment.phoneInfo {
  131. info.append(PhoneMultiFactorInfo(proto: enrollment))
  132. } else if let _ = enrollment.totpInfo {
  133. info.append(TOTPMultiFactorInfo(proto: enrollment))
  134. } else {
  135. AuthLog.logError(code: "I-AUT000021", message: "Multifactor type is not supported")
  136. }
  137. }
  138. return AuthErrorUtils.secondFactorRequiredError(
  139. pendingCredential: mfaResponse.mfaPendingCredential,
  140. hints: info,
  141. auth: auth
  142. )
  143. } else {
  144. return nil
  145. }
  146. #endif // !os(iOS)
  147. }
  148. // Check whether or not the successful response is actually the special case phone
  149. // auth flow that returns a temporary proof and phone number.
  150. private static func phoneCredentialInUse(response: AuthRPCResponse) -> Error? {
  151. #if !os(iOS)
  152. return nil
  153. #else
  154. if let phoneAuthResponse = response as? VerifyPhoneNumberResponse,
  155. let phoneNumber = phoneAuthResponse.phoneNumber,
  156. phoneNumber.count > 0,
  157. let temporaryProof = phoneAuthResponse.temporaryProof,
  158. temporaryProof.count > 0 {
  159. let credential = PhoneAuthCredential(withTemporaryProof: temporaryProof,
  160. phoneNumber: phoneNumber,
  161. providerID: PhoneAuthProvider.id)
  162. return AuthErrorUtils.credentialAlreadyInUseError(message: nil,
  163. credential: credential,
  164. email: nil)
  165. } else {
  166. return nil
  167. }
  168. #endif // !os(iOS)
  169. }
  170. /// Calls the RPC using HTTP request.
  171. ///
  172. /// Possible error responses:
  173. /// * See FIRAuthInternalErrorCodeRPCRequestEncodingError
  174. /// * See FIRAuthInternalErrorCodeJSONSerializationError
  175. /// * See FIRAuthInternalErrorCodeNetworkError
  176. /// * See FIRAuthInternalErrorCodeUnexpectedErrorResponse
  177. /// * See FIRAuthInternalErrorCodeUnexpectedResponse
  178. /// * See FIRAuthInternalErrorCodeRPCResponseDecodingError
  179. /// - Parameter request: The request.
  180. /// - Returns: The response.
  181. fileprivate func callInternal<T: AuthRPCRequest>(with request: T) async throws -> T.Response {
  182. var bodyData: Data?
  183. if let postBody = request.unencodedHTTPRequestBody {
  184. #if DEBUG
  185. let JSONWritingOptions = JSONSerialization.WritingOptions.prettyPrinted
  186. #else
  187. let JSONWritingOptions = JSONSerialization.WritingOptions(rawValue: 0)
  188. #endif
  189. guard JSONSerialization.isValidJSONObject(postBody) else {
  190. throw AuthErrorUtils.JSONSerializationErrorForUnencodableType()
  191. }
  192. bodyData = try? JSONSerialization.data(
  193. withJSONObject: postBody,
  194. options: JSONWritingOptions
  195. )
  196. if bodyData == nil {
  197. // This is an untested case. This happens exclusively when there is an error in the
  198. // framework implementation of dataWithJSONObject:options:error:. This shouldn't normally
  199. // occur as isValidJSONObject: should return NO in any case we should encounter an error.
  200. throw AuthErrorUtils.JSONSerializationErrorForUnencodableType()
  201. }
  202. }
  203. let (data, error) = await rpcIssuer
  204. .asyncCallToURL(with: request, body: bodyData, contentType: "application/json")
  205. // If there is an error with no body data at all, then this must be a
  206. // network error.
  207. guard let data = data else {
  208. if let error = error {
  209. throw AuthErrorUtils.networkError(underlyingError: error)
  210. } else {
  211. // TODO: this was ignored before
  212. fatalError("Auth Internal error: RPC call didn't return data or an error.")
  213. }
  214. }
  215. // Try to decode the HTTP response data which may contain either a
  216. // successful response or error message.
  217. var dictionary: [String: AnyHashable]
  218. var rawDecode: Any
  219. do {
  220. rawDecode = try JSONSerialization.jsonObject(
  221. with: data, options: JSONSerialization.ReadingOptions.mutableLeaves
  222. )
  223. } catch let jsonError {
  224. if error != nil {
  225. // We have an error, but we couldn't decode the body, so we have no
  226. // additional information other than the raw response and the
  227. // original NSError (the jsonError is inferred by the error code
  228. // (AuthErrorCodeUnexpectedHTTPResponse, and is irrelevant.)
  229. throw AuthErrorUtils.unexpectedErrorResponse(data: data, underlyingError: error)
  230. } else {
  231. // This is supposed to be a "successful" response, but we couldn't
  232. // deserialize the body.
  233. throw AuthErrorUtils.unexpectedResponse(data: data, underlyingError: jsonError)
  234. }
  235. }
  236. guard let decodedDictionary = rawDecode as? [String: AnyHashable] else {
  237. if error != nil {
  238. throw AuthErrorUtils.unexpectedErrorResponse(deserializedResponse: rawDecode,
  239. underlyingError: error)
  240. } else {
  241. throw AuthErrorUtils.unexpectedResponse(deserializedResponse: rawDecode)
  242. }
  243. }
  244. dictionary = decodedDictionary
  245. let responseResult = Result {
  246. try T.Response(dictionary: dictionary)
  247. }
  248. // At this point we either have an error with successfully decoded
  249. // details in the body, or we have a response which must pass further
  250. // validation before we know it's truly successful. We deal with the
  251. // case where we have an error with successfully decoded error details
  252. // first:
  253. switch responseResult {
  254. case let .success(response):
  255. try propagateError(error, dictionary: dictionary, response: response)
  256. // In case returnIDPCredential of a verifyAssertion request is set to
  257. // @YES, the server may return a 200 with a response that may contain a
  258. // server error.
  259. if let verifyAssertionRequest = request as? VerifyAssertionRequest {
  260. if verifyAssertionRequest.returnIDPCredential {
  261. if let errorMessage = dictionary["errorMessage"] as? String {
  262. if let clientError = Self.clientError(
  263. withServerErrorMessage: errorMessage,
  264. errorDictionary: dictionary,
  265. response: response,
  266. error: error
  267. ) {
  268. throw clientError
  269. }
  270. }
  271. }
  272. }
  273. return response
  274. case let .failure(failure):
  275. try propagateError(error, dictionary: dictionary, response: nil)
  276. throw AuthErrorUtils
  277. .RPCResponseDecodingError(deserializedResponse: dictionary, underlyingError: failure)
  278. }
  279. }
  280. private func propagateError(_ error: Error?, dictionary: [String: AnyHashable],
  281. response: AuthRPCResponse?) throws {
  282. guard let error else {
  283. return
  284. }
  285. if let errorDictionary = dictionary["error"] as? [String: AnyHashable] {
  286. if let errorMessage = errorDictionary["message"] as? String {
  287. if let clientError = Self.clientError(
  288. withServerErrorMessage: errorMessage,
  289. errorDictionary: errorDictionary,
  290. response: response,
  291. error: error
  292. ) {
  293. throw clientError
  294. }
  295. }
  296. // Not a message we know, return the message directly.
  297. throw AuthErrorUtils.unexpectedErrorResponse(
  298. deserializedResponse: errorDictionary,
  299. underlyingError: error
  300. )
  301. }
  302. // No error message at all, return the decoded response.
  303. throw AuthErrorUtils
  304. .unexpectedErrorResponse(deserializedResponse: dictionary, underlyingError: error)
  305. }
  306. private static func splitStringAtFirstColon(_ input: String) -> (before: String, after: String) {
  307. guard let colonIndex = input.firstIndex(of: ":") else {
  308. return (input, "") // No colon, return original string before and empty after
  309. }
  310. let before = String(input.prefix(upTo: colonIndex))
  311. .trimmingCharacters(in: .whitespacesAndNewlines)
  312. let after = String(input.suffix(from: input.index(after: colonIndex)))
  313. .trimmingCharacters(in: .whitespacesAndNewlines)
  314. return (before, after.isEmpty ? "" : after) // Return empty after if it's empty
  315. }
  316. private static func clientError(withServerErrorMessage serverErrorMessage: String,
  317. errorDictionary: [String: Any],
  318. response: AuthRPCResponse?,
  319. error: Error?) -> Error? {
  320. let (shortErrorMessage, serverDetailErrorMessage) = splitStringAtFirstColon(serverErrorMessage)
  321. switch shortErrorMessage {
  322. case "USER_NOT_FOUND": return AuthErrorUtils
  323. .userNotFoundError(message: serverDetailErrorMessage)
  324. case "MISSING_CONTINUE_URI": return AuthErrorUtils
  325. .missingContinueURIError(message: serverDetailErrorMessage)
  326. // "INVALID_IDENTIFIER" can be returned by createAuthURI RPC. Considering email addresses are
  327. // currently the only identifiers, we surface the FIRAuthErrorCodeInvalidEmail error code in
  328. // this case.
  329. case "INVALID_IDENTIFIER": return AuthErrorUtils
  330. .invalidEmailError(message: serverDetailErrorMessage)
  331. case "INVALID_ID_TOKEN": return AuthErrorUtils
  332. .invalidUserTokenError(message: serverDetailErrorMessage)
  333. case "CREDENTIAL_TOO_OLD_LOGIN_AGAIN": return AuthErrorUtils
  334. .requiresRecentLoginError(message: serverDetailErrorMessage)
  335. case "EMAIL_EXISTS": return AuthErrorUtils
  336. .emailAlreadyInUseError(email: nil)
  337. case "OPERATION_NOT_ALLOWED": return AuthErrorUtils
  338. .operationNotAllowedError(message: serverDetailErrorMessage)
  339. case "PASSWORD_LOGIN_DISABLED": return AuthErrorUtils
  340. .operationNotAllowedError(message: serverDetailErrorMessage)
  341. case "USER_DISABLED": return AuthErrorUtils
  342. .userDisabledError(message: serverDetailErrorMessage)
  343. case "INVALID_EMAIL": return AuthErrorUtils
  344. .invalidEmailError(message: serverDetailErrorMessage)
  345. case "EXPIRED_OOB_CODE": return AuthErrorUtils
  346. .expiredActionCodeError(message: serverDetailErrorMessage)
  347. case "INVALID_OOB_CODE": return AuthErrorUtils
  348. .invalidActionCodeError(message: serverDetailErrorMessage)
  349. case "INVALID_MESSAGE_PAYLOAD": return AuthErrorUtils
  350. .invalidMessagePayloadError(message: serverDetailErrorMessage)
  351. case "INVALID_SENDER": return AuthErrorUtils
  352. .invalidSenderError(message: serverDetailErrorMessage)
  353. case "INVALID_RECIPIENT_EMAIL": return AuthErrorUtils
  354. .invalidRecipientEmailError(message: serverDetailErrorMessage)
  355. case "WEAK_PASSWORD": return AuthErrorUtils
  356. .weakPasswordError(serverResponseReason: serverDetailErrorMessage)
  357. case "TOO_MANY_ATTEMPTS_TRY_LATER": return AuthErrorUtils
  358. .tooManyRequestsError(message: serverDetailErrorMessage)
  359. case "EMAIL_NOT_FOUND": return AuthErrorUtils
  360. .userNotFoundError(message: serverDetailErrorMessage)
  361. case "MISSING_EMAIL": return AuthErrorUtils
  362. .missingEmailError(message: serverDetailErrorMessage)
  363. case "MISSING_IOS_BUNDLE_ID": return AuthErrorUtils
  364. .missingIosBundleIDError(message: serverDetailErrorMessage)
  365. case "MISSING_ANDROID_PACKAGE_NAME": return AuthErrorUtils
  366. .missingAndroidPackageNameError(message: serverDetailErrorMessage)
  367. case "UNAUTHORIZED_DOMAIN": return AuthErrorUtils
  368. .unauthorizedDomainError(message: serverDetailErrorMessage)
  369. case "INVALID_CONTINUE_URI": return AuthErrorUtils
  370. .invalidContinueURIError(message: serverDetailErrorMessage)
  371. case "INVALID_PASSWORD": return AuthErrorUtils
  372. .wrongPasswordError(message: serverDetailErrorMessage)
  373. case "INVALID_IDP_RESPONSE": return AuthErrorUtils
  374. .invalidCredentialError(message: serverDetailErrorMessage)
  375. case "INVALID_PENDING_TOKEN": return AuthErrorUtils
  376. .invalidCredentialError(message: serverDetailErrorMessage)
  377. case "INVALID_LOGIN_CREDENTIALS": return AuthErrorUtils
  378. .invalidCredentialError(message: serverDetailErrorMessage)
  379. case "INVALID_CUSTOM_TOKEN": return AuthErrorUtils
  380. .invalidCustomTokenError(message: serverDetailErrorMessage)
  381. case "CREDENTIAL_MISMATCH": return AuthErrorUtils
  382. .customTokenMismatchError(message: serverDetailErrorMessage)
  383. case "INVALID_PHONE_NUMBER": return AuthErrorUtils
  384. .invalidPhoneNumberError(message: serverDetailErrorMessage)
  385. case "QUOTA_EXCEEDED": return AuthErrorUtils
  386. .quotaExceededError(message: serverDetailErrorMessage)
  387. case "APP_NOT_VERIFIED": return AuthErrorUtils
  388. .appNotVerifiedError(message: serverDetailErrorMessage)
  389. case "CAPTCHA_CHECK_FAILED": return AuthErrorUtils
  390. .captchaCheckFailedError(message: serverDetailErrorMessage)
  391. case "INVALID_APP_CREDENTIAL": return AuthErrorUtils
  392. .invalidAppCredential(message: serverDetailErrorMessage)
  393. case "MISSING_APP_CREDENTIAL": return AuthErrorUtils
  394. .missingAppCredential(message: serverDetailErrorMessage)
  395. case "INVALID_CODE": return AuthErrorUtils
  396. .invalidVerificationCodeError(message: serverDetailErrorMessage)
  397. case "INVALID_HOSTING_LINK_DOMAIN": return AuthErrorUtils
  398. .invalidHostingLinkDomainError(message: serverDetailErrorMessage)
  399. case "INVALID_SESSION_INFO": return AuthErrorUtils
  400. .invalidVerificationIDError(message: serverDetailErrorMessage)
  401. case "SESSION_EXPIRED": return AuthErrorUtils
  402. .sessionExpiredError(message: serverDetailErrorMessage)
  403. case "ADMIN_ONLY_OPERATION": return AuthErrorUtils
  404. .error(code: AuthErrorCode.adminRestrictedOperation, message: serverDetailErrorMessage)
  405. case "BLOCKING_FUNCTION_ERROR_RESPONSE": return AuthErrorUtils
  406. .blockingCloudFunctionServerResponse(message: serverDetailErrorMessage)
  407. case "EMAIL_CHANGE_NEEDS_VERIFICATION": return AuthErrorUtils
  408. .error(code: AuthErrorCode.emailChangeNeedsVerification, message: serverDetailErrorMessage)
  409. case "INVALID_MFA_PENDING_CREDENTIAL": return AuthErrorUtils
  410. .error(code: AuthErrorCode.invalidMultiFactorSession, message: serverDetailErrorMessage)
  411. case "INVALID_PROVIDER_ID": return AuthErrorUtils
  412. .invalidProviderIDError(message: serverDetailErrorMessage)
  413. case "MFA_ENROLLMENT_NOT_FOUND": return AuthErrorUtils
  414. .error(code: AuthErrorCode.multiFactorInfoNotFound, message: serverDetailErrorMessage)
  415. case "MISSING_CLIENT_IDENTIFIER": return AuthErrorUtils
  416. .missingClientIdentifierError(message: serverDetailErrorMessage)
  417. case "MISSING_IOS_APP_TOKEN": return AuthErrorUtils
  418. .missingAppTokenError(underlyingError: nil)
  419. case "MISSING_MFA_ENROLLMENT_ID": return AuthErrorUtils
  420. .error(code: AuthErrorCode.missingMultiFactorInfo, message: serverDetailErrorMessage)
  421. case "MISSING_MFA_PENDING_CREDENTIAL": return AuthErrorUtils
  422. .error(code: AuthErrorCode.missingMultiFactorSession, message: serverDetailErrorMessage)
  423. case "MISSING_OR_INVALID_NONCE": return AuthErrorUtils
  424. .missingOrInvalidNonceError(message: serverDetailErrorMessage)
  425. case "SECOND_FACTOR_EXISTS": return AuthErrorUtils
  426. .error(code: AuthErrorCode.secondFactorAlreadyEnrolled, message: serverDetailErrorMessage)
  427. case "SECOND_FACTOR_LIMIT_EXCEEDED": return AuthErrorUtils
  428. .error(
  429. code: AuthErrorCode.maximumSecondFactorCountExceeded,
  430. message: serverDetailErrorMessage
  431. )
  432. case "TENANT_ID_MISMATCH": return AuthErrorUtils.tenantIDMismatchError()
  433. case "TOKEN_EXPIRED": return AuthErrorUtils
  434. .userTokenExpiredError(message: serverDetailErrorMessage)
  435. case "UNSUPPORTED_FIRST_FACTOR": return AuthErrorUtils
  436. .error(code: AuthErrorCode.unsupportedFirstFactor, message: serverDetailErrorMessage)
  437. case "UNSUPPORTED_TENANT_OPERATION": return AuthErrorUtils
  438. .unsupportedTenantOperationError()
  439. case "UNVERIFIED_EMAIL": return AuthErrorUtils
  440. .error(code: AuthErrorCode.unverifiedEmail, message: serverDetailErrorMessage)
  441. case "FEDERATED_USER_ID_ALREADY_LINKED":
  442. guard let verifyAssertion = response as? VerifyAssertionResponse else {
  443. return AuthErrorUtils.credentialAlreadyInUseError(
  444. message: serverDetailErrorMessage, credential: nil, email: nil
  445. )
  446. }
  447. let credential = OAuthCredential(withVerifyAssertionResponse: verifyAssertion)
  448. let email = verifyAssertion.email
  449. return AuthErrorUtils.credentialAlreadyInUseError(
  450. message: serverDetailErrorMessage, credential: credential, email: email
  451. )
  452. default:
  453. if let underlyingErrors = errorDictionary["errors"] as? [[String: String]] {
  454. for underlyingError in underlyingErrors {
  455. if let reason = underlyingError["reason"] {
  456. if reason.starts(with: "keyInvalid") {
  457. return AuthErrorUtils.invalidAPIKeyError()
  458. }
  459. if underlyingError["reason"] == "ipRefererBlocked" {
  460. return AuthErrorUtils.appNotAuthorizedError()
  461. }
  462. }
  463. }
  464. }
  465. }
  466. return nil
  467. }
  468. }