AuthBackend.swift 24 KB

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