You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1118 lines
44 KiB

6 years ago
  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 <Foundation/Foundation.h>
  17. #import "FIRAuthBackend.h"
  18. #import "FIRAuthErrorUtils.h"
  19. #import "FIRAuthGlobalWorkQueue.h"
  20. #import "FirebaseAuth.h"
  21. #import "FIRAuthRPCRequest.h"
  22. #import "FIRAuthRPCResponse.h"
  23. #import "FIRCreateAuthURIRequest.h"
  24. #import "FIRCreateAuthURIResponse.h"
  25. #import "FIRDeleteAccountRequest.h"
  26. #import "FIRDeleteAccountResponse.h"
  27. #import "FIRGetAccountInfoRequest.h"
  28. #import "FIRGetAccountInfoResponse.h"
  29. #import "FIRGetOOBConfirmationCodeRequest.h"
  30. #import "FIRGetOOBConfirmationCodeResponse.h"
  31. #import "FIRGetProjectConfigRequest.h"
  32. #import "FIRGetProjectConfigResponse.h"
  33. #import "FIRResetPasswordRequest.h"
  34. #import "FIRResetPasswordResponse.h"
  35. #import "FIRSendVerificationCodeRequest.h"
  36. #import "FIRSendVerificationCodeResponse.h"
  37. #import "FIRSecureTokenRequest.h"
  38. #import "FIRSecureTokenResponse.h"
  39. #import "FIRSetAccountInfoRequest.h"
  40. #import "FIRSetAccountInfoResponse.h"
  41. #import "FIRSignUpNewUserRequest.h"
  42. #import "FIRSignUpNewUserResponse.h"
  43. #import "FIRVerifyAssertionRequest.h"
  44. #import "FIRVerifyAssertionResponse.h"
  45. #import "FIRVerifyClientRequest.h"
  46. #import "FIRVerifyClientResponse.h"
  47. #import "FIRVerifyCustomTokenRequest.h"
  48. #import "FIRVerifyCustomTokenResponse.h"
  49. #import "FIRVerifyPasswordRequest.h"
  50. #import "FIRVerifyPasswordResponse.h"
  51. #import "FIREmailLinkSignInRequest.h"
  52. #import "FIREmailLinkSignInResponse.h"
  53. #import "FIRVerifyPhoneNumberRequest.h"
  54. #import "FIRVerifyPhoneNumberResponse.h"
  55. #import <GTMSessionFetcher/GTMSessionFetcher.h>
  56. #import <GTMSessionFetcher/GTMSessionFetcherService.h>
  57. #if TARGET_OS_IOS
  58. #import "../AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h"
  59. #import "FIRPhoneAuthProvider.h"
  60. #endif
  61. /** @var kClientVersionHeader
  62. @brief HTTP header name for the client version.
  63. */
  64. static NSString *const kClientVersionHeader = @"X-Client-Version";
  65. /** @var kIosBundleIdentifierHeader
  66. @brief HTTP header name for iOS bundle ID.
  67. */
  68. static NSString *const kIosBundleIdentifierHeader = @"X-Ios-Bundle-Identifier";
  69. /** @var kFirebaseLocalHeader
  70. @brief HTTP header name for the firebase locale.
  71. */
  72. static NSString *const kFirebaseLocalHeader = @"X-Firebase-Locale";
  73. /** @var kFirebaseAuthCoreFrameworkMarker
  74. @brief The marker in the HTTP header that indicates the request comes from Firebase Auth Core.
  75. */
  76. static NSString *const kFirebaseAuthCoreFrameworkMarker = @"FirebaseCore-iOS";
  77. /** @var kJSONContentType
  78. @brief The value of the HTTP content-type header for JSON payloads.
  79. */
  80. static NSString *const kJSONContentType = @"application/json";
  81. /** @var kErrorDataKey
  82. @brief Key for error data in NSError returned by @c GTMSessionFetcher.
  83. */
  84. static NSString * const kErrorDataKey = @"data";
  85. /** @var kErrorKey
  86. @brief The key for the "error" value in JSON responses from the server.
  87. */
  88. static NSString *const kErrorKey = @"error";
  89. /** @var kErrorsKey
  90. @brief The key for the "errors" value in JSON responses from the server.
  91. */
  92. static NSString *const kErrorsKey = @"errors";
  93. /** @var kReasonKey
  94. @brief The key for the "reason" value in JSON responses from the server.
  95. */
  96. static NSString *const kReasonKey = @"reason";
  97. /** @var kInvalidKeyReasonValue
  98. @brief The value for the "reason" key indicating an invalid API Key was received by the server.
  99. */
  100. static NSString *const kInvalidKeyReasonValue = @"keyInvalid";
  101. /** @var kAppNotAuthorizedReasonValue
  102. @brief The value for the "reason" key indicating the App is not authorized to use Firebase
  103. Authentication.
  104. */
  105. static NSString *const kAppNotAuthorizedReasonValue = @"ipRefererBlocked";
  106. /** @var kErrorMessageKey
  107. @brief The key for an error's "message" value in JSON responses from the server.
  108. */
  109. static NSString *const kErrorMessageKey = @"message";
  110. /** @var kUserNotFoundErrorMessage
  111. @brief This is the error message returned when the user is not found, which means the user
  112. account has been deleted given the token was once valid.
  113. */
  114. static NSString *const kUserNotFoundErrorMessage = @"USER_NOT_FOUND";
  115. /** @var kUserDeletedErrorMessage
  116. @brief This is the error message the server will respond with if the user entered an invalid
  117. email address.
  118. */
  119. static NSString *const kUserDeletedErrorMessage = @"EMAIL_NOT_FOUND";
  120. /** @var kInvalidLocalIDErrorMessage
  121. @brief This is the error message the server responds with if the user local id in the id token
  122. does not exit.
  123. */
  124. static NSString *const kInvalidLocalIDErrorMessage = @"INVALID_LOCAL_ID";
  125. /** @var kUserTokenExpiredErrorMessage
  126. @brief The error returned by the server if the token issue time is older than the account's
  127. valid_since time.
  128. */
  129. static NSString *const kUserTokenExpiredErrorMessage = @"TOKEN_EXPIRED";
  130. /** @var kTooManyRequestsErrorMessage
  131. @brief This is the error message the server will respond with if too many requests were made to
  132. a server method.
  133. */
  134. static NSString *const kTooManyRequestsErrorMessage = @"TOO_MANY_ATTEMPTS_TRY_LATER";
  135. /** @var kInvalidTokenCustomErrorMessage
  136. @brief This is the error message the server will respond with if there is a validation error
  137. with the custom token.
  138. */
  139. static NSString *const kInvalidCustomTokenErrorMessage = @"INVALID_CUSTOM_TOKEN";
  140. /** @var kCustomTokenMismatch
  141. @brief This is the error message the server will respond with if the service account and API key
  142. belong to different projects.
  143. */
  144. static NSString *const kCustomTokenMismatch = @"CREDENTIAL_MISMATCH";
  145. /** @var kInvalidCredentialErrorMessage
  146. @brief This is the error message the server responds with if the IDP token or requestUri is
  147. invalid.
  148. */
  149. static NSString *const kInvalidCredentialErrorMessage = @"INVALID_IDP_RESPONSE";
  150. /** @var kUserDisabledErrorMessage
  151. @brief The error returned by the server if the user account is diabled.
  152. */
  153. static NSString *const kUserDisabledErrorMessage = @"USER_DISABLED";
  154. /** @var kOperationNotAllowedErrorMessage
  155. @brief This is the error message the server will respond with if Admin disables IDP specified by
  156. provider.
  157. */
  158. static NSString *const kOperationNotAllowedErrorMessage = @"OPERATION_NOT_ALLOWED";
  159. /** @var kPasswordLoginDisabledErrorMessage
  160. @brief This is the error message the server responds with if password login is disabled.
  161. */
  162. static NSString *const kPasswordLoginDisabledErrorMessage = @"PASSWORD_LOGIN_DISABLED";
  163. /** @var kEmailAlreadyInUseErrorMessage
  164. @brief This is the error message the server responds with if the email address already exists.
  165. */
  166. static NSString *const kEmailAlreadyInUseErrorMessage = @"EMAIL_EXISTS";
  167. /** @var kInvalidEmailErrorMessage
  168. @brief The error returned by the server if the email is invalid.
  169. */
  170. static NSString *const kInvalidEmailErrorMessage = @"INVALID_EMAIL";
  171. /** @var kInvalidIdentifierErrorMessage
  172. @brief The error returned by the server if the identifier is invalid.
  173. */
  174. static NSString *const kInvalidIdentifierErrorMessage = @"INVALID_IDENTIFIER";
  175. /** @var kWrongPasswordErrorMessage
  176. @brief This is the error message the server will respond with if the user entered a wrong
  177. password.
  178. */
  179. static NSString *const kWrongPasswordErrorMessage = @"INVALID_PASSWORD";
  180. /** @var kCredentialTooOldErrorMessage
  181. @brief This is the error message the server responds with if account change is attempted 5
  182. minutes after signing in.
  183. */
  184. static NSString *const kCredentialTooOldErrorMessage = @"CREDENTIAL_TOO_OLD_LOGIN_AGAIN";
  185. /** @var kFederatedUserIDAlreadyLinkedMessage
  186. @brief This is the error message the server will respond with if the federated user ID has been
  187. already linked with another account.
  188. */
  189. static NSString *const kFederatedUserIDAlreadyLinkedMessage = @"FEDERATED_USER_ID_ALREADY_LINKED";
  190. /** @var kInvalidUserTokenErrorMessage
  191. @brief This is the error message the server responds with if user's saved auth credential is
  192. invalid, and the user needs to sign in again.
  193. */
  194. static NSString *const kInvalidUserTokenErrorMessage = @"INVALID_ID_TOKEN";
  195. /** @var kWeakPasswordErrorMessagePrefix
  196. @brief This is the prefix for the error message the server responds with if user's new password
  197. to be set is too weak.
  198. */
  199. static NSString *const kWeakPasswordErrorMessagePrefix = @"WEAK_PASSWORD";
  200. /** @var kExpiredActionCodeErrorMessage
  201. @brief This is the error message the server will respond with if the action code is expired.
  202. */
  203. static NSString *const kExpiredActionCodeErrorMessage = @"EXPIRED_OOB_CODE";
  204. /** @var kInvalidActionCodeErrorMessage
  205. @brief This is the error message the server will respond with if the action code is invalid.
  206. */
  207. static NSString *const kInvalidActionCodeErrorMessage = @"INVALID_OOB_CODE";
  208. /** @var kMissingEmailErrorMessage
  209. @brief This is the error message the server will respond with if the email address is missing
  210. during a "send password reset email" attempt.
  211. */
  212. static NSString *const kMissingEmailErrorMessage = @"MISSING_EMAIL";
  213. /** @var kInvalidSenderEmailErrorMessage
  214. @brief This is the error message the server will respond with if the sender email is invalid
  215. during a "send password reset email" attempt.
  216. */
  217. static NSString *const kInvalidSenderEmailErrorMessage = @"INVALID_SENDER";
  218. /** @var kInvalidMessagePayloadErrorMessage
  219. @brief This is the error message the server will respond with if there are invalid parameters in
  220. the payload during a "send password reset email" attempt.
  221. */
  222. static NSString *const kInvalidMessagePayloadErrorMessage = @"INVALID_MESSAGE_PAYLOAD";
  223. /** @var kInvalidRecipientEmailErrorMessage
  224. @brief This is the error message the server will respond with if the recipient email is invalid.
  225. */
  226. static NSString *const kInvalidRecipientEmailErrorMessage = @"INVALID_RECIPIENT_EMAIL";
  227. /** @var kMissingIosBundleIDErrorMessage
  228. @brief This is the error message the server will respond with if iOS bundle ID is missing but
  229. the iOS App store ID is provided.
  230. */
  231. static NSString *const kMissingIosBundleIDErrorMessage = @"MISSING_IOS_BUNDLE_ID";
  232. /** @var kMissingAndroidPackageNameErrorMessage
  233. @brief This is the error message the server will respond with if Android Package Name is missing
  234. but the flag indicating the app should be installed is set to true.
  235. */
  236. static NSString *const kMissingAndroidPackageNameErrorMessage = @"MISSING_ANDROID_PACKAGE_NAME";
  237. /** @var kUnauthorizedDomainErrorMessage
  238. @brief This is the error message the server will respond with if the domain of the continue URL
  239. specified is not whitelisted in the firebase console.
  240. */
  241. static NSString *const kUnauthorizedDomainErrorMessage = @"UNAUTHORIZED_DOMAIN";
  242. /** @var kInvalidContinueURIErrorMessage
  243. @brief This is the error message the server will respond with if the continue URL provided in
  244. the request is invalid.
  245. */
  246. static NSString *const kInvalidContinueURIErrorMessage = @"INVALID_CONTINUE_URI";
  247. /** @var kMissingContinueURIErrorMessage
  248. @brief This is the error message the server will respond with if there was no continue URI
  249. present in a request that required one.
  250. */
  251. static NSString *const kMissingContinueURIErrorMessage = @"MISSING_CONTINUE_URI";
  252. /** @var kInvalidPhoneNumberErrorMessage
  253. @brief This is the error message the server will respond with if an incorrectly formatted phone
  254. number is provided.
  255. */
  256. static NSString *const kInvalidPhoneNumberErrorMessage = @"INVALID_PHONE_NUMBER";
  257. /** @var kInvalidVerificationCodeErrorMessage
  258. @brief This is the error message the server will respond with if an invalid verification code is
  259. provided.
  260. */
  261. static NSString *const kInvalidVerificationCodeErrorMessage = @"INVALID_CODE";
  262. /** @var kInvalidSessionInfoErrorMessage
  263. @brief This is the error message the server will respond with if an invalid session info
  264. (verification ID) is provided.
  265. */
  266. static NSString *const kInvalidSessionInfoErrorMessage = @"INVALID_SESSION_INFO";
  267. /** @var kSessionExpiredErrorMessage
  268. @brief This is the error message the server will respond with if the SMS code has expired before
  269. it is used.
  270. */
  271. static NSString *const kSessionExpiredErrorMessage = @"SESSION_EXPIRED";
  272. /** @var kMissingAppTokenErrorMessage
  273. @brief This is the error message the server will respond with if the APNS token is missing in a
  274. verifyClient request.
  275. */
  276. static NSString *const kMissingAppTokenErrorMessage = @"MISSING_IOS_APP_TOKEN";
  277. /** @var kMissingAppCredentialErrorMessage
  278. @brief This is the error message the server will respond with if the app token is missing in a
  279. sendVerificationCode request.
  280. */
  281. static NSString *const kMissingAppCredentialErrorMessage = @"MISSING_APP_CREDENTIAL";
  282. /** @var kInvalidAppCredentialErrorMessage
  283. @brief This is the error message the server will respond with if the app credential in a
  284. sendVerificationCode request is invalid.
  285. */
  286. static NSString *const kInvalidAppCredentialErrorMessage = @"INVALID_APP_CREDENTIAL";
  287. /** @var kQuoutaExceededErrorMessage
  288. @brief This is the error message the server will respond with if the quota for SMS text messages
  289. has been exceeded for the project.
  290. */
  291. static NSString *const kQuoutaExceededErrorMessage = @"QUOTA_EXCEEDED";
  292. /** @var kAppNotVerifiedErrorMessage
  293. @brief This is the error message the server will respond with if Firebase could not verify the
  294. app during a phone authentication flow.
  295. */
  296. static NSString *const kAppNotVerifiedErrorMessage = @"APP_NOT_VERIFIED";
  297. /** @var kMissingClientIdentifier
  298. @brief This is the error message the server will respond with if Firebase could not verify the
  299. app during a phone authentication flow when a real phone number is used and app verification
  300. is disabled for testing.
  301. */
  302. static NSString *const kMissingClientIdentifier = @"MISSING_CLIENT_IDENTIFIER";
  303. /** @var kCaptchaCheckFailedErrorMessage
  304. @brief This is the error message the server will respond with if the reCAPTCHA token provided is
  305. invalid.
  306. */
  307. static NSString *const kCaptchaCheckFailedErrorMessage = @"CAPTCHA_CHECK_FAILED";
  308. /** @var gBackendImplementation
  309. @brief The singleton FIRAuthBackendImplementation instance to use.
  310. */
  311. static id<FIRAuthBackendImplementation> gBackendImplementation;
  312. /** @class FIRAuthBackendRPCImplementation
  313. @brief The default RPC-based backend implementation.
  314. */
  315. @interface FIRAuthBackendRPCImplementation : NSObject <FIRAuthBackendImplementation>
  316. /** @property RPCIssuer
  317. @brief An instance of FIRAuthBackendRPCIssuer for making RPC requests. Allows the RPC
  318. requests/responses to be easily faked.
  319. */
  320. @property(nonatomic, strong) id<FIRAuthBackendRPCIssuer> RPCIssuer;
  321. @end
  322. @implementation FIRAuthBackend
  323. + (id<FIRAuthBackendImplementation>)implementation {
  324. if (!gBackendImplementation) {
  325. gBackendImplementation = [[FIRAuthBackendRPCImplementation alloc] init];
  326. }
  327. return gBackendImplementation;
  328. }
  329. + (void)setBackendImplementation:(id<FIRAuthBackendImplementation>)backendImplementation {
  330. gBackendImplementation = backendImplementation;
  331. }
  332. + (void)setDefaultBackendImplementationWithRPCIssuer:
  333. (nullable id<FIRAuthBackendRPCIssuer>)RPCIssuer {
  334. FIRAuthBackendRPCImplementation *defaultImplementation =
  335. [[FIRAuthBackendRPCImplementation alloc] init];
  336. if (RPCIssuer) {
  337. defaultImplementation.RPCIssuer = RPCIssuer;
  338. }
  339. gBackendImplementation = defaultImplementation;
  340. }
  341. + (void)createAuthURI:(FIRCreateAuthURIRequest *)request
  342. callback:(FIRCreateAuthURIResponseCallback)callback {
  343. [[self implementation] createAuthURI:request callback:callback];
  344. }
  345. + (void)getAccountInfo:(FIRGetAccountInfoRequest *)request
  346. callback:(FIRGetAccountInfoResponseCallback)callback {
  347. [[self implementation] getAccountInfo:request callback:callback];
  348. }
  349. + (void)getProjectConfig:(FIRGetProjectConfigRequest *)request
  350. callback:(FIRGetProjectConfigResponseCallback)callback {
  351. [[self implementation] getProjectConfig:request callback:callback];
  352. }
  353. + (void)setAccountInfo:(FIRSetAccountInfoRequest *)request
  354. callback:(FIRSetAccountInfoResponseCallback)callback {
  355. [[self implementation] setAccountInfo:request callback:callback];
  356. }
  357. + (void)verifyAssertion:(FIRVerifyAssertionRequest *)request
  358. callback:(FIRVerifyAssertionResponseCallback)callback {
  359. [[self implementation] verifyAssertion:request callback:callback];
  360. }
  361. + (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request
  362. callback:(FIRVerifyCustomTokenResponseCallback)callback {
  363. [[self implementation] verifyCustomToken:request callback:callback];
  364. }
  365. + (void)verifyPassword:(FIRVerifyPasswordRequest *)request
  366. callback:(FIRVerifyPasswordResponseCallback)callback {
  367. [[self implementation] verifyPassword:request callback:callback];
  368. }
  369. + (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request
  370. callback:(FIREmailLinkSigninResponseCallback)callback {
  371. [[self implementation] emailLinkSignin:request callback:callback];
  372. }
  373. + (void)secureToken:(FIRSecureTokenRequest *)request
  374. callback:(FIRSecureTokenResponseCallback)callback {
  375. [[self implementation] secureToken:request callback:callback];
  376. }
  377. + (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request
  378. callback:(FIRGetOOBConfirmationCodeResponseCallback)callback {
  379. [[self implementation] getOOBConfirmationCode:request callback:callback];
  380. }
  381. + (void)signUpNewUser:(FIRSignUpNewUserRequest *)request
  382. callback:(FIRSignupNewUserCallback)callback {
  383. [[self implementation] signUpNewUser:request callback:callback];
  384. }
  385. + (void)deleteAccount:(FIRDeleteAccountRequest *)request callback:(FIRDeleteCallBack)callback {
  386. [[self implementation] deleteAccount:request callback:callback];
  387. }
  388. #if TARGET_OS_IOS
  389. + (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request
  390. callback:(FIRSendVerificationCodeResponseCallback)callback {
  391. [[self implementation] sendVerificationCode:request callback:callback];
  392. }
  393. + (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request
  394. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  395. [[self implementation] verifyPhoneNumber:request callback:callback];
  396. }
  397. + (void)verifyClient:(id)request callback:(FIRVerifyClientResponseCallback)callback {
  398. [[self implementation] verifyClient:request callback:callback];
  399. }
  400. #endif
  401. + (void)resetPassword:(FIRResetPasswordRequest *)request
  402. callback:(FIRResetPasswordCallback)callback {
  403. [[self implementation] resetPassword:request callback:callback];
  404. }
  405. + (NSString *)authUserAgent {
  406. return [NSString stringWithFormat:@"FirebaseAuth.iOS/%s %@",
  407. FirebaseAuthVersionStr, GTMFetcherStandardUserAgentString(nil)];
  408. }
  409. @end
  410. @interface FIRAuthBackendRPCIssuerImplementation : NSObject <FIRAuthBackendRPCIssuer>
  411. @end
  412. @implementation FIRAuthBackendRPCIssuerImplementation {
  413. /** @var The session fetcher service.
  414. */
  415. GTMSessionFetcherService *_fetcherService;
  416. }
  417. - (instancetype)init {
  418. self = [super init];
  419. if (self) {
  420. _fetcherService = [[GTMSessionFetcherService alloc] init];
  421. _fetcherService.userAgent = [FIRAuthBackend authUserAgent];
  422. _fetcherService.callbackQueue = FIRAuthGlobalWorkQueue();
  423. }
  424. return self;
  425. }
  426. - (void)asyncPostToURLWithRequestConfiguration:(FIRAuthRequestConfiguration *)requestConfiguration
  427. URL:(NSURL *)URL
  428. body:(NSData *)body
  429. contentType:(NSString *)contentType
  430. completionHandler:(void (^)(NSData *_Nullable,
  431. NSError *_Nullable))handler {
  432. NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
  433. [request setValue:contentType forHTTPHeaderField:@"Content-Type"];
  434. NSString *additionalFrameworkMarker = requestConfiguration.additionalFrameworkMarker ?:
  435. kFirebaseAuthCoreFrameworkMarker;
  436. NSString *clientVersion = [NSString stringWithFormat:@"iOS/FirebaseSDK/%s/%@",
  437. FirebaseAuthVersionStr,
  438. additionalFrameworkMarker];
  439. [request setValue:clientVersion forHTTPHeaderField:kClientVersionHeader];
  440. NSString *bundleID = [[NSBundle mainBundle] bundleIdentifier];
  441. [request setValue:bundleID forHTTPHeaderField:kIosBundleIdentifierHeader];
  442. NSArray<NSString *> *preferredLocalizations = [NSBundle mainBundle].preferredLocalizations;
  443. if (preferredLocalizations.count) {
  444. NSString *acceptLanguage = preferredLocalizations.firstObject;
  445. [request setValue:acceptLanguage forHTTPHeaderField:@"Accept-Language"];
  446. }
  447. NSString *languageCode = requestConfiguration.languageCode;
  448. if (languageCode.length) {
  449. [request setValue:languageCode forHTTPHeaderField:kFirebaseLocalHeader];
  450. }
  451. GTMSessionFetcher* fetcher = [_fetcherService fetcherWithRequest:request];
  452. fetcher.bodyData = body;
  453. [fetcher beginFetchWithCompletionHandler:handler];
  454. }
  455. @end
  456. @implementation FIRAuthBackendRPCImplementation
  457. - (instancetype)init {
  458. self = [super init];
  459. if (self) {
  460. _RPCIssuer = [[FIRAuthBackendRPCIssuerImplementation alloc] init];
  461. }
  462. return self;
  463. }
  464. - (void)createAuthURI:(FIRCreateAuthURIRequest *)request
  465. callback:(FIRCreateAuthURIResponseCallback)callback {
  466. FIRCreateAuthURIResponse *response = [[FIRCreateAuthURIResponse alloc] init];
  467. [self postWithRequest:request response:response callback:^(NSError *error) {
  468. if (error) {
  469. callback(nil, error);
  470. } else {
  471. callback(response, nil);
  472. }
  473. }];
  474. }
  475. - (void)getAccountInfo:(FIRGetAccountInfoRequest *)request
  476. callback:(FIRGetAccountInfoResponseCallback)callback {
  477. FIRGetAccountInfoResponse *response = [[FIRGetAccountInfoResponse alloc] init];
  478. [self postWithRequest:request response:response callback:^(NSError *error) {
  479. if (error) {
  480. callback(nil, error);
  481. } else {
  482. callback(response, nil);
  483. }
  484. }];
  485. }
  486. - (void)getProjectConfig:(FIRGetProjectConfigRequest *)request
  487. callback:(FIRGetProjectConfigResponseCallback)callback {
  488. FIRGetProjectConfigResponse *response = [[FIRGetProjectConfigResponse alloc] init];
  489. [self postWithRequest:request response:response callback:^(NSError *error) {
  490. if (error) {
  491. callback(nil, error);
  492. } else {
  493. callback(response, nil);
  494. }
  495. }];
  496. }
  497. - (void)setAccountInfo:(FIRSetAccountInfoRequest *)request
  498. callback:(FIRSetAccountInfoResponseCallback)callback {
  499. FIRSetAccountInfoResponse *response = [[FIRSetAccountInfoResponse alloc] init];
  500. [self postWithRequest:request response:response callback:^(NSError *error) {
  501. if (error) {
  502. callback(nil, error);
  503. } else {
  504. callback(response, nil);
  505. }
  506. }];
  507. }
  508. - (void)verifyAssertion:(FIRVerifyAssertionRequest *)request
  509. callback:(FIRVerifyAssertionResponseCallback)callback {
  510. FIRVerifyAssertionResponse *response = [[FIRVerifyAssertionResponse alloc] init];
  511. [self postWithRequest:request response:response callback:^(NSError *error) {
  512. if (error) {
  513. callback(nil, error);
  514. return;
  515. }
  516. callback(response, nil);
  517. }];
  518. }
  519. - (void)verifyCustomToken:(FIRVerifyCustomTokenRequest *)request
  520. callback:(FIRVerifyCustomTokenResponseCallback)callback {
  521. FIRVerifyCustomTokenResponse *response = [[FIRVerifyCustomTokenResponse alloc] init];
  522. [self postWithRequest:request response:response callback:^(NSError *error) {
  523. if (error) {
  524. callback(nil, error);
  525. } else {
  526. callback(response, nil);
  527. }
  528. }];
  529. }
  530. - (void)verifyPassword:(FIRVerifyPasswordRequest *)request
  531. callback:(FIRVerifyPasswordResponseCallback)callback {
  532. FIRVerifyPasswordResponse *response = [[FIRVerifyPasswordResponse alloc] init];
  533. [self postWithRequest:request response:response callback:^(NSError *error) {
  534. if (error) {
  535. callback(nil, error);
  536. } else {
  537. callback(response, nil);
  538. }
  539. }];
  540. }
  541. - (void)emailLinkSignin:(FIREmailLinkSignInRequest *)request
  542. callback:(FIREmailLinkSigninResponseCallback)callback {
  543. FIREmailLinkSignInResponse *response = [[FIREmailLinkSignInResponse alloc] init];
  544. [self postWithRequest:request response:response callback:^(NSError *error) {
  545. if (error) {
  546. callback(nil, error);
  547. } else {
  548. callback(response, nil);
  549. }
  550. }];
  551. }
  552. - (void)secureToken:(FIRSecureTokenRequest *)request
  553. callback:(FIRSecureTokenResponseCallback)callback {
  554. FIRSecureTokenResponse *response = [[FIRSecureTokenResponse alloc] init];
  555. [self postWithRequest:request response:response callback:^(NSError *error) {
  556. if (error) {
  557. callback(nil, error);
  558. } else {
  559. callback(response, nil);
  560. }
  561. }];
  562. }
  563. - (void)getOOBConfirmationCode:(FIRGetOOBConfirmationCodeRequest *)request
  564. callback:(FIRGetOOBConfirmationCodeResponseCallback)callback {
  565. FIRGetOOBConfirmationCodeResponse *response = [[FIRGetOOBConfirmationCodeResponse alloc] init];
  566. [self postWithRequest:request response:response callback:^(NSError *error) {
  567. if (error) {
  568. callback(nil, error);
  569. } else {
  570. callback(response, nil);
  571. }
  572. }];
  573. }
  574. - (void)signUpNewUser:(FIRSignUpNewUserRequest *)request
  575. callback:(FIRSignupNewUserCallback)callback{
  576. FIRSignUpNewUserResponse *response = [[FIRSignUpNewUserResponse alloc] init];
  577. [self postWithRequest:request response:response callback:^(NSError *error) {
  578. if (error) {
  579. callback(nil, error);
  580. } else {
  581. callback(response, nil);
  582. }
  583. }];
  584. }
  585. - (void)deleteAccount:(FIRDeleteAccountRequest *)request callback:(FIRDeleteCallBack)callback {
  586. FIRDeleteAccountResponse *response = [[FIRDeleteAccountResponse alloc] init];
  587. [self postWithRequest:request response:response callback:callback];
  588. }
  589. #if TARGET_OS_IOS
  590. - (void)sendVerificationCode:(FIRSendVerificationCodeRequest *)request
  591. callback:(FIRSendVerificationCodeResponseCallback)callback {
  592. FIRSendVerificationCodeResponse *response = [[FIRSendVerificationCodeResponse alloc] init];
  593. [self postWithRequest:request response:response callback:^(NSError *error) {
  594. if (error) {
  595. callback(nil, error);
  596. } else {
  597. callback(response, error);
  598. }
  599. }];
  600. }
  601. - (void)verifyPhoneNumber:(FIRVerifyPhoneNumberRequest *)request
  602. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  603. FIRVerifyPhoneNumberResponse *response = [[FIRVerifyPhoneNumberResponse alloc] init];
  604. [self postWithRequest:request response:response callback:^(NSError *error) {
  605. if (error) {
  606. callback(nil, error);
  607. return;
  608. }
  609. // Check whether or not the successful response is actually the special case phone auth flow
  610. // that returns a temporary proof and phone number.
  611. if (response.phoneNumber.length && response.temporaryProof.length) {
  612. FIRPhoneAuthCredential *credential =
  613. [[FIRPhoneAuthCredential alloc] initWithTemporaryProof:response.temporaryProof
  614. phoneNumber:response.phoneNumber
  615. providerID:FIRPhoneAuthProviderID];
  616. callback(nil,
  617. [FIRAuthErrorUtils credentialAlreadyInUseErrorWithMessage:nil
  618. credential:credential]);
  619. return;
  620. }
  621. callback(response, nil);
  622. }];
  623. }
  624. - (void)verifyClient:(id)request callback:(FIRVerifyClientResponseCallback)callback {
  625. FIRVerifyClientResponse *response = [[FIRVerifyClientResponse alloc] init];
  626. [self postWithRequest:request response:response callback:^(NSError *error) {
  627. if (error) {
  628. callback(nil, error);
  629. return;
  630. }
  631. callback(response, nil);
  632. }];
  633. }
  634. #endif
  635. - (void)resetPassword:(FIRResetPasswordRequest *)request
  636. callback:(FIRResetPasswordCallback)callback {
  637. FIRResetPasswordResponse *response = [[FIRResetPasswordResponse alloc] init];
  638. [self postWithRequest:request response:response callback:^(NSError *error) {
  639. if (error) {
  640. callback(nil, error);
  641. return;
  642. }
  643. callback(response, nil);
  644. }];
  645. }
  646. #pragma mark - Generic RPC handling methods
  647. /** @fn postWithRequest:response:callback:
  648. @brief Calls the RPC using HTTP POST.
  649. @remarks Possible error responses:
  650. @see FIRAuthInternalErrorCodeRPCRequestEncodingError
  651. @see FIRAuthInternalErrorCodeJSONSerializationError
  652. @see FIRAuthInternalErrorCodeNetworkError
  653. @see FIRAuthInternalErrorCodeUnexpectedErrorResponse
  654. @see FIRAuthInternalErrorCodeUnexpectedResponse
  655. @see FIRAuthInternalErrorCodeRPCResponseDecodingError
  656. @param request The request.
  657. @param response The empty response to be filled.
  658. @param callback The callback for both success and failure.
  659. */
  660. - (void)postWithRequest:(id<FIRAuthRPCRequest>)request
  661. response:(id<FIRAuthRPCResponse>)response
  662. callback:(void (^)(NSError *error))callback {
  663. NSError *error;
  664. NSData *bodyData;
  665. if ([request containsPostBody]) {
  666. id postBody = [request unencodedHTTPRequestBodyWithError:&error];
  667. if (!postBody) {
  668. callback([FIRAuthErrorUtils RPCRequestEncodingErrorWithUnderlyingError:error]);
  669. return;
  670. }
  671. NSJSONWritingOptions JSONWritingOptions = 0;
  672. #if DEBUG
  673. JSONWritingOptions |= NSJSONWritingPrettyPrinted;
  674. #endif
  675. if ([NSJSONSerialization isValidJSONObject:postBody]) {
  676. bodyData = [NSJSONSerialization dataWithJSONObject:postBody
  677. options:JSONWritingOptions
  678. error:&error];
  679. if (!bodyData) {
  680. // This is an untested case. This happens exclusively when there is an error in the framework
  681. // implementation of dataWithJSONObject:options:error:. This shouldn't normally occur as
  682. // isValidJSONObject: should return NO in any case we should encounter an error.
  683. error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:error];
  684. }
  685. } else {
  686. error = [FIRAuthErrorUtils JSONSerializationErrorForUnencodableType];
  687. }
  688. if (!bodyData) {
  689. callback(error);
  690. return;
  691. }
  692. }
  693. [_RPCIssuer asyncPostToURLWithRequestConfiguration:[request requestConfiguration]
  694. URL:[request requestURL]
  695. body:bodyData
  696. contentType:kJSONContentType
  697. completionHandler:^(NSData *data, NSError *error) {
  698. // If there is an error with no body data at all, then this must be a network error.
  699. if (error && !data) {
  700. callback([FIRAuthErrorUtils networkErrorWithUnderlyingError:error]);
  701. return;
  702. }
  703. // Try to decode the HTTP response data which may contain either a successful response or error
  704. // message.
  705. NSError *jsonError;
  706. NSDictionary * dictionary =
  707. [NSJSONSerialization JSONObjectWithData:data
  708. options:NSJSONReadingMutableLeaves
  709. error:&jsonError];
  710. if (!dictionary) {
  711. if (error) {
  712. // We have an error, but we couldn't decode the body, so we have no additional information
  713. // other than the raw response and the original NSError (the jsonError is infered by the
  714. // error code (FIRAuthErrorCodeUnexpectedHTTPResponse, and is irrelevant.)
  715. callback([FIRAuthErrorUtils unexpectedErrorResponseWithData:data underlyingError:error]);
  716. } else {
  717. // This is supposed to be a "successful" response, but we couldn't deserialize the body.
  718. callback([FIRAuthErrorUtils unexpectedResponseWithData:data underlyingError:jsonError]);
  719. }
  720. return;
  721. }
  722. if (![dictionary isKindOfClass:[NSDictionary class]]) {
  723. if (error) {
  724. callback([FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:dictionary]);
  725. } else {
  726. callback([FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:dictionary]);
  727. }
  728. return;
  729. }
  730. // At this point we either have an error with successfully decoded details in the body, or we
  731. // have a response which must pass further validation before we know it's truly successful.
  732. // We deal with the case where we have an error with successfully decoded error details first:
  733. if (error) {
  734. NSDictionary *errorDictionary = dictionary[kErrorKey];
  735. if ([errorDictionary isKindOfClass:[NSDictionary class]]) {
  736. id<NSObject> errorMessage = errorDictionary[kErrorMessageKey];
  737. if ([errorMessage isKindOfClass:[NSString class]]) {
  738. NSString *errorMessageString = (NSString *)errorMessage;
  739. // Contruct client error.
  740. NSError *clientError = [[self class] clientErrorWithServerErrorMessage:errorMessageString
  741. errorDictionary:errorDictionary
  742. response:response];
  743. if (clientError) {
  744. callback(clientError);
  745. return;
  746. }
  747. }
  748. // Not a message we know, return the message directly.
  749. if (errorMessage) {
  750. NSError *unexpecterErrorResponse =
  751. [FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:errorDictionary];
  752. callback(unexpecterErrorResponse);
  753. return;
  754. }
  755. }
  756. // No error message at all, return the decoded response.
  757. callback([FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:dictionary]);
  758. return;
  759. }
  760. // Finally, we try to populate the response object with the JSON values.
  761. if (![response setWithDictionary:dictionary error:&error]) {
  762. callback([FIRAuthErrorUtils RPCResponseDecodingErrorWithDeserializedResponse:dictionary
  763. underlyingError:error]);
  764. return;
  765. }
  766. // Success! The response object originally passed in can be used by the caller.
  767. callback(nil);
  768. }];
  769. }
  770. /** @fn clientErrorWithServerErrorMessage:errorDictionary:
  771. @brief Translates known server errors to client errors.
  772. @param serverErrorMessage The error message from the server.
  773. @param errorDictionary The error part of the response from the server.
  774. @param response The response from the server RPC.
  775. @return A client error, if any.
  776. */
  777. + (nullable NSError *)clientErrorWithServerErrorMessage:(NSString *)serverErrorMessage
  778. errorDictionary:(NSDictionary *)errorDictionary
  779. response:(id<FIRAuthRPCResponse>)response {
  780. NSString *shortErrorMessage = serverErrorMessage;
  781. NSString *serverDetailErrorMessage;
  782. NSRange colonRange = [serverErrorMessage rangeOfString:@":"];
  783. if (colonRange.location != NSNotFound) {
  784. shortErrorMessage = [serverErrorMessage substringToIndex:colonRange.location];
  785. shortErrorMessage =
  786. [shortErrorMessage stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
  787. serverDetailErrorMessage = [serverErrorMessage substringFromIndex:colonRange.location + 1];
  788. serverDetailErrorMessage = [serverDetailErrorMessage stringByTrimmingCharactersInSet:
  789. [NSCharacterSet whitespaceCharacterSet]];
  790. }
  791. // Delegate the responsibility for constructing the client error to the response object,
  792. // if possible.
  793. SEL clientErrorWithServerErrorMessageSelector =
  794. @selector(clientErrorWithShortErrorMessage:detailErrorMessage:);
  795. if ([response respondsToSelector:clientErrorWithServerErrorMessageSelector]) {
  796. NSError *error = [response clientErrorWithShortErrorMessage:shortErrorMessage
  797. detailErrorMessage:serverDetailErrorMessage];
  798. if (error) {
  799. return error;
  800. }
  801. }
  802. if ([shortErrorMessage isEqualToString:kUserNotFoundErrorMessage]) {
  803. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  804. }
  805. if ([shortErrorMessage isEqualToString:kUserDeletedErrorMessage]) {
  806. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  807. }
  808. if ([shortErrorMessage isEqualToString:kInvalidLocalIDErrorMessage]) {
  809. // This case shouldn't be necessary but it is for now: b/27908364 .
  810. return [FIRAuthErrorUtils userNotFoundErrorWithMessage:serverDetailErrorMessage];
  811. }
  812. if ([shortErrorMessage isEqualToString:kUserTokenExpiredErrorMessage]) {
  813. return [FIRAuthErrorUtils userTokenExpiredErrorWithMessage:serverDetailErrorMessage];
  814. }
  815. if ([shortErrorMessage isEqualToString:kTooManyRequestsErrorMessage]) {
  816. return [FIRAuthErrorUtils tooManyRequestsErrorWithMessage:serverDetailErrorMessage];
  817. }
  818. if ([shortErrorMessage isEqualToString:kInvalidCustomTokenErrorMessage]) {
  819. return [FIRAuthErrorUtils invalidCustomTokenErrorWithMessage:serverDetailErrorMessage];
  820. }
  821. if ([shortErrorMessage isEqualToString:kCustomTokenMismatch]) {
  822. return [FIRAuthErrorUtils customTokenMistmatchErrorWithMessage:serverDetailErrorMessage];
  823. }
  824. if ([shortErrorMessage isEqualToString:kInvalidCredentialErrorMessage]) {
  825. return [FIRAuthErrorUtils invalidCredentialErrorWithMessage:serverDetailErrorMessage];
  826. }
  827. if ([shortErrorMessage isEqualToString:kUserDisabledErrorMessage]) {
  828. return [FIRAuthErrorUtils userDisabledErrorWithMessage:serverDetailErrorMessage];
  829. }
  830. if ([shortErrorMessage isEqualToString:kOperationNotAllowedErrorMessage]) {
  831. return [FIRAuthErrorUtils operationNotAllowedErrorWithMessage:serverDetailErrorMessage];
  832. }
  833. if ([shortErrorMessage isEqualToString:kPasswordLoginDisabledErrorMessage]) {
  834. return [FIRAuthErrorUtils operationNotAllowedErrorWithMessage:serverDetailErrorMessage];
  835. }
  836. if ([shortErrorMessage isEqualToString:kEmailAlreadyInUseErrorMessage]) {
  837. return [FIRAuthErrorUtils emailAlreadyInUseErrorWithEmail:nil];
  838. }
  839. if ([shortErrorMessage isEqualToString:kInvalidEmailErrorMessage]) {
  840. return [FIRAuthErrorUtils invalidEmailErrorWithMessage:serverDetailErrorMessage];
  841. }
  842. // "INVALID_IDENTIFIER" can be returned by createAuthURI RPC. Considering email addresses are
  843. // currently the only identifiers, we surface the FIRAuthErrorCodeInvalidEmail error code in this
  844. // case.
  845. if ([shortErrorMessage isEqualToString:kInvalidIdentifierErrorMessage]) {
  846. return [FIRAuthErrorUtils invalidEmailErrorWithMessage:serverDetailErrorMessage];
  847. }
  848. if ([shortErrorMessage isEqualToString:kWrongPasswordErrorMessage]) {
  849. return [FIRAuthErrorUtils wrongPasswordErrorWithMessage:serverDetailErrorMessage];
  850. }
  851. if ([shortErrorMessage isEqualToString:kCredentialTooOldErrorMessage]) {
  852. return [FIRAuthErrorUtils requiresRecentLoginErrorWithMessage:serverDetailErrorMessage];
  853. }
  854. if ([shortErrorMessage isEqualToString:kInvalidUserTokenErrorMessage]) {
  855. return [FIRAuthErrorUtils invalidUserTokenErrorWithMessage:serverDetailErrorMessage];
  856. }
  857. if ([shortErrorMessage isEqualToString:kFederatedUserIDAlreadyLinkedMessage]) {
  858. return [FIRAuthErrorUtils credentialAlreadyInUseErrorWithMessage:serverDetailErrorMessage
  859. credential:nil];
  860. }
  861. if ([shortErrorMessage isEqualToString:kWeakPasswordErrorMessagePrefix]) {
  862. return [FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:serverDetailErrorMessage];
  863. }
  864. if ([shortErrorMessage isEqualToString:kExpiredActionCodeErrorMessage]) {
  865. return [FIRAuthErrorUtils expiredActionCodeErrorWithMessage:serverDetailErrorMessage];
  866. }
  867. if ([shortErrorMessage isEqualToString:kInvalidActionCodeErrorMessage]) {
  868. return [FIRAuthErrorUtils invalidActionCodeErrorWithMessage:serverDetailErrorMessage];
  869. }
  870. if ([shortErrorMessage isEqualToString:kMissingEmailErrorMessage]) {
  871. return [FIRAuthErrorUtils missingEmailErrorWithMessage:serverDetailErrorMessage];
  872. }
  873. if ([shortErrorMessage isEqualToString:kInvalidSenderEmailErrorMessage]) {
  874. return [FIRAuthErrorUtils invalidSenderErrorWithMessage:serverDetailErrorMessage];
  875. }
  876. if ([shortErrorMessage isEqualToString:kInvalidMessagePayloadErrorMessage]) {
  877. return [FIRAuthErrorUtils invalidMessagePayloadErrorWithMessage:serverDetailErrorMessage];
  878. }
  879. if ([shortErrorMessage isEqualToString:kInvalidRecipientEmailErrorMessage]) {
  880. return [FIRAuthErrorUtils invalidRecipientEmailErrorWithMessage:serverDetailErrorMessage];
  881. }
  882. if ([shortErrorMessage isEqualToString:kMissingIosBundleIDErrorMessage]) {
  883. return [FIRAuthErrorUtils missingIosBundleIDErrorWithMessage:serverDetailErrorMessage];
  884. }
  885. if ([shortErrorMessage isEqualToString:kMissingAndroidPackageNameErrorMessage]) {
  886. return [FIRAuthErrorUtils missingAndroidPackageNameErrorWithMessage:serverDetailErrorMessage];
  887. }
  888. if ([shortErrorMessage isEqualToString:kUnauthorizedDomainErrorMessage]) {
  889. return [FIRAuthErrorUtils unauthorizedDomainErrorWithMessage:serverDetailErrorMessage];
  890. }
  891. if ([shortErrorMessage isEqualToString:kInvalidContinueURIErrorMessage]) {
  892. return [FIRAuthErrorUtils invalidContinueURIErrorWithMessage:serverDetailErrorMessage];
  893. }
  894. if ([shortErrorMessage isEqualToString:kMissingContinueURIErrorMessage]) {
  895. return [FIRAuthErrorUtils missingContinueURIErrorWithMessage:serverDetailErrorMessage];
  896. }
  897. if ([shortErrorMessage isEqualToString:kInvalidPhoneNumberErrorMessage]) {
  898. return [FIRAuthErrorUtils invalidPhoneNumberErrorWithMessage:serverDetailErrorMessage];
  899. }
  900. if ([shortErrorMessage isEqualToString:kInvalidSessionInfoErrorMessage]) {
  901. return [FIRAuthErrorUtils invalidVerificationIDErrorWithMessage:serverDetailErrorMessage];
  902. }
  903. if ([shortErrorMessage isEqualToString:kInvalidVerificationCodeErrorMessage]) {
  904. return [FIRAuthErrorUtils invalidVerificationCodeErrorWithMessage:serverDetailErrorMessage];
  905. }
  906. if ([shortErrorMessage isEqualToString:kSessionExpiredErrorMessage]) {
  907. return [FIRAuthErrorUtils sessionExpiredErrorWithMessage:serverDetailErrorMessage];
  908. }
  909. if ([shortErrorMessage isEqualToString:kMissingAppTokenErrorMessage]) {
  910. return [FIRAuthErrorUtils missingAppTokenErrorWithUnderlyingError:nil];
  911. }
  912. if ([shortErrorMessage isEqualToString:kMissingAppCredentialErrorMessage]) {
  913. return [FIRAuthErrorUtils missingAppCredentialWithMessage:serverDetailErrorMessage];
  914. }
  915. if ([shortErrorMessage isEqualToString:kInvalidAppCredentialErrorMessage]) {
  916. return [FIRAuthErrorUtils invalidAppCredentialWithMessage:serverDetailErrorMessage];
  917. }
  918. if ([shortErrorMessage isEqualToString:kQuoutaExceededErrorMessage]) {
  919. return [FIRAuthErrorUtils quotaExceededErrorWithMessage:serverErrorMessage];
  920. }
  921. if ([shortErrorMessage isEqualToString:kAppNotVerifiedErrorMessage]) {
  922. return [FIRAuthErrorUtils appNotVerifiedErrorWithMessage:serverErrorMessage];
  923. }
  924. if ([shortErrorMessage isEqualToString:kMissingClientIdentifier]) {
  925. return [FIRAuthErrorUtils appNotVerifiedErrorWithMessage:@"Missing app verification via"
  926. " reCAPTCHA or APNS token. Please verify that appVerificationDisabledForTesting is not"
  927. " enabled when testing with a phone number that is not marked as a test Phone number in the"
  928. " app console."];
  929. }
  930. if ([shortErrorMessage isEqualToString:kCaptchaCheckFailedErrorMessage]) {
  931. return [FIRAuthErrorUtils captchaCheckFailedErrorWithMessage:serverErrorMessage];
  932. }
  933. // In this case we handle an error that might be specified in the underlying errors dictionary,
  934. // the error message in determined based on the @c reason key in the dictionary.
  935. if (errorDictionary[kErrorsKey]) {
  936. // Check for underlying error with reason = keyInvalid;
  937. id underlyingErrors = errorDictionary[kErrorsKey];
  938. if ([underlyingErrors isKindOfClass:[NSArray class]]) {
  939. NSArray *underlyingErrorsArray = (NSArray *)underlyingErrors;
  940. for (id underlyingError in underlyingErrorsArray) {
  941. if ([underlyingError isKindOfClass:[NSDictionary class]]) {
  942. NSDictionary *underlyingErrorDictionary = (NSDictionary *)underlyingError;
  943. NSString *reason = underlyingErrorDictionary[kReasonKey];
  944. if ([reason hasPrefix:kInvalidKeyReasonValue]) {
  945. return [FIRAuthErrorUtils invalidAPIKeyError];
  946. }
  947. if ([reason isEqualToString:kAppNotAuthorizedReasonValue]) {
  948. return [FIRAuthErrorUtils appNotAuthorizedError];
  949. }
  950. }
  951. }
  952. }
  953. }
  954. return nil;
  955. }
  956. @end