FIRAuthBackend.m 61 KB

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