FIRAuthBackend.m 64 KB

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