FIRAuthBackend.m 65 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  1. /*
  2. * Copyright 2017 Google
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #import "FirebaseAuth/Sources/Backend/FIRAuthBackend.h"
  17. #if SWIFT_PACKAGE
  18. @import GTMSessionFetcherCore;
  19. #else
  20. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  21. #import <GTMSessionFetcher/GTMSessionFetcherService.h>
  22. #endif
  23. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FirebaseAuth.h"
  24. #import "FirebaseAppCheck/Interop/FIRAppCheckInterop.h"
  25. #import "FirebaseAppCheck/Interop/FIRAppCheckTokenResultInterop.h"
  26. #import "FirebaseAuth/Sources/Auth/FIRAuthGlobalWorkQueue.h"
  27. #import "FirebaseAuth/Sources/Auth/FIRAuth_Internal.h"
  28. #import "FirebaseAuth/Sources/AuthProvider/OAuth/FIROAuthCredential_Internal.h"
  29. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIRequest.h"
  30. #import "FirebaseAuth/Sources/Backend/RPC/FIRCreateAuthURIResponse.h"
  31. #import "FirebaseAuth/Sources/Backend/RPC/FIRDeleteAccountRequest.h"
  32. #import "FirebaseAuth/Sources/Backend/RPC/FIRDeleteAccountResponse.h"
  33. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInRequest.h"
  34. #import "FirebaseAuth/Sources/Backend/RPC/FIREmailLinkSignInResponse.h"
  35. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoRequest.h"
  36. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetAccountInfoResponse.h"
  37. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeRequest.h"
  38. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetOOBConfirmationCodeResponse.h"
  39. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetProjectConfigRequest.h"
  40. #import "FirebaseAuth/Sources/Backend/RPC/FIRGetProjectConfigResponse.h"
  41. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordRequest.h"
  42. #import "FirebaseAuth/Sources/Backend/RPC/FIRResetPasswordResponse.h"
  43. #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenRequest.h"
  44. #import "FirebaseAuth/Sources/Backend/RPC/FIRSecureTokenResponse.h"
  45. #import "FirebaseAuth/Sources/Backend/RPC/FIRSendVerificationCodeRequest.h"
  46. #import "FirebaseAuth/Sources/Backend/RPC/FIRSendVerificationCodeResponse.h"
  47. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoRequest.h"
  48. #import "FirebaseAuth/Sources/Backend/RPC/FIRSetAccountInfoResponse.h"
  49. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignInWithGameCenterRequest.h"
  50. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignInWithGameCenterResponse.h"
  51. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserRequest.h"
  52. #import "FirebaseAuth/Sources/Backend/RPC/FIRSignUpNewUserResponse.h"
  53. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionRequest.h"
  54. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyAssertionResponse.h"
  55. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyClientRequest.h"
  56. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyClientResponse.h"
  57. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenRequest.h"
  58. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyCustomTokenResponse.h"
  59. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordRequest.h"
  60. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPasswordResponse.h"
  61. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberRequest.h"
  62. #import "FirebaseAuth/Sources/Backend/RPC/FIRVerifyPhoneNumberResponse.h"
  63. #import "FirebaseAuth/Sources/Utilities/FIRAuthErrorUtils.h"
  64. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  65. #if TARGET_OS_IOS
  66. #import "FirebaseAuth/Sources/Public/FirebaseAuth/FIRPhoneAuthProvider.h"
  67. #import "FirebaseAuth/Sources/AuthProvider/Phone/FIRPhoneAuthCredential_Internal.h"
  68. #import "FirebaseAuth/Sources/MultiFactor/Phone/FIRPhoneMultiFactorInfo+Internal.h"
  69. #endif
  70. NS_ASSUME_NONNULL_BEGIN
  71. /** @var kClientVersionHeader
  72. @brief HTTP header name for the client version.
  73. */
  74. static NSString *const kClientVersionHeader = @"X-Client-Version";
  75. /** @var kIosBundleIdentifierHeader
  76. @brief HTTP header name for iOS bundle ID.
  77. */
  78. static NSString *const kIosBundleIdentifierHeader = @"X-Ios-Bundle-Identifier";
  79. /** @var kFirebaseLocalHeader
  80. @brief HTTP header name for the firebase locale.
  81. */
  82. static NSString *const kFirebaseLocalHeader = @"X-Firebase-Locale";
  83. /** @var kFirebaseAppIDHeader
  84. @brief HTTP header name for the Firebase app ID.
  85. */
  86. static NSString *const kFirebaseAppIDHeader = @"X-Firebase-GMPID";
  87. /** @var kFirebaseHeartbeatHeader
  88. @brief HTTP header name for a Firebase heartbeats payload.
  89. */
  90. static NSString *const kFirebaseHeartbeatHeader = @"X-Firebase-Client";
  91. /** @var kFirebaseAuthCoreFrameworkMarker
  92. @brief The marker in the HTTP header that indicates the request comes from Firebase Auth Core.
  93. */
  94. static NSString *const kFirebaseAuthCoreFrameworkMarker = @"FirebaseCore-iOS";
  95. /** @var kJSONContentType
  96. @brief The value of the HTTP content-type header for JSON payloads.
  97. */
  98. static NSString *const kJSONContentType = @"application/json";
  99. /** @var kErrorDataKey
  100. @brief Key for error data in NSError returned by @c GTMSessionFetcher.
  101. */
  102. static NSString *const kErrorDataKey = @"data";
  103. /** @var kErrorKey
  104. @brief The key for the "error" value in JSON responses from the server.
  105. */
  106. static NSString *const kErrorKey = @"error";
  107. /** @var kErrorsKey
  108. @brief The key for the "errors" value in JSON responses from the server.
  109. */
  110. static NSString *const kErrorsKey = @"errors";
  111. /** @var kReasonKey
  112. @brief The key for the "reason" value in JSON responses from the server.
  113. */
  114. static NSString *const kReasonKey = @"reason";
  115. /** @var kInvalidKeyReasonValue
  116. @brief The value for the "reason" key indicating an invalid API Key was received by the server.
  117. */
  118. static NSString *const kInvalidKeyReasonValue = @"keyInvalid";
  119. /** @var kAppNotAuthorizedReasonValue
  120. @brief The value for the "reason" key indicating the App is not authorized to use Firebase
  121. Authentication.
  122. */
  123. static NSString *const kAppNotAuthorizedReasonValue = @"ipRefererBlocked";
  124. /** @var kErrorMessageKey
  125. @brief The key for an error's "message" value in JSON responses from the server.
  126. */
  127. static NSString *const kErrorMessageKey = @"message";
  128. /** @var kReturnIDPCredentialErrorMessageKey
  129. @brief The key for "errorMessage" value in JSON responses from the server, In case
  130. returnIDPCredential of a verifyAssertion request is set to @YES.
  131. */
  132. static NSString *const kReturnIDPCredentialErrorMessageKey = @"errorMessage";
  133. /** @var kUserNotFoundErrorMessage
  134. @brief This is the error message returned when the user is not found, which means the user
  135. account has been deleted given the token was once valid.
  136. */
  137. static NSString *const kUserNotFoundErrorMessage = @"USER_NOT_FOUND";
  138. /** @var kUserDeletedErrorMessage
  139. @brief This is the error message the server will respond with if the user entered an invalid
  140. email address.
  141. */
  142. static NSString *const kUserDeletedErrorMessage = @"EMAIL_NOT_FOUND";
  143. /** @var kInvalidLocalIDErrorMessage
  144. @brief This is the error message the server responds with if the user local id in the id token
  145. does not exit.
  146. */
  147. static NSString *const kInvalidLocalIDErrorMessage = @"INVALID_LOCAL_ID";
  148. /** @var kUserTokenExpiredErrorMessage
  149. @brief The error returned by the server if the token issue time is older than the account's
  150. valid_since time.
  151. */
  152. static NSString *const kUserTokenExpiredErrorMessage = @"TOKEN_EXPIRED";
  153. /** @var kTooManyRequestsErrorMessage
  154. @brief This is the error message the server will respond with if too many requests were made to
  155. a server method.
  156. */
  157. static NSString *const kTooManyRequestsErrorMessage = @"TOO_MANY_ATTEMPTS_TRY_LATER";
  158. /** @var kInvalidCustomTokenErrorMessage
  159. @brief This is the error message the server will respond with if there is a validation error
  160. with the custom token.
  161. */
  162. static NSString *const kInvalidCustomTokenErrorMessage = @"INVALID_CUSTOM_TOKEN";
  163. /** @var kCustomTokenMismatch
  164. @brief This is the error message the server will respond with if the service account and API key
  165. belong to different projects.
  166. */
  167. static NSString *const kCustomTokenMismatch = @"CREDENTIAL_MISMATCH";
  168. /** @var kInvalidCredentialErrorMessage
  169. @brief This is the error message the server responds with if the IDP token or requestUri is
  170. invalid.
  171. */
  172. static NSString *const kInvalidCredentialErrorMessage = @"INVALID_IDP_RESPONSE";
  173. /** @var kUserDisabledErrorMessage
  174. @brief The error returned by the server if the user account is diabled.
  175. */
  176. static NSString *const kUserDisabledErrorMessage = @"USER_DISABLED";
  177. /** @var kOperationNotAllowedErrorMessage
  178. @brief This is the error message the server will respond with if Admin disables IDP specified by
  179. provider.
  180. */
  181. static NSString *const kOperationNotAllowedErrorMessage = @"OPERATION_NOT_ALLOWED";
  182. /** @var kPasswordLoginDisabledErrorMessage
  183. @brief This is the error message the server responds with if password login is disabled.
  184. */
  185. static NSString *const kPasswordLoginDisabledErrorMessage = @"PASSWORD_LOGIN_DISABLED";
  186. /** @var kEmailAlreadyInUseErrorMessage
  187. @brief This is the error message the server responds with if the email address already exists.
  188. */
  189. static NSString *const kEmailAlreadyInUseErrorMessage = @"EMAIL_EXISTS";
  190. /** @var kInvalidEmailErrorMessage
  191. @brief The error returned by the server if the email is invalid.
  192. */
  193. static NSString *const kInvalidEmailErrorMessage = @"INVALID_EMAIL";
  194. /** @var kInvalidIdentifierErrorMessage
  195. @brief The error returned by the server if the identifier is invalid.
  196. */
  197. static NSString *const kInvalidIdentifierErrorMessage = @"INVALID_IDENTIFIER";
  198. /** @var kWrongPasswordErrorMessage
  199. @brief This is the error message the server will respond with if the user entered a wrong
  200. password.
  201. */
  202. static NSString *const kWrongPasswordErrorMessage = @"INVALID_PASSWORD";
  203. /** @var kCredentialTooOldErrorMessage
  204. @brief This is the error message the server responds with if account change is attempted 5
  205. minutes after signing in.
  206. */
  207. static NSString *const kCredentialTooOldErrorMessage = @"CREDENTIAL_TOO_OLD_LOGIN_AGAIN";
  208. /** @var kFederatedUserIDAlreadyLinkedMessage
  209. @brief This is the error message the server will respond with if the federated user ID has been
  210. already linked with another account.
  211. */
  212. static NSString *const kFederatedUserIDAlreadyLinkedMessage = @"FEDERATED_USER_ID_ALREADY_LINKED";
  213. /** @var kInvalidUserTokenErrorMessage
  214. @brief This is the error message the server responds with if user's saved auth credential is
  215. invalid, and the user needs to sign in again.
  216. */
  217. static NSString *const kInvalidUserTokenErrorMessage = @"INVALID_ID_TOKEN";
  218. /** @var kWeakPasswordErrorMessagePrefix
  219. @brief This is the prefix for the error message the server responds with if user's new password
  220. to be set is too weak.
  221. */
  222. static NSString *const kWeakPasswordErrorMessagePrefix = @"WEAK_PASSWORD";
  223. /** @var kExpiredActionCodeErrorMessage
  224. @brief This is the error message the server will respond with if the action code is expired.
  225. */
  226. static NSString *const kExpiredActionCodeErrorMessage = @"EXPIRED_OOB_CODE";
  227. /** @var kInvalidActionCodeErrorMessage
  228. @brief This is the error message the server will respond with if the action code is invalid.
  229. */
  230. static NSString *const kInvalidActionCodeErrorMessage = @"INVALID_OOB_CODE";
  231. /** @var kMissingEmailErrorMessage
  232. @brief This is the error message the server will respond with if the email address is missing
  233. during a "send password reset email" attempt.
  234. */
  235. static NSString *const kMissingEmailErrorMessage = @"MISSING_EMAIL";
  236. /** @var kInvalidSenderEmailErrorMessage
  237. @brief This is the error message the server will respond with if the sender email is invalid
  238. during a "send password reset email" attempt.
  239. */
  240. static NSString *const kInvalidSenderEmailErrorMessage = @"INVALID_SENDER";
  241. /** @var kInvalidMessagePayloadErrorMessage
  242. @brief This is the error message the server will respond with if there are invalid parameters in
  243. the payload during a "send password reset email" attempt.
  244. */
  245. static NSString *const kInvalidMessagePayloadErrorMessage = @"INVALID_MESSAGE_PAYLOAD";
  246. /** @var kInvalidRecipientEmailErrorMessage
  247. @brief This is the error message the server will respond with if the recipient email is invalid.
  248. */
  249. static NSString *const kInvalidRecipientEmailErrorMessage = @"INVALID_RECIPIENT_EMAIL";
  250. /** @var kMissingIosBundleIDErrorMessage
  251. @brief This is the error message the server will respond with if iOS bundle ID is missing but
  252. the iOS App store ID is provided.
  253. */
  254. static NSString *const kMissingIosBundleIDErrorMessage = @"MISSING_IOS_BUNDLE_ID";
  255. /** @var kMissingAndroidPackageNameErrorMessage
  256. @brief This is the error message the server will respond with if Android Package Name is missing
  257. but the flag indicating the app should be installed is set to true.
  258. */
  259. static NSString *const kMissingAndroidPackageNameErrorMessage = @"MISSING_ANDROID_PACKAGE_NAME";
  260. /** @var kUnauthorizedDomainErrorMessage
  261. @brief This is the error message the server will respond with if the domain of the continue URL
  262. specified is not allowlisted in the Firebase console.
  263. */
  264. static NSString *const kUnauthorizedDomainErrorMessage = @"UNAUTHORIZED_DOMAIN";
  265. /** @var kInvalidProviderIDErrorMessage
  266. @brief This is the error message the server will respond with if the provider id given for the
  267. web operation is invalid.
  268. */
  269. static NSString *const kInvalidProviderIDErrorMessage = @"INVALID_PROVIDER_ID";
  270. /** @var kInvalidDynamicLinkDomainErrorMessage
  271. @brief This is the error message the server will respond with if the dynamic link domain
  272. provided in the request is invalid.
  273. */
  274. static NSString *const kInvalidDynamicLinkDomainErrorMessage = @"INVALID_DYNAMIC_LINK_DOMAIN";
  275. /** @var kInvalidContinueURIErrorMessage
  276. @brief This is the error message the server will respond with if the continue URL provided in
  277. the request is invalid.
  278. */
  279. static NSString *const kInvalidContinueURIErrorMessage = @"INVALID_CONTINUE_URI";
  280. /** @var kMissingContinueURIErrorMessage
  281. @brief This is the error message the server will respond with if there was no continue URI
  282. present in a request that required one.
  283. */
  284. static NSString *const kMissingContinueURIErrorMessage = @"MISSING_CONTINUE_URI";
  285. /** @var kInvalidPhoneNumberErrorMessage
  286. @brief This is the error message the server will respond with if an incorrectly formatted phone
  287. number is provided.
  288. */
  289. static NSString *const kInvalidPhoneNumberErrorMessage = @"INVALID_PHONE_NUMBER";
  290. /** @var kInvalidVerificationCodeErrorMessage
  291. @brief This is the error message the server will respond with if an invalid verification code is
  292. provided.
  293. */
  294. static NSString *const kInvalidVerificationCodeErrorMessage = @"INVALID_CODE";
  295. /** @var kInvalidSessionInfoErrorMessage
  296. @brief This is the error message the server will respond with if an invalid session info
  297. (verification ID) is provided.
  298. */
  299. static NSString *const kInvalidSessionInfoErrorMessage = @"INVALID_SESSION_INFO";
  300. /** @var kSessionExpiredErrorMessage
  301. @brief This is the error message the server will respond with if the SMS code has expired before
  302. it is used.
  303. */
  304. static NSString *const kSessionExpiredErrorMessage = @"SESSION_EXPIRED";
  305. /** @var kMissingOrInvalidNonceErrorMessage
  306. @brief This is the error message the server will respond with if the nonce is missing or
  307. invalid.
  308. */
  309. static NSString *const kMissingOrInvalidNonceErrorMessage = @"MISSING_OR_INVALID_NONCE";
  310. /** @var kMissingAppTokenErrorMessage
  311. @brief This is the error message the server will respond with if the APNS token is missing in a
  312. verifyClient request.
  313. */
  314. static NSString *const kMissingAppTokenErrorMessage = @"MISSING_IOS_APP_TOKEN";
  315. /** @var kMissingAppCredentialErrorMessage
  316. @brief This is the error message the server will respond with if the app token is missing in a
  317. sendVerificationCode request.
  318. */
  319. static NSString *const kMissingAppCredentialErrorMessage = @"MISSING_APP_CREDENTIAL";
  320. /** @var kInvalidAppCredentialErrorMessage
  321. @brief This is the error message the server will respond with if the app credential in a
  322. sendVerificationCode request is invalid.
  323. */
  324. static NSString *const kInvalidAppCredentialErrorMessage = @"INVALID_APP_CREDENTIAL";
  325. /** @var kQuoutaExceededErrorMessage
  326. @brief This is the error message the server will respond with if the quota for SMS text messages
  327. has been exceeded for the project.
  328. */
  329. static NSString *const kQuoutaExceededErrorMessage = @"QUOTA_EXCEEDED";
  330. /** @var kAppNotVerifiedErrorMessage
  331. @brief This is the error message the server will respond with if Firebase could not verify the
  332. app during a phone authentication flow.
  333. */
  334. static NSString *const kAppNotVerifiedErrorMessage = @"APP_NOT_VERIFIED";
  335. /** @var kMissingClientIdentifier
  336. @brief This is the error message the server will respond with if Firebase could not verify the
  337. app during a phone authentication flow when a real phone number is used and app verification
  338. is disabled for testing.
  339. */
  340. static NSString *const kMissingClientIdentifier = @"MISSING_CLIENT_IDENTIFIER";
  341. /** @var kCaptchaCheckFailedErrorMessage
  342. @brief This is the error message the server will respond with if the reCAPTCHA token provided is
  343. invalid.
  344. */
  345. static NSString *const kCaptchaCheckFailedErrorMessage = @"CAPTCHA_CHECK_FAILED";
  346. /** @var kTenantIDMismatch
  347. @brief This is the error message the server will respond with if the tenant id mismatches.
  348. */
  349. static NSString *const kTenantIDMismatch = @"TENANT_ID_MISMATCH";
  350. /** @var kUnsupportedTenantOperation
  351. @brief This is the error message the server will respond with if the operation does not support
  352. multi-tenant.
  353. */
  354. static NSString *const kUnsupportedTenantOperation = @"UNSUPPORTED_TENANT_OPERATION";
  355. /** @var kMissingMFAPendingCredentialErrorMessage
  356. @brief This is the error message the server will respond with if the MFA pending credential is
  357. missing.
  358. */
  359. static NSString *const kMissingMFAPendingCredentialErrorMessage = @"MISSING_MFA_PENDING_CREDENTIAL";
  360. /** @var kMissingMFAEnrollmentIDErrorMessage
  361. @brief This is the error message the server will respond with if the MFA enrollment ID is missing.
  362. */
  363. static NSString *const kMissingMFAEnrollmentIDErrorMessage = @"MISSING_MFA_ENROLLMENT_ID";
  364. /** @var kInvalidMFAPendingCredentialErrorMessage
  365. @brief This is the error message the server will respond with if the MFA pending credential is
  366. invalid.
  367. */
  368. static NSString *const kInvalidMFAPendingCredentialErrorMessage = @"INVALID_MFA_PENDING_CREDENTIAL";
  369. /** @var kMFAEnrollmentNotFoundErrorMessage
  370. @brief This is the error message the server will respond with if the MFA enrollment info is not
  371. found.
  372. */
  373. static NSString *const kMFAEnrollmentNotFoundErrorMessage = @"MFA_ENROLLMENT_NOT_FOUND";
  374. /** @var kAdminOnlyOperationErrorMessage
  375. @brief This is the error message the server will respond with if the operation is admin only.
  376. */
  377. static NSString *const kAdminOnlyOperationErrorMessage = @"ADMIN_ONLY_OPERATION";
  378. /** @var kUnverifiedEmailErrorMessage
  379. @brief This is the error message the server will respond with if the email is unverified.
  380. */
  381. static NSString *const kUnverifiedEmailErrorMessage = @"UNVERIFIED_EMAIL";
  382. /** @var kSecondFactorExistsErrorMessage
  383. @brief This is the error message the server will respond with if the second factor already exsists.
  384. */
  385. static NSString *const kSecondFactorExistsErrorMessage = @"SECOND_FACTOR_EXISTS";
  386. /** @var kSecondFactorLimitExceededErrorMessage
  387. @brief This is the error message the server will respond with if the number of second factor
  388. reaches the limit.
  389. */
  390. static NSString *const kSecondFactorLimitExceededErrorMessage = @"SECOND_FACTOR_LIMIT_EXCEEDED";
  391. /** @var kUnsupportedFirstFactorErrorMessage
  392. @brief This is the error message the server will respond with if the first factor doesn't support
  393. MFA.
  394. */
  395. static NSString *const kUnsupportedFirstFactorErrorMessage = @"UNSUPPORTED_FIRST_FACTOR";
  396. /** @var kBlockingCloudFunctionErrorResponse
  397. @brief This is the error message blocking Cloud Functions.
  398. */
  399. static NSString *const kBlockingCloudFunctionErrorResponse = @"BLOCKING_FUNCTION_ERROR_RESPONSE";
  400. /** @var kEmailChangeNeedsVerificationErrorMessage
  401. @brief This is the error message the server will respond with if changing an unverified email.
  402. */
  403. static NSString *const kEmailChangeNeedsVerificationErrorMessage =
  404. @"EMAIL_CHANGE_NEEDS_VERIFICATION";
  405. /** @var kInvalidPendingToken
  406. @brief Generic IDP error codes.
  407. */
  408. static NSString *const kInvalidPendingToken = @"INVALID_PENDING_TOKEN";
  409. /** @var gBackendImplementation
  410. @brief The singleton FIRAuthBackendImplementation instance to use.
  411. */
  412. static id<FIRAuthBackendImplementation> gBackendImplementation;
  413. /** @class FIRAuthBackendRPCImplementation
  414. @brief The default RPC-based backend implementation.
  415. */
  416. @interface FIRAuthBackendRPCImplementation : NSObject <FIRAuthBackendImplementation>
  417. /** @property RPCIssuer
  418. @brief An instance of FIRAuthBackendRPCIssuer for making RPC requests. Allows the RPC
  419. requests/responses to be easily faked.
  420. */
  421. @property(nonatomic, strong) id<FIRAuthBackendRPCIssuer> RPCIssuer;
  422. @end
  423. @implementation FIRAuthBackend
  424. + (id<FIRAuthBackendImplementation>)implementation {
  425. if (!gBackendImplementation) {
  426. gBackendImplementation = [[FIRAuthBackendRPCImplementation alloc] init];
  427. }
  428. return gBackendImplementation;
  429. }
  430. + (void)setBackendImplementation:(id<FIRAuthBackendImplementation>)backendImplementation {
  431. gBackendImplementation = backendImplementation;
  432. }
  433. + (void)setDefaultBackendImplementationWithRPCIssuer:
  434. (nullable id<FIRAuthBackendRPCIssuer>)RPCIssuer {
  435. FIRAuthBackendRPCImplementation *defaultImplementation =
  436. [[FIRAuthBackendRPCImplementation alloc] init];
  437. if (RPCIssuer) {
  438. defaultImplementation.RPCIssuer = RPCIssuer;
  439. }
  440. gBackendImplementation = defaultImplementation;
  441. }
  442. + (void)createAuthURI:(FIRCreateAuthURIRequest *)request
  443. callback:(FIRCreateAuthURIResponseCallback)callback {
  444. [[self implementation] createAuthURI:request callback:callback];
  445. }
  446. + (void)getAccountInfo:(FIRGetAccountInfoRequest *)request
  447. callback:(FIRGetAccountInfoResponseCallback)callback {
  448. [[self implementation] getAccountInfo:request callback:callback];
  449. }
  450. + (void)getProjectConfig:(FIRGetProjectConfigRequest *)request
  451. callback:(FIRGetProjectConfigResponseCallback)callback {
  452. [[self implementation] getProjectConfig:request callback:callback];
  453. }
  454. + (void)setAccountInfo:(FIRSetAccountInfoRequest *)request
  455. callback:(FIRSetAccountInfoResponseCallback)callback {
  456. [[self implementation] setAccountInfo:request callback:callback];
  457. }
  458. + (void)verifyAssertion:(FIRVerifyAssertionRequest *)request
  459. callback:(FIRVerifyAssertionResponseCallback)callback {
  460. [[self implementation] verifyAssertion:request callback:callback];
  461. }
  462. + (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request
  463. callback:(FIRVerifyCustomTokenResponseCallback)callback {
  464. [[self implementation] verifyCustomToken:request callback:callback];
  465. }
  466. + (void)verifyPassword:(FIRVerifyPasswordRequest *)request
  467. callback:(FIRVerifyPasswordResponseCallback)callback {
  468. [[self implementation] verifyPassword:request callback:callback];
  469. }
  470. + (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request
  471. callback:(FIREmailLinkSigninResponseCallback)callback {
  472. [[self implementation] emailLinkSignin:request callback:callback];
  473. }
  474. + (void)secureToken:(FIRSecureTokenRequest *)request
  475. callback:(FIRSecureTokenResponseCallback)callback {
  476. [[self implementation] secureToken:request callback:callback];
  477. }
  478. + (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request
  479. callback:(FIRGetOOBConfirmationCodeResponseCallback)callback {
  480. [[self implementation] getOOBConfirmationCode:request callback:callback];
  481. }
  482. + (void)signUpNewUser:(FIRSignUpNewUserRequest *)request
  483. callback:(FIRSignupNewUserCallback)callback {
  484. [[self implementation] signUpNewUser:request callback:callback];
  485. }
  486. + (void)deleteAccount:(FIRDeleteAccountRequest *)request callback:(FIRDeleteCallBack)callback {
  487. [[self implementation] deleteAccount:request callback:callback];
  488. }
  489. + (void)signInWithGameCenter:(FIRSignInWithGameCenterRequest *)request
  490. callback:(FIRSignInWithGameCenterResponseCallback)callback {
  491. [[self implementation] signInWithGameCenter:request callback:callback];
  492. }
  493. #if TARGET_OS_IOS
  494. + (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request
  495. callback:(FIRSendVerificationCodeResponseCallback)callback {
  496. [[self implementation] sendVerificationCode:request callback:callback];
  497. }
  498. + (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request
  499. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  500. [[self implementation] verifyPhoneNumber:request callback:callback];
  501. }
  502. + (void)verifyClient:(id)request callback:(FIRVerifyClientResponseCallback)callback {
  503. [[self implementation] verifyClient:request callback:callback];
  504. }
  505. #endif
  506. + (void)resetPassword:(FIRResetPasswordRequest *)request
  507. callback:(FIRResetPasswordCallback)callback {
  508. [[self implementation] resetPassword:request callback:callback];
  509. }
  510. + (NSString *)authUserAgent {
  511. return [NSString stringWithFormat:@"FirebaseAuth.iOS/%@ %@", FIRFirebaseVersion(),
  512. GTMFetcherStandardUserAgentString(nil)];
  513. }
  514. + (void)requestWithURL:(NSURL *)URL
  515. contentType:(NSString *)contentType
  516. requestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration
  517. completionHandler:(void (^)(NSMutableURLRequest *_Nullable))completionHandler {
  518. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  519. [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
  520. NSString *additionalFrameworkMarker =
  521. requestConfiguration.additionalFrameworkMarker ?: kFirebaseAuthCoreFrameworkMarker;
  522. NSString *clientVersion = [NSString
  523. stringWithFormat:@"iOS/FirebaseSDK/%@/%@", FIRFirebaseVersion(), additionalFrameworkMarker];
  524. [request setValue:clientVersion forHTTPHeaderField:kClientVersionHeader];
  525. NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
  526. [request setValue:bundleID forHTTPHeaderField:kIosBundleIdentifierHeader];
  527. NSString *appID = requestConfiguration.appID;
  528. [request setValue:appID forHTTPHeaderField:kFirebaseAppIDHeader];
  529. [request setValue:FIRHeaderValueFromHeartbeatsPayload(
  530. [requestConfiguration.heartbeatLogger flushHeartbeatsIntoPayload])
  531. forHTTPHeaderField:kFirebaseHeartbeatHeader];
  532. NSArray<NSString *> *preferredLocalizations = [NSBundle mainBundle].preferredLocalizations;
  533. if (preferredLocalizations.count) {
  534. NSString *acceptLanguage = preferredLocalizations.firstObject;
  535. [request setValue:acceptLanguage forHTTPHeaderField:@"Accept-Language"];
  536. }
  537. NSString *languageCode = requestConfiguration.languageCode;
  538. if (languageCode.length) {
  539. [request setValue:languageCode forHTTPHeaderField:kFirebaseLocalHeader];
  540. }
  541. if (requestConfiguration.appCheck) {
  542. [requestConfiguration.appCheck
  543. getTokenForcingRefresh:false
  544. completion:^(id<FIRAppCheckTokenResultInterop> _Nonnull tokenResult) {
  545. if (tokenResult.error) {
  546. FIRLogWarning(kFIRLoggerAuth, @"I-AUT000018",
  547. @"Error getting App Check token; using placeholder token "
  548. @"instead. Error: %@",
  549. tokenResult.error);
  550. }
  551. [request setValue:tokenResult.token
  552. forHTTPHeaderField:@"X-Firebase-AppCheck"];
  553. completionHandler(request);
  554. NSLog(@"appCheck token: %@", tokenResult.token);
  555. }];
  556. } else {
  557. completionHandler(request);
  558. }
  559. }
  560. @end
  561. @interface FIRAuthBackendRPCIssuerImplementation : NSObject <FIRAuthBackendRPCIssuer>
  562. @end
  563. @implementation FIRAuthBackendRPCIssuerImplementation {
  564. /** @var The session fetcher service.
  565. */
  566. GTMSessionFetcherService *_fetcherService;
  567. }
  568. - (instancetype)init {
  569. self = [super init];
  570. if (self) {
  571. _fetcherService = [[GTMSessionFetcherService alloc] init];
  572. _fetcherService.userAgent = [FIRAuthBackend authUserAgent];
  573. _fetcherService.callbackQueue = FIRAuthGlobalWorkQueue();
  574. // Avoid reusing the session to prevent
  575. // https://github.com/firebase/firebase-ios-sdk/issues/1261
  576. _fetcherService.reuseSession = NO;
  577. }
  578. return self;
  579. }
  580. - (void)asyncPostToURLWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration
  581. URL:(NSURL *)URL
  582. body:(nullable NSData *)body
  583. contentType:(NSString *)contentType
  584. completionHandler:
  585. (void (^)(NSData *_Nullable, NSError *_Nullable))handler {
  586. [FIRAuthBackend requestWithURL:URL
  587. contentType:contentType
  588. requestConfiguration:requestConfiguration
  589. completionHandler:^(NSMutableURLRequest *request) {
  590. GTMSessionFetcher *fetcher = [self->_fetcherService fetcherWithRequest:request];
  591. NSString *emulatorHostAndPort = requestConfiguration.emulatorHostAndPort;
  592. if (emulatorHostAndPort) {
  593. fetcher.allowLocalhostRequest = YES;
  594. fetcher.allowedInsecureSchemes = @[ @"http" ];
  595. }
  596. fetcher.bodyData = body;
  597. [fetcher beginFetchWithCompletionHandler:handler];
  598. }];
  599. }
  600. @end
  601. @implementation FIRAuthBackendRPCImplementation
  602. - (instancetype)init {
  603. self = [super init];
  604. if (self) {
  605. _RPCIssuer = [[FIRAuthBackendRPCIssuerImplementation alloc] init];
  606. }
  607. return self;
  608. }
  609. - (void)createAuthURI:(FIRCreateAuthURIRequest *)request
  610. callback:(FIRCreateAuthURIResponseCallback)callback {
  611. FIRCreateAuthURIResponse *response = [[FIRCreateAuthURIResponse alloc] init];
  612. [self postWithRequest:request
  613. response:response
  614. callback:^(NSError *error) {
  615. if (error) {
  616. callback(nil, error);
  617. } else {
  618. callback(response, nil);
  619. }
  620. }];
  621. }
  622. - (void)getAccountInfo:(FIRGetAccountInfoRequest *)request
  623. callback:(FIRGetAccountInfoResponseCallback)callback {
  624. FIRGetAccountInfoResponse *response = [[FIRGetAccountInfoResponse alloc] init];
  625. [self postWithRequest:request
  626. response:response
  627. callback:^(NSError *error) {
  628. if (error) {
  629. callback(nil, error);
  630. } else {
  631. callback(response, nil);
  632. }
  633. }];
  634. }
  635. - (void)getProjectConfig:(FIRGetProjectConfigRequest *)request
  636. callback:(FIRGetProjectConfigResponseCallback)callback {
  637. FIRGetProjectConfigResponse *response = [[FIRGetProjectConfigResponse alloc] init];
  638. [self postWithRequest:request
  639. response:response
  640. callback:^(NSError *error) {
  641. if (error) {
  642. callback(nil, error);
  643. } else {
  644. callback(response, nil);
  645. }
  646. }];
  647. }
  648. - (void)setAccountInfo:(FIRSetAccountInfoRequest *)request
  649. callback:(FIRSetAccountInfoResponseCallback)callback {
  650. FIRSetAccountInfoResponse *response = [[FIRSetAccountInfoResponse alloc] init];
  651. [self postWithRequest:request
  652. response:response
  653. callback:^(NSError *error) {
  654. if (error) {
  655. callback(nil, error);
  656. } else {
  657. callback(response, nil);
  658. }
  659. }];
  660. }
  661. - (void)verifyAssertion:(FIRVerifyAssertionRequest *)request
  662. callback:(FIRVerifyAssertionResponseCallback)callback {
  663. FIRVerifyAssertionResponse *response = [[FIRVerifyAssertionResponse alloc] init];
  664. [self
  665. postWithRequest:request
  666. response:response
  667. callback:^(NSError *error) {
  668. if (error) {
  669. callback(nil, error);
  670. } else {
  671. if (!response.IDToken && response.MFAInfo) {
  672. #if TARGET_OS_IOS
  673. NSMutableArray<FIRMultiFactorInfo *> *multiFactorInfo = [NSMutableArray array];
  674. for (FIRAuthProtoMFAEnrollment *MFAEnrollment in response.MFAInfo) {
  675. FIRPhoneMultiFactorInfo *info =
  676. [[FIRPhoneMultiFactorInfo alloc] initWithProto:MFAEnrollment];
  677. [multiFactorInfo addObject:info];
  678. }
  679. NSError *multiFactorRequiredError = [FIRAuthErrorUtils
  680. secondFactorRequiredErrorWithPendingCredential:response.MFAPendingCredential
  681. hints:multiFactorInfo];
  682. callback(nil, multiFactorRequiredError);
  683. #endif
  684. } else {
  685. callback(response, nil);
  686. }
  687. }
  688. }];
  689. }
  690. - (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request
  691. callback:(FIRVerifyCustomTokenResponseCallback)callback {
  692. FIRVerifyCustomTokenResponse *response = [[FIRVerifyCustomTokenResponse alloc] init];
  693. [self postWithRequest:request
  694. response:response
  695. callback:^(NSError *error) {
  696. if (error) {
  697. callback(nil, error);
  698. } else {
  699. callback(response, nil);
  700. }
  701. }];
  702. }
  703. - (void)verifyPassword:(FIRVerifyPasswordRequest *)request
  704. callback:(FIRVerifyPasswordResponseCallback)callback {
  705. FIRVerifyPasswordResponse *response = [[FIRVerifyPasswordResponse alloc] init];
  706. [self
  707. postWithRequest:request
  708. response:response
  709. callback:^(NSError *error) {
  710. if (error) {
  711. callback(nil, error);
  712. } else {
  713. if (!response.IDToken && response.MFAInfo) {
  714. #if TARGET_OS_IOS
  715. NSMutableArray<FIRMultiFactorInfo *> *multiFactorInfo = [NSMutableArray array];
  716. for (FIRAuthProtoMFAEnrollment *MFAEnrollment in response.MFAInfo) {
  717. FIRPhoneMultiFactorInfo *info =
  718. [[FIRPhoneMultiFactorInfo alloc] initWithProto:MFAEnrollment];
  719. [multiFactorInfo addObject:info];
  720. }
  721. NSError *multiFactorRequiredError = [FIRAuthErrorUtils
  722. secondFactorRequiredErrorWithPendingCredential:response.MFAPendingCredential
  723. hints:multiFactorInfo];
  724. callback(nil, multiFactorRequiredError);
  725. #endif
  726. } else {
  727. callback(response, nil);
  728. }
  729. }
  730. }];
  731. }
  732. - (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request
  733. callback:(FIREmailLinkSigninResponseCallback)callback {
  734. FIREmailLinkSignInResponse *response = [[FIREmailLinkSignInResponse alloc] init];
  735. [self
  736. postWithRequest:request
  737. response:response
  738. callback:^(NSError *error) {
  739. if (error) {
  740. callback(nil, error);
  741. } else {
  742. if (!response.IDToken && response.MFAInfo) {
  743. #if TARGET_OS_IOS
  744. NSMutableArray<FIRMultiFactorInfo *> *multiFactorInfo = [NSMutableArray array];
  745. for (FIRAuthProtoMFAEnrollment *MFAEnrollment in response.MFAInfo) {
  746. FIRPhoneMultiFactorInfo *info =
  747. [[FIRPhoneMultiFactorInfo alloc] initWithProto:MFAEnrollment];
  748. [multiFactorInfo addObject:info];
  749. }
  750. NSError *multiFactorRequiredError = [FIRAuthErrorUtils
  751. secondFactorRequiredErrorWithPendingCredential:response.MFAPendingCredential
  752. hints:multiFactorInfo];
  753. callback(nil, multiFactorRequiredError);
  754. #endif
  755. } else {
  756. callback(response, nil);
  757. }
  758. }
  759. }];
  760. }
  761. - (void)secureToken:(FIRSecureTokenRequest *)request
  762. callback:(FIRSecureTokenResponseCallback)callback {
  763. FIRSecureTokenResponse *response = [[FIRSecureTokenResponse alloc] init];
  764. [self postWithRequest:request
  765. response:response
  766. callback:^(NSError *error) {
  767. if (error) {
  768. callback(nil, error);
  769. } else {
  770. callback(response, nil);
  771. }
  772. }];
  773. }
  774. - (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request
  775. callback:(FIRGetOOBConfirmationCodeResponseCallback)callback {
  776. FIRGetOOBConfirmationCodeResponse *response = [[FIRGetOOBConfirmationCodeResponse alloc] init];
  777. [self postWithRequest:request
  778. response:response
  779. callback:^(NSError *error) {
  780. if (error) {
  781. callback(nil, error);
  782. } else {
  783. callback(response, nil);
  784. }
  785. }];
  786. }
  787. - (void)signUpNewUser:(FIRSignUpNewUserRequest *)request
  788. callback:(FIRSignupNewUserCallback)callback {
  789. FIRSignUpNewUserResponse *response = [[FIRSignUpNewUserResponse alloc] init];
  790. [self postWithRequest:request
  791. response:response
  792. callback:^(NSError *error) {
  793. if (error) {
  794. callback(nil, error);
  795. } else {
  796. callback(response, nil);
  797. }
  798. }];
  799. }
  800. - (void)deleteAccount:(FIRDeleteAccountRequest *)request callback:(FIRDeleteCallBack)callback {
  801. FIRDeleteAccountResponse *response = [[FIRDeleteAccountResponse alloc] init];
  802. [self postWithRequest:request response:response callback:callback];
  803. }
  804. #if TARGET_OS_IOS
  805. - (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request
  806. callback:(FIRSendVerificationCodeResponseCallback)callback {
  807. FIRSendVerificationCodeResponse *response = [[FIRSendVerificationCodeResponse alloc] init];
  808. [self postWithRequest:request
  809. response:response
  810. callback:^(NSError *error) {
  811. if (error) {
  812. callback(nil, error);
  813. } else {
  814. callback(response, error);
  815. }
  816. }];
  817. }
  818. - (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request
  819. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  820. FIRVerifyPhoneNumberResponse *response = [[FIRVerifyPhoneNumberResponse alloc] init];
  821. [self
  822. postWithRequest:request
  823. response:response
  824. callback:^(NSError *error) {
  825. if (error) {
  826. callback(nil, error);
  827. return;
  828. }
  829. // Check whether or not the successful response is actually the special case phone
  830. // auth flow that returns a temporary proof and phone number.
  831. if (response.phoneNumber.length && response.temporaryProof.length) {
  832. FIRPhoneAuthCredential *credential =
  833. [[FIRPhoneAuthCredential alloc] initWithTemporaryProof:response.temporaryProof
  834. phoneNumber:response.phoneNumber
  835. providerID:FIRPhoneAuthProviderID];
  836. callback(nil, [FIRAuthErrorUtils credentialAlreadyInUseErrorWithMessage:nil
  837. credential:credential
  838. email:nil]);
  839. return;
  840. }
  841. callback(response, nil);
  842. }];
  843. }
  844. - (void)verifyClient:(id)request callback:(FIRVerifyClientResponseCallback)callback {
  845. FIRVerifyClientResponse *response = [[FIRVerifyClientResponse alloc] init];
  846. [self postWithRequest:request
  847. response:response
  848. callback:^(NSError *error) {
  849. if (error) {
  850. callback(nil, error);
  851. return;
  852. }
  853. callback(response, nil);
  854. }];
  855. }
  856. #endif
  857. - (void)resetPassword:(FIRResetPasswordRequest *)request
  858. callback:(FIRResetPasswordCallback)callback {
  859. FIRResetPasswordResponse *response = [[FIRResetPasswordResponse alloc] init];
  860. [self postWithRequest:request
  861. response:response
  862. callback:^(NSError *error) {
  863. if (error) {
  864. callback(nil, error);
  865. return;
  866. }
  867. callback(response, nil);
  868. }];
  869. }
  870. - (void)signInWithGameCenter:(FIRSignInWithGameCenterRequest *)request
  871. callback:(FIRSignInWithGameCenterResponseCallback)callback {
  872. FIRSignInWithGameCenterResponse *response = [[FIRSignInWithGameCenterResponse alloc] init];
  873. [self postWithRequest:request
  874. response:response
  875. callback:^(NSError *error) {
  876. if (error) {
  877. if (callback) {
  878. callback(nil, error);
  879. }
  880. } else {
  881. if (callback) {
  882. callback(response, nil);
  883. }
  884. }
  885. }];
  886. }
  887. #pragma mark - Generic RPC handling methods
  888. /** @fn postWithRequest:response:callback:
  889. @brief Calls the RPC using HTTP POST.
  890. @remarks Possible error responses:
  891. @see FIRAuthInternalErrorCodeRPCRequestEncodingError
  892. @see FIRAuthInternalErrorCodeJSONSerializationError
  893. @see FIRAuthInternalErrorCodeNetworkError
  894. @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  895. @see FIRAuthInternalErrorCodeUnexpectedResponse
  896. @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  897. @param request The request.
  898. @param response The empty response to be filled.
  899. @param callback The callback for both success and failure.
  900. */
  901. - (void)postWithRequest:(id<FIRAuthRPCRequest>)request
  902. response:(id<FIRAuthRPCResponse>)response
  903. callback:(void (^)(NSError *_Nullable error))callback {
  904. NSError *error;
  905. NSData *bodyData;
  906. if ([request containsPostBody]) {
  907. id postBody = [request unencodedHTTPRequestBodyWithError:&error];
  908. if (!postBody) {
  909. callback([FIRAuthErrorUtils RPCRequestEncodingErrorWithUnderlyingError:error]);
  910. return;
  911. }
  912. NSJSONWritingOptions JSONWritingOptions = 0;
  913. #if DEBUG
  914. JSONWritingOptions |= NSJSONWritingPrettyPrinted;
  915. #endif
  916. if ([NSJSONSerialization isValidJSONObject:postBody]) {
  917. bodyData = [NSJSONSerialization dataWithJSONObject:postBody
  918. options:JSONWritingOptions
  919. error:&error];
  920. if (!bodyData) {
  921. // This is an untested case. This happens exclusively when there is an error in the
  922. // framework implementation of dataWithJSONObject:options:error:. This shouldn't normally
  923. // occur as isValidJSONObject: should return NO in any case we should encounter an error.
  924. error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:error];
  925. }
  926. } else {
  927. error = [FIRAuthErrorUtils JSONSerializationErrorForUnencodableType];
  928. }
  929. if (!bodyData) {
  930. callback(error);
  931. return;
  932. }
  933. }
  934. [_RPCIssuer
  935. asyncPostToURLWithRequestConfiguration:[request requestConfiguration]
  936. URL:[request requestURL]
  937. body:bodyData
  938. contentType:kJSONContentType
  939. completionHandler:^(NSData *data, NSError *error) {
  940. // If there is an error with no body data at all, then this must be a
  941. // network error.
  942. if (error && !data) {
  943. callback([FIRAuthErrorUtils networkErrorWithUnderlyingError:error]);
  944. return;
  945. }
  946. // Try to decode the HTTP response data which may contain either a
  947. // successful response or error message.
  948. NSError *jsonError;
  949. NSDictionary *dictionary =
  950. [NSJSONSerialization JSONObjectWithData:data
  951. options:NSJSONReadingMutableLeaves
  952. error:&jsonError];
  953. if (!dictionary) {
  954. if (error) {
  955. // We have an error, but we couldn't decode the body, so we have no
  956. // additional information other than the raw response and the
  957. // original NSError (the jsonError is infered by the error code
  958. // (FIRAuthErrorCodeUnexpectedHTTPResponse, and is irrelevant.)
  959. callback([FIRAuthErrorUtils
  960. unexpectedErrorResponseWithData:data
  961. underlyingError:error]);
  962. } else {
  963. // This is supposed to be a "successful" response, but we couldn't
  964. // deserialize the body.
  965. callback([FIRAuthErrorUtils unexpectedResponseWithData:data
  966. underlyingError:jsonError]);
  967. }
  968. return;
  969. }
  970. if (![dictionary isKindOfClass:[NSDictionary class]]) {
  971. if (error) {
  972. callback([FIRAuthErrorUtils
  973. unexpectedErrorResponseWithDeserializedResponse:dictionary
  974. underlyingError:error]);
  975. } else {
  976. callback([FIRAuthErrorUtils
  977. unexpectedResponseWithDeserializedResponse:dictionary]);
  978. }
  979. return;
  980. }
  981. // At this point we either have an error with successfully decoded
  982. // details in the body, or we have a response which must pass further
  983. // validation before we know it's truly successful. We deal with the
  984. // case where we have an error with successfully decoded error details
  985. // first:
  986. if (error) {
  987. NSDictionary *errorDictionary = dictionary[kErrorKey];
  988. if ([errorDictionary isKindOfClass:[NSDictionary class]]) {
  989. id<NSObject> errorMessage = errorDictionary[kErrorMessageKey];
  990. if ([errorMessage isKindOfClass:[NSString class]]) {
  991. NSString *errorMessageString = (NSString *)errorMessage;
  992. // Contruct client error.
  993. NSError *clientError = [[self class]
  994. clientErrorWithServerErrorMessage:errorMessageString
  995. errorDictionary:errorDictionary
  996. response:response];
  997. if (clientError) {
  998. callback(clientError);
  999. return;
  1000. }
  1001. }
  1002. // Not a message we know, return the message directly.
  1003. if (errorMessage) {
  1004. NSError *unexpecterErrorResponse = [FIRAuthErrorUtils
  1005. unexpectedErrorResponseWithDeserializedResponse:
  1006. errorDictionary
  1007. underlyingError:error];
  1008. callback(unexpecterErrorResponse);
  1009. return;
  1010. }
  1011. }
  1012. // No error message at all, return the decoded response.
  1013. callback([FIRAuthErrorUtils
  1014. unexpectedErrorResponseWithDeserializedResponse:dictionary
  1015. underlyingError:error]);
  1016. return;
  1017. }
  1018. // Finally, we try to populate the response object with the JSON
  1019. // values.
  1020. if (![response setWithDictionary:dictionary error:&error]) {
  1021. callback([FIRAuthErrorUtils
  1022. RPCResponseDecodingErrorWithDeserializedResponse:dictionary
  1023. underlyingError:error]);
  1024. return;
  1025. }
  1026. // In case returnIDPCredential of a verifyAssertion request is set to
  1027. // @YES, the server may return a 200 with a response that may contain a
  1028. // server error.
  1029. if ([request isKindOfClass:[FIRVerifyAssertionRequest class]]) {
  1030. FIRVerifyAssertionRequest *verifyAssertionRequest =
  1031. (FIRVerifyAssertionRequest *)request;
  1032. if (verifyAssertionRequest.returnIDPCredential) {
  1033. NSString *errorMessage =
  1034. dictionary[kReturnIDPCredentialErrorMessageKey];
  1035. if ([errorMessage isKindOfClass:[NSString class]]) {
  1036. NSString *errorString = (NSString *)errorMessage;
  1037. NSError *clientError =
  1038. [[self class] clientErrorWithServerErrorMessage:errorString
  1039. errorDictionary:@{}
  1040. response:response];
  1041. if (clientError) {
  1042. callback(clientError);
  1043. return;
  1044. }
  1045. }
  1046. }
  1047. }
  1048. // Success! The response object originally passed in can be used by the
  1049. // caller.
  1050. callback(nil);
  1051. }];
  1052. }
  1053. /** @fn clientErrorWithServerErrorMessage:errorDictionary:
  1054. @brief Translates known server errors to client errors.
  1055. @param serverErrorMessage The error message from the server.
  1056. @param errorDictionary The error part of the response from the server.
  1057. @param response The response from the server RPC.
  1058. @return A client error, if any.
  1059. */
  1060. + (nullable NSError *)clientErrorWithServerErrorMessage:(NSString *)serverErrorMessage
  1061. errorDictionary:(NSDictionary *)errorDictionary
  1062. response:(id<FIRAuthRPCResponse>)response {
  1063. NSString *shortErrorMessage = serverErrorMessage;
  1064. NSString *serverDetailErrorMessage;
  1065. NSRange colonRange = [serverErrorMessage rangeOfString:@":"];
  1066. if (colonRange.location != NSNotFound) {
  1067. shortErrorMessage = [serverErrorMessage substringToIndex:colonRange.location];
  1068. shortErrorMessage =
  1069. [shortErrorMessage stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  1070. serverDetailErrorMessage = [serverErrorMessage substringFromIndex:colonRange.location + 1];
  1071. serverDetailErrorMessage = [serverDetailErrorMessage
  1072. stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  1073. }
  1074. // Delegate the responsibility for constructing the client error to the response object,
  1075. // if possible.
  1076. SEL clientErrorWithServerErrorMessageSelector = @selector(clientErrorWithShortErrorMessage:
  1077. detailErrorMessage:);
  1078. if ([response respondsToSelector:clientErrorWithServerErrorMessageSelector]) {
  1079. NSError *error = [response clientErrorWithShortErrorMessage:shortErrorMessage
  1080. detailErrorMessage:serverDetailErrorMessage];
  1081. if (error) {
  1082. return error;
  1083. }
  1084. }
  1085. if ([shortErrorMessage isEqualToString:kUserNotFoundErrorMessage]) {
  1086. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  1087. }
  1088. if ([shortErrorMessage isEqualToString:kUserDeletedErrorMessage]) {
  1089. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  1090. }
  1091. if ([shortErrorMessage isEqualToString:kInvalidLocalIDErrorMessage]) {
  1092. // This case shouldn't be necessary but it is for now: b/27908364 .
  1093. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  1094. }
  1095. if ([shortErrorMessage isEqualToString:kUserTokenExpiredErrorMessage]) {
  1096. return [FIRAuthErrorUtils userTokenExpiredErrorWithMessage:serverDetailErrorMessage];
  1097. }
  1098. if ([shortErrorMessage isEqualToString:kTooManyRequestsErrorMessage]) {
  1099. return [FIRAuthErrorUtils tooManyRequestsErrorWithMessage:serverDetailErrorMessage];
  1100. }
  1101. if ([shortErrorMessage isEqualToString:kInvalidCustomTokenErrorMessage]) {
  1102. return [FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:serverDetailErrorMessage];
  1103. }
  1104. if ([shortErrorMessage isEqualToString:kCustomTokenMismatch]) {
  1105. return [FIRAuthErrorUtils customTokenMistmatchErrorWithMessage:serverDetailErrorMessage];
  1106. }
  1107. if ([shortErrorMessage isEqualToString:kInvalidCredentialErrorMessage] ||
  1108. [shortErrorMessage isEqualToString:kInvalidPendingToken]) {
  1109. return [FIRAuthErrorUtils invalidCredentialErrorWithMessage:serverDetailErrorMessage];
  1110. }
  1111. if ([shortErrorMessage isEqualToString:kUserDisabledErrorMessage]) {
  1112. return [FIRAuthErrorUtils userDisabledErrorWithMessage:serverDetailErrorMessage];
  1113. }
  1114. if ([shortErrorMessage isEqualToString:kOperationNotAllowedErrorMessage]) {
  1115. return [FIRAuthErrorUtils operationNotAllowedErrorWithMessage:serverDetailErrorMessage];
  1116. }
  1117. if ([shortErrorMessage isEqualToString:kPasswordLoginDisabledErrorMessage]) {
  1118. return [FIRAuthErrorUtils operationNotAllowedErrorWithMessage:serverDetailErrorMessage];
  1119. }
  1120. if ([shortErrorMessage isEqualToString:kEmailAlreadyInUseErrorMessage]) {
  1121. return [FIRAuthErrorUtils emailAlreadyInUseErrorWithEmail:nil];
  1122. }
  1123. if ([shortErrorMessage isEqualToString:kInvalidEmailErrorMessage]) {
  1124. return [FIRAuthErrorUtils invalidEmailErrorWithMessage:serverDetailErrorMessage];
  1125. }
  1126. // "INVALID_IDENTIFIER" can be returned by createAuthURI RPC. Considering email addresses are
  1127. // currently the only identifiers, we surface the FIRAuthErrorCodeInvalidEmail error code in this
  1128. // case.
  1129. if ([shortErrorMessage isEqualToString:kInvalidIdentifierErrorMessage]) {
  1130. return [FIRAuthErrorUtils invalidEmailErrorWithMessage:serverDetailErrorMessage];
  1131. }
  1132. if ([shortErrorMessage isEqualToString:kWrongPasswordErrorMessage]) {
  1133. return [FIRAuthErrorUtils wrongPasswordErrorWithMessage:serverDetailErrorMessage];
  1134. }
  1135. if ([shortErrorMessage isEqualToString:kCredentialTooOldErrorMessage]) {
  1136. return [FIRAuthErrorUtils requiresRecentLoginErrorWithMessage:serverDetailErrorMessage];
  1137. }
  1138. if ([shortErrorMessage isEqualToString:kInvalidUserTokenErrorMessage]) {
  1139. return [FIRAuthErrorUtils invalidUserTokenErrorWithMessage:serverDetailErrorMessage];
  1140. }
  1141. if ([shortErrorMessage isEqualToString:kFederatedUserIDAlreadyLinkedMessage]) {
  1142. FIROAuthCredential *credential;
  1143. NSString *email;
  1144. if ([response isKindOfClass:[FIRVerifyAssertionResponse class]]) {
  1145. FIRVerifyAssertionResponse *verifyAssertion = (FIRVerifyAssertionResponse *)response;
  1146. credential = [[FIROAuthCredential alloc] initWithVerifyAssertionResponse:verifyAssertion];
  1147. email = verifyAssertion.email;
  1148. }
  1149. return [FIRAuthErrorUtils credentialAlreadyInUseErrorWithMessage:serverDetailErrorMessage
  1150. credential:credential
  1151. email:email];
  1152. }
  1153. if ([shortErrorMessage isEqualToString:kWeakPasswordErrorMessagePrefix]) {
  1154. return [FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:serverDetailErrorMessage];
  1155. }
  1156. if ([shortErrorMessage isEqualToString:kExpiredActionCodeErrorMessage]) {
  1157. return [FIRAuthErrorUtils expiredActionCodeErrorWithMessage:serverDetailErrorMessage];
  1158. }
  1159. if ([shortErrorMessage isEqualToString:kInvalidActionCodeErrorMessage]) {
  1160. return [FIRAuthErrorUtils invalidActionCodeErrorWithMessage:serverDetailErrorMessage];
  1161. }
  1162. if ([shortErrorMessage isEqualToString:kMissingEmailErrorMessage]) {
  1163. return [FIRAuthErrorUtils missingEmailErrorWithMessage:serverDetailErrorMessage];
  1164. }
  1165. if ([shortErrorMessage isEqualToString:kInvalidSenderEmailErrorMessage]) {
  1166. return [FIRAuthErrorUtils invalidSenderErrorWithMessage:serverDetailErrorMessage];
  1167. }
  1168. if ([shortErrorMessage isEqualToString:kInvalidMessagePayloadErrorMessage]) {
  1169. return [FIRAuthErrorUtils invalidMessagePayloadErrorWithMessage:serverDetailErrorMessage];
  1170. }
  1171. if ([shortErrorMessage isEqualToString:kInvalidRecipientEmailErrorMessage]) {
  1172. return [FIRAuthErrorUtils invalidRecipientEmailErrorWithMessage:serverDetailErrorMessage];
  1173. }
  1174. if ([shortErrorMessage isEqualToString:kMissingIosBundleIDErrorMessage]) {
  1175. return [FIRAuthErrorUtils missingIosBundleIDErrorWithMessage:serverDetailErrorMessage];
  1176. }
  1177. if ([shortErrorMessage isEqualToString:kMissingAndroidPackageNameErrorMessage]) {
  1178. return [FIRAuthErrorUtils missingAndroidPackageNameErrorWithMessage:serverDetailErrorMessage];
  1179. }
  1180. if ([shortErrorMessage isEqualToString:kUnauthorizedDomainErrorMessage]) {
  1181. return [FIRAuthErrorUtils unauthorizedDomainErrorWithMessage:serverDetailErrorMessage];
  1182. }
  1183. if ([shortErrorMessage isEqualToString:kInvalidContinueURIErrorMessage]) {
  1184. return [FIRAuthErrorUtils invalidContinueURIErrorWithMessage:serverDetailErrorMessage];
  1185. }
  1186. if ([shortErrorMessage isEqualToString:kInvalidProviderIDErrorMessage]) {
  1187. return [FIRAuthErrorUtils invalidProviderIDErrorWithMessage:serverDetailErrorMessage];
  1188. }
  1189. if ([shortErrorMessage isEqualToString:kInvalidDynamicLinkDomainErrorMessage]) {
  1190. return [FIRAuthErrorUtils invalidDynamicLinkDomainErrorWithMessage:serverDetailErrorMessage];
  1191. }
  1192. if ([shortErrorMessage isEqualToString:kMissingContinueURIErrorMessage]) {
  1193. return [FIRAuthErrorUtils missingContinueURIErrorWithMessage:serverDetailErrorMessage];
  1194. }
  1195. if ([shortErrorMessage isEqualToString:kInvalidPhoneNumberErrorMessage]) {
  1196. return [FIRAuthErrorUtils invalidPhoneNumberErrorWithMessage:serverDetailErrorMessage];
  1197. }
  1198. if ([shortErrorMessage isEqualToString:kInvalidSessionInfoErrorMessage]) {
  1199. return [FIRAuthErrorUtils invalidVerificationIDErrorWithMessage:serverDetailErrorMessage];
  1200. }
  1201. if ([shortErrorMessage isEqualToString:kInvalidVerificationCodeErrorMessage]) {
  1202. return [FIRAuthErrorUtils invalidVerificationCodeErrorWithMessage:serverDetailErrorMessage];
  1203. }
  1204. if ([shortErrorMessage isEqualToString:kSessionExpiredErrorMessage]) {
  1205. return [FIRAuthErrorUtils sessionExpiredErrorWithMessage:serverDetailErrorMessage];
  1206. }
  1207. if ([shortErrorMessage isEqualToString:kMissingAppTokenErrorMessage]) {
  1208. return [FIRAuthErrorUtils missingAppTokenErrorWithUnderlyingError:nil];
  1209. }
  1210. if ([shortErrorMessage isEqualToString:kMissingAppCredentialErrorMessage]) {
  1211. return [FIRAuthErrorUtils missingAppCredentialWithMessage:serverDetailErrorMessage];
  1212. }
  1213. if ([shortErrorMessage isEqualToString:kInvalidAppCredentialErrorMessage]) {
  1214. return [FIRAuthErrorUtils invalidAppCredentialWithMessage:serverDetailErrorMessage];
  1215. }
  1216. if ([shortErrorMessage isEqualToString:kQuoutaExceededErrorMessage]) {
  1217. return [FIRAuthErrorUtils quotaExceededErrorWithMessage:serverErrorMessage];
  1218. }
  1219. if ([shortErrorMessage isEqualToString:kAppNotVerifiedErrorMessage]) {
  1220. return [FIRAuthErrorUtils appNotVerifiedErrorWithMessage:serverErrorMessage];
  1221. }
  1222. if ([shortErrorMessage isEqualToString:kMissingClientIdentifier]) {
  1223. return [FIRAuthErrorUtils missingClientIdentifierErrorWithMessage:serverErrorMessage];
  1224. }
  1225. if ([shortErrorMessage isEqualToString:kCaptchaCheckFailedErrorMessage]) {
  1226. return [FIRAuthErrorUtils captchaCheckFailedErrorWithMessage:serverErrorMessage];
  1227. }
  1228. if ([shortErrorMessage isEqualToString:kMissingOrInvalidNonceErrorMessage]) {
  1229. return [FIRAuthErrorUtils missingOrInvalidNonceErrorWithMessage:serverDetailErrorMessage];
  1230. }
  1231. if ([shortErrorMessage isEqualToString:kMissingMFAPendingCredentialErrorMessage]) {
  1232. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeMissingMultiFactorSession
  1233. message:serverErrorMessage];
  1234. }
  1235. if ([shortErrorMessage isEqualToString:kMissingMFAEnrollmentIDErrorMessage]) {
  1236. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeMissingMultiFactorInfo
  1237. message:serverErrorMessage];
  1238. }
  1239. if ([shortErrorMessage isEqualToString:kInvalidMFAPendingCredentialErrorMessage]) {
  1240. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeInvalidMultiFactorSession
  1241. message:serverErrorMessage];
  1242. }
  1243. if ([shortErrorMessage isEqualToString:kMFAEnrollmentNotFoundErrorMessage]) {
  1244. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeMultiFactorInfoNotFound
  1245. message:serverErrorMessage];
  1246. }
  1247. if ([shortErrorMessage isEqualToString:kAdminOnlyOperationErrorMessage]) {
  1248. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeAdminRestrictedOperation
  1249. message:serverErrorMessage];
  1250. }
  1251. if ([shortErrorMessage isEqualToString:kUnverifiedEmailErrorMessage]) {
  1252. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeUnverifiedEmail
  1253. message:serverErrorMessage];
  1254. }
  1255. if ([shortErrorMessage isEqualToString:kSecondFactorExistsErrorMessage]) {
  1256. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeSecondFactorAlreadyEnrolled
  1257. message:serverErrorMessage];
  1258. }
  1259. if ([shortErrorMessage isEqualToString:kSecondFactorLimitExceededErrorMessage]) {
  1260. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeMaximumSecondFactorCountExceeded
  1261. message:serverErrorMessage];
  1262. }
  1263. if ([shortErrorMessage isEqualToString:kUnsupportedFirstFactorErrorMessage]) {
  1264. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeUnsupportedFirstFactor
  1265. message:serverErrorMessage];
  1266. }
  1267. if ([shortErrorMessage isEqualToString:kEmailChangeNeedsVerificationErrorMessage]) {
  1268. return [FIRAuthErrorUtils errorWithCode:FIRAuthInternalErrorCodeEmailChangeNeedsVerification
  1269. message:serverErrorMessage];
  1270. }
  1271. if ([shortErrorMessage isEqualToString:kTenantIDMismatch]) {
  1272. return [FIRAuthErrorUtils tenantIDMismatchError];
  1273. }
  1274. if ([shortErrorMessage isEqualToString:kUnsupportedTenantOperation]) {
  1275. return [FIRAuthErrorUtils unsupportedTenantOperationError];
  1276. }
  1277. if ([shortErrorMessage isEqualToString:kBlockingCloudFunctionErrorResponse]) {
  1278. return
  1279. [FIRAuthErrorUtils blockingCloudFunctionServerResponseWithMessage:serverDetailErrorMessage];
  1280. }
  1281. // In this case we handle an error that might be specified in the underlying errors dictionary,
  1282. // the error message in determined based on the @c reason key in the dictionary.
  1283. if (errorDictionary[kErrorsKey]) {
  1284. // Check for underlying error with reason = keyInvalid;
  1285. id underlyingErrors = errorDictionary[kErrorsKey];
  1286. if ([underlyingErrors isKindOfClass:[NSArray class]]) {
  1287. NSArray *underlyingErrorsArray = (NSArray *)underlyingErrors;
  1288. for (id underlyingError in underlyingErrorsArray) {
  1289. if ([underlyingError isKindOfClass:[NSDictionary class]]) {
  1290. NSDictionary *underlyingErrorDictionary = (NSDictionary *)underlyingError;
  1291. NSString *reason = underlyingErrorDictionary[kReasonKey];
  1292. if ([reason hasPrefix:kInvalidKeyReasonValue]) {
  1293. return [FIRAuthErrorUtils invalidAPIKeyError];
  1294. }
  1295. if ([reason isEqualToString:kAppNotAuthorizedReasonValue]) {
  1296. return [FIRAuthErrorUtils appNotAuthorizedError];
  1297. }
  1298. }
  1299. }
  1300. }
  1301. }
  1302. return nil;
  1303. }
  1304. @end
  1305. NS_ASSUME_NONNULL_END