FIRAuthBackend.m 64 KB

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