FIRAuthBackend.m 62 KB

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