FIRAuthBackend.m 63 KB

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