FIRAuthBackend.m 62 KB

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