FIRAuthBackend.m 65 KB

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