FIRPhoneAuthProvider.m 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  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. #include <TargetConditionals.h>
  17. #if TARGET_OS_IOS
  18. #import "FIRPhoneAuthProvider.h"
  19. #import <FirebaseCore/FIRApp.h>
  20. #import <FirebaseCore/FIRLogger.h>
  21. #import <FirebaseCore/FIROptions.h>
  22. #import "FIRAuthAPNSToken.h"
  23. #import "FIRAuthAPNSTokenManager.h"
  24. #import "FIRAuthAppCredential.h"
  25. #import "FIRAuthAppCredentialManager.h"
  26. #import "FIRAuthBackend+MultiFactor.h"
  27. #import "FIRAuthBackend.h"
  28. #import "FIRAuthErrorUtils.h"
  29. #import "FIRAuthGlobalWorkQueue.h"
  30. #import "FIRAuthNotificationManager.h"
  31. #import "FIRAuthProtoStartMFAPhoneRequestInfo.h"
  32. #import "FIRAuthSettings.h"
  33. #import "FIRAuthURLPresenter.h"
  34. #import "FIRAuthWebUtils.h"
  35. #import "FIRAuth_Internal.h"
  36. #import "FIRGetProjectConfigRequest.h"
  37. #import "FIRGetProjectConfigResponse.h"
  38. #import "FIRMultiFactorResolver.h"
  39. #import "FIRMultiFactorSession+Internal.h"
  40. #import "FIRSendVerificationCodeRequest.h"
  41. #import "FIRSendVerificationCodeResponse.h"
  42. #import "FIRStartMFAEnrollmentRequest.h"
  43. #import "FIRStartMFAEnrollmentResponse.h"
  44. #import "FIRVerifyClientRequest.h"
  45. #import "FIRVerifyClientResponse.h"
  46. #import "FirebaseAuthVersion.h"
  47. #if TARGET_OS_IOS
  48. #import "FIRPhoneAuthCredential_Internal.h"
  49. #import "FIRPhoneMultiFactorInfo+Internal.h"
  50. #endif
  51. NS_ASSUME_NONNULL_BEGIN
  52. /** @typedef FIRReCAPTCHAURLCallBack
  53. @brief The callback invoked at the end of the flow to fetch a reCAPTCHA URL.
  54. @param reCAPTCHAURL The reCAPTCHA URL.
  55. @param error The error that occurred while fetching the reCAPTCHAURL, if any.
  56. */
  57. typedef void (^FIRReCAPTCHAURLCallBack)(NSURL *_Nullable reCAPTCHAURL, NSError *_Nullable error);
  58. /** @typedef FIRVerifyClientCallback
  59. @brief The callback invoked at the end of a client verification flow.
  60. @param appCredential credential that proves the identity of the app during a phone
  61. authentication flow.
  62. @param error The error that occurred while verifying the app, if any.
  63. */
  64. typedef void (^FIRVerifyClientCallback)(FIRAuthAppCredential *_Nullable appCredential,
  65. NSString *_Nullable reCAPTCHAToken,
  66. NSError *_Nullable error);
  67. /** @typedef FIRFetchAuthDomainCallback
  68. @brief The callback invoked at the end of the flow to fetch the Auth domain.
  69. @param authDomain The Auth domain.
  70. @param error The error that occurred while fetching the auth domain, if any.
  71. */
  72. typedef void (^FIRFetchAuthDomainCallback)(NSString *_Nullable authDomain,
  73. NSError *_Nullable error);
  74. /** @var kauthTypeVerifyApp
  75. @brief The auth type to be specified in the app verification request.
  76. */
  77. static NSString *const kAuthTypeVerifyApp = @"verifyApp";
  78. /** @var kReCAPTCHAURLStringFormat
  79. @brief The format of the URL used to open the reCAPTCHA page during app verification.
  80. */
  81. NSString *const kReCAPTCHAURLStringFormat = @"https://%@/__/auth/handler?";
  82. extern NSString *const FIRPhoneMultiFactorID;
  83. @implementation FIRPhoneAuthProvider {
  84. /** @var _auth
  85. @brief The auth instance used for verifying the phone number.
  86. */
  87. FIRAuth *_auth;
  88. /** @var _callbackScheme
  89. @brief The callback URL scheme used for reCAPTCHA fallback.
  90. */
  91. NSString *_callbackScheme;
  92. }
  93. /** @fn initWithAuth:
  94. @brief returns an instance of @c FIRPhoneAuthProvider associated with the provided auth
  95. instance.
  96. @return An Instance of @c FIRPhoneAuthProvider.
  97. */
  98. - (nullable instancetype)initWithAuth:(FIRAuth *)auth {
  99. self = [super init];
  100. if (self) {
  101. _auth = auth;
  102. _callbackScheme = [[[_auth.app.options.clientID componentsSeparatedByString:@"."]
  103. reverseObjectEnumerator].allObjects componentsJoinedByString:@"."];
  104. }
  105. return self;
  106. }
  107. - (void)verifyPhoneNumber:(NSString *)phoneNumber
  108. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  109. completion:(nullable FIRVerificationResultCallback)completion {
  110. if (![FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:_callbackScheme]) {
  111. [NSException raise:NSInternalInconsistencyException
  112. format:@"Please register custom URL scheme '%@' in the app's Info.plist file.",
  113. _callbackScheme];
  114. }
  115. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  116. FIRVerificationResultCallback callBackOnMainThread =
  117. ^(NSString *_Nullable verificationID, NSError *_Nullable error) {
  118. if (completion) {
  119. dispatch_async(dispatch_get_main_queue(), ^{
  120. completion(verificationID, error);
  121. });
  122. }
  123. };
  124. [self
  125. internalVerifyPhoneNumber:phoneNumber
  126. UIDelegate:UIDelegate
  127. completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) {
  128. if (!error) {
  129. callBackOnMainThread(verificationID, nil);
  130. return;
  131. } else {
  132. callBackOnMainThread(nil, error);
  133. return;
  134. }
  135. }];
  136. });
  137. }
  138. - (void)verifyPhoneNumberWithMultiFactorInfo:(FIRPhoneMultiFactorInfo *)phoneMultiFactorInfo
  139. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  140. multiFactorSession:(nullable FIRMultiFactorSession *)session
  141. completion:(nullable FIRVerificationResultCallback)completion {
  142. session.multiFactorInfo = phoneMultiFactorInfo;
  143. [self verifyPhoneNumber:phoneMultiFactorInfo.phoneNumber
  144. UIDelegate:UIDelegate
  145. multiFactorSession:session
  146. completion:completion];
  147. }
  148. - (void)verifyPhoneNumber:(NSString *)phoneNumber
  149. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  150. multiFactorSession:(nullable FIRMultiFactorSession *)session
  151. completion:(nullable FIRVerificationResultCallback)completion {
  152. if (!session) {
  153. [self verifyPhoneNumber:phoneNumber UIDelegate:UIDelegate completion:completion];
  154. return;
  155. }
  156. if (![FIRAuthWebUtils isCallbackSchemeRegisteredForCustomURLScheme:_callbackScheme]) {
  157. [NSException raise:NSInternalInconsistencyException
  158. format:@"Please register custom URL scheme '%@' in the app's Info.plist file.",
  159. _callbackScheme];
  160. }
  161. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  162. FIRVerificationResultCallback callBackOnMainThread =
  163. ^(NSString *_Nullable verificationID, NSError *_Nullable error) {
  164. if (completion) {
  165. dispatch_async(dispatch_get_main_queue(), ^{
  166. completion(verificationID, error);
  167. });
  168. }
  169. };
  170. [self
  171. internalVerifyPhoneNumber:phoneNumber
  172. UIDelegate:UIDelegate
  173. multiFactorSession:session
  174. completion:^(NSString *_Nullable verificationID, NSError *_Nullable error) {
  175. if (!error) {
  176. callBackOnMainThread(verificationID, nil);
  177. return;
  178. } else {
  179. callBackOnMainThread(nil, error);
  180. return;
  181. }
  182. }];
  183. });
  184. }
  185. - (FIRPhoneAuthCredential *)credentialWithVerificationID:(NSString *)verificationID
  186. verificationCode:(NSString *)verificationCode {
  187. return [[FIRPhoneAuthCredential alloc] initWithProviderID:FIRPhoneAuthProviderID
  188. verificationID:verificationID
  189. verificationCode:verificationCode];
  190. }
  191. + (instancetype)provider {
  192. return [[self alloc] initWithAuth:[FIRAuth auth]];
  193. }
  194. + (instancetype)providerWithAuth:(FIRAuth *)auth {
  195. return [[self alloc] initWithAuth:auth];
  196. }
  197. #pragma mark - Internal Methods
  198. /** @fn reCAPTCHATokenForURL:error:
  199. @brief Parses the reCAPTCHA URL and returns the reCAPTCHA token.
  200. @param URL The url to be parsed for a reCAPTCHA token.
  201. @param error The error that occurred if any.
  202. @return The reCAPTCHA token if successful.
  203. */
  204. - (NSString *)reCAPTCHATokenForURL:(NSURL *)URL error:(NSError **)error {
  205. NSURLComponents *actualURLComponents = [NSURLComponents componentsWithURL:URL
  206. resolvingAgainstBaseURL:NO];
  207. NSArray<NSURLQueryItem *> *queryItems = [actualURLComponents queryItems];
  208. NSString *deepLinkURL = [FIRAuthWebUtils queryItemValue:@"deep_link_id" from:queryItems];
  209. NSData *errorData;
  210. if (deepLinkURL) {
  211. actualURLComponents = [NSURLComponents componentsWithString:deepLinkURL];
  212. queryItems = [actualURLComponents queryItems];
  213. NSString *recaptchaToken = [FIRAuthWebUtils queryItemValue:@"recaptchaToken" from:queryItems];
  214. if (recaptchaToken) {
  215. return recaptchaToken;
  216. }
  217. NSString *firebaseError = [FIRAuthWebUtils queryItemValue:@"firebaseError" from:queryItems];
  218. errorData = [firebaseError dataUsingEncoding:NSUTF8StringEncoding];
  219. } else {
  220. errorData = nil;
  221. }
  222. NSError *jsonError;
  223. NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData
  224. options:0
  225. error:&jsonError];
  226. if (jsonError) {
  227. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  228. return nil;
  229. }
  230. *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"]
  231. message:errorDict[@"message"]];
  232. if (!*error) {
  233. NSString *reason;
  234. if (errorDict[@"code"] && errorDict[@"message"]) {
  235. reason = [NSString stringWithFormat:@"[%@] - %@", errorDict[@"code"], errorDict[@"message"]];
  236. } else {
  237. reason = [NSString stringWithFormat:@"An unknown error occurred with the following "
  238. "response: %@",
  239. deepLinkURL];
  240. }
  241. *error = [FIRAuthErrorUtils appVerificationUserInteractionFailureWithReason:reason];
  242. }
  243. return nil;
  244. }
  245. /** @fn internalVerifyPhoneNumber:completion:
  246. @brief Starts the phone number authentication flow by sending a verifcation code to the
  247. specified phone number.
  248. @param phoneNumber The phone number to be verified.
  249. @param completion The callback to be invoked when the verification flow is finished.
  250. */
  251. - (void)internalVerifyPhoneNumber:(NSString *)phoneNumber
  252. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  253. completion:(nullable FIRVerificationResultCallback)completion {
  254. if (!phoneNumber.length) {
  255. completion(nil, [FIRAuthErrorUtils missingPhoneNumberErrorWithMessage:nil]);
  256. return;
  257. }
  258. [_auth.notificationManager
  259. checkNotificationForwardingWithCallback:^(BOOL isNotificationBeingForwarded) {
  260. if (!isNotificationBeingForwarded) {
  261. completion(nil, [FIRAuthErrorUtils notificationNotForwardedError]);
  262. return;
  263. }
  264. FIRVerificationResultCallback callback =
  265. ^(NSString *_Nullable verificationID, NSError *_Nullable error) {
  266. if (completion) {
  267. completion(verificationID, error);
  268. }
  269. };
  270. [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber
  271. retryOnInvalidAppCredential:YES
  272. UIDelegate:UIDelegate
  273. callback:callback];
  274. }];
  275. }
  276. - (void)internalVerifyPhoneNumber:(NSString *)phoneNumber
  277. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  278. multiFactorSession:(nullable FIRMultiFactorSession *)session
  279. completion:(nullable FIRVerificationResultCallback)completion {
  280. if (!phoneNumber.length) {
  281. if (completion) {
  282. completion(nil, [FIRAuthErrorUtils missingPhoneNumberErrorWithMessage:nil]);
  283. }
  284. return;
  285. }
  286. [_auth.notificationManager
  287. checkNotificationForwardingWithCallback:^(BOOL isNotificationBeingForwarded) {
  288. if (!isNotificationBeingForwarded) {
  289. if (completion) {
  290. completion(nil, [FIRAuthErrorUtils notificationNotForwardedError]);
  291. }
  292. return;
  293. }
  294. FIRVerificationResultCallback callback =
  295. ^(NSString *_Nullable verificationID, NSError *_Nullable error) {
  296. if (completion) {
  297. completion(verificationID, error);
  298. }
  299. };
  300. [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber
  301. retryOnInvalidAppCredential:YES
  302. UIDelegate:UIDelegate
  303. multiFactorSession:session
  304. callback:callback];
  305. }];
  306. }
  307. /** @fn verifyClientAndSendVerificationCodeToPhoneNumber:retryOnInvalidAppCredential:callback:
  308. @brief Starts the flow to verify the client via silent push notification.
  309. @param retryOnInvalidAppCredential Whether of not the flow should be retried if an
  310. FIRAuthErrorCodeInvalidAppCredential error is returned from the backend.
  311. @param phoneNumber The phone number to be verified.
  312. @param callback The callback to be invoked on the global work queue when the flow is
  313. finished.
  314. */
  315. - (void)verifyClientAndSendVerificationCodeToPhoneNumber:(NSString *)phoneNumber
  316. retryOnInvalidAppCredential:(BOOL)retryOnInvalidAppCredential
  317. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  318. callback:(FIRVerificationResultCallback)callback {
  319. if (_auth.settings.isAppVerificationDisabledForTesting) {
  320. FIRSendVerificationCodeRequest *request =
  321. [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber
  322. appCredential:nil
  323. reCAPTCHAToken:nil
  324. requestConfiguration:_auth.requestConfiguration];
  325. [FIRAuthBackend sendVerificationCode:request
  326. callback:^(FIRSendVerificationCodeResponse *_Nullable response,
  327. NSError *_Nullable error) {
  328. callback(response.verificationID, error);
  329. }];
  330. return;
  331. }
  332. [self
  333. verifyClientWithUIDelegate:UIDelegate
  334. completion:^(FIRAuthAppCredential *_Nullable appCredential,
  335. NSString *_Nullable reCAPTCHAToken, NSError *_Nullable error) {
  336. if (error) {
  337. callback(nil, error);
  338. return;
  339. }
  340. FIRSendVerificationCodeRequest *_Nullable request;
  341. if (appCredential) {
  342. request = [[FIRSendVerificationCodeRequest alloc]
  343. initWithPhoneNumber:phoneNumber
  344. appCredential:appCredential
  345. reCAPTCHAToken:nil
  346. requestConfiguration:self->_auth.requestConfiguration];
  347. } else if (reCAPTCHAToken) {
  348. request = [[FIRSendVerificationCodeRequest alloc]
  349. initWithPhoneNumber:phoneNumber
  350. appCredential:nil
  351. reCAPTCHAToken:reCAPTCHAToken
  352. requestConfiguration:self->_auth.requestConfiguration];
  353. }
  354. if (request) {
  355. [FIRAuthBackend
  356. sendVerificationCode:request
  357. callback:^(
  358. FIRSendVerificationCodeResponse *_Nullable response,
  359. NSError *_Nullable error) {
  360. if (error) {
  361. if (error.code ==
  362. FIRAuthErrorCodeInvalidAppCredential) {
  363. if (retryOnInvalidAppCredential) {
  364. [self->_auth
  365. .appCredentialManager clearCredential];
  366. [self
  367. verifyClientAndSendVerificationCodeToPhoneNumber:
  368. phoneNumber
  369. retryOnInvalidAppCredential:
  370. NO
  371. UIDelegate:
  372. UIDelegate
  373. callback:
  374. callback];
  375. return;
  376. }
  377. callback(
  378. nil,
  379. [FIRAuthErrorUtils
  380. unexpectedResponseWithDeserializedResponse:
  381. nil
  382. underlyingError:
  383. error]);
  384. return;
  385. }
  386. callback(nil, error);
  387. return;
  388. }
  389. callback(response.verificationID, nil);
  390. }];
  391. }
  392. }];
  393. }
  394. - (void)verifyClientAndSendVerificationCodeToPhoneNumber:(NSString *)phoneNumber
  395. retryOnInvalidAppCredential:(BOOL)retryOnInvalidAppCredential
  396. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  397. multiFactorSession:(nullable FIRMultiFactorSession *)session
  398. callback:(FIRVerificationResultCallback)callback {
  399. if (_auth.settings.isAppVerificationDisabledForTesting) {
  400. FIRSendVerificationCodeRequest *request =
  401. [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber
  402. appCredential:nil
  403. reCAPTCHAToken:nil
  404. requestConfiguration:_auth.requestConfiguration];
  405. [FIRAuthBackend sendVerificationCode:request
  406. callback:^(FIRSendVerificationCodeResponse *_Nullable response,
  407. NSError *_Nullable error) {
  408. callback(response.verificationID, error);
  409. }];
  410. return;
  411. }
  412. [self
  413. verifyClientWithUIDelegate:UIDelegate
  414. completion:^(FIRAuthAppCredential *_Nullable appCredential,
  415. NSString *_Nullable reCAPTCHAToken, NSError *_Nullable error) {
  416. if (error) {
  417. if (callback) {
  418. callback(nil, error);
  419. }
  420. return;
  421. }
  422. NSString *IDToken = session.IDToken;
  423. NSString *multiFactorProvider = FIRPhoneMultiFactorID;
  424. FIRAuthProtoStartMFAPhoneRequestInfo *startMFARequestInfo =
  425. [[FIRAuthProtoStartMFAPhoneRequestInfo alloc]
  426. initWithPhoneNumber:phoneNumber
  427. appCredential:appCredential
  428. reCAPTCHAToken:reCAPTCHAToken];
  429. if (session.IDToken) {
  430. FIRStartMFAEnrollmentRequest *request =
  431. [[FIRStartMFAEnrollmentRequest alloc]
  432. initWithIDToken:IDToken
  433. multiFactorProvider:multiFactorProvider
  434. enrollmentInfo:startMFARequestInfo
  435. requestConfiguration:self->_auth.requestConfiguration];
  436. [FIRAuthBackend
  437. startMultiFactorEnrollment:request
  438. callback:^(FIRStartMFAEnrollmentResponse
  439. *_Nullable response,
  440. NSError *_Nullable error) {
  441. if (error) {
  442. if (error.code ==
  443. FIRAuthErrorCodeInvalidAppCredential) {
  444. if (retryOnInvalidAppCredential) {
  445. [self->_auth.appCredentialManager
  446. clearCredential];
  447. [self
  448. verifyClientAndSendVerificationCodeToPhoneNumber:
  449. phoneNumber
  450. retryOnInvalidAppCredential:
  451. NO
  452. UIDelegate:
  453. UIDelegate
  454. multiFactorSession:
  455. session
  456. callback:
  457. callback];
  458. return;
  459. }
  460. if (callback) {
  461. callback(
  462. nil,
  463. [FIRAuthErrorUtils
  464. unexpectedResponseWithDeserializedResponse:
  465. nil
  466. underlyingError:
  467. error]);
  468. }
  469. return;
  470. } else {
  471. if (callback) {
  472. callback(nil, error);
  473. }
  474. }
  475. } else {
  476. if (callback) {
  477. callback(
  478. response.enrollmentResponse.sessionInfo,
  479. nil);
  480. }
  481. }
  482. }];
  483. } else {
  484. FIRStartMFASignInRequest *request = [[FIRStartMFASignInRequest alloc]
  485. initWithMFAProvider:multiFactorProvider
  486. MFAPendingCredential:session.MFAPendingCredential
  487. MFAEnrollmentID:session.multiFactorInfo.UID
  488. signInInfo:startMFARequestInfo
  489. requestConfiguration:self->_auth.requestConfiguration];
  490. [FIRAuthBackend
  491. startMultiFactorSignIn:request
  492. callback:^(
  493. FIRStartMFASignInResponse *_Nullable response,
  494. NSError *_Nullable error) {
  495. if (error) {
  496. if (error.code ==
  497. FIRAuthErrorCodeInvalidAppCredential) {
  498. if (retryOnInvalidAppCredential) {
  499. [self->_auth
  500. .appCredentialManager clearCredential];
  501. [self
  502. verifyClientAndSendVerificationCodeToPhoneNumber:
  503. phoneNumber
  504. retryOnInvalidAppCredential:
  505. NO
  506. UIDelegate:
  507. UIDelegate
  508. multiFactorSession:
  509. session
  510. callback:
  511. callback];
  512. return;
  513. }
  514. if (callback) {
  515. callback(
  516. nil,
  517. [FIRAuthErrorUtils
  518. unexpectedResponseWithDeserializedResponse:
  519. nil
  520. underlyingError:
  521. error]);
  522. }
  523. return;
  524. } else {
  525. if (callback) {
  526. callback(nil, error);
  527. }
  528. }
  529. } else {
  530. if (callback) {
  531. callback(response.responseInfo.sessionInfo, nil);
  532. }
  533. }
  534. }];
  535. }
  536. }];
  537. }
  538. /** @fn verifyClientWithCompletion:completion:
  539. @brief Continues the flow to verify the client via silent push notification.
  540. @param completion The callback to be invoked when the client verification flow is finished.
  541. */
  542. - (void)verifyClientWithUIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  543. completion:(FIRVerifyClientCallback)completion {
  544. if (_auth.appCredentialManager.credential) {
  545. completion(_auth.appCredentialManager.credential, nil, nil);
  546. return;
  547. }
  548. [_auth.tokenManager getTokenWithCallback:^(FIRAuthAPNSToken *_Nullable token,
  549. NSError *_Nullable error) {
  550. if (!token) {
  551. [self reCAPTCHAFlowWithUIDelegate:UIDelegate completion:completion];
  552. return;
  553. }
  554. FIRVerifyClientRequest *request =
  555. [[FIRVerifyClientRequest alloc] initWithAppToken:token.string
  556. isSandbox:token.type == FIRAuthAPNSTokenTypeSandbox
  557. requestConfiguration:self->_auth.requestConfiguration];
  558. [FIRAuthBackend
  559. verifyClient:request
  560. callback:^(FIRVerifyClientResponse *_Nullable response, NSError *_Nullable error) {
  561. if (error) {
  562. NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey];
  563. BOOL isInvalidAppCredential =
  564. error.code == FIRAuthErrorCodeInternalError &&
  565. underlyingError.code == FIRAuthErrorCodeInvalidAppCredential;
  566. if (error.code != FIRAuthErrorCodeMissingAppToken && !isInvalidAppCredential) {
  567. completion(nil, nil, error);
  568. return;
  569. } else {
  570. [self reCAPTCHAFlowWithUIDelegate:UIDelegate completion:completion];
  571. return;
  572. }
  573. }
  574. NSTimeInterval timeout = [response.suggestedTimeOutDate timeIntervalSinceNow];
  575. [self->_auth.appCredentialManager
  576. didStartVerificationWithReceipt:response.receipt
  577. timeout:timeout
  578. callback:^(FIRAuthAppCredential *credential) {
  579. if (!credential.secret) {
  580. FIRLogWarning(kFIRLoggerAuth, @"I-AUT000014",
  581. @"Failed to receive remote notification "
  582. @"to verify app identity within "
  583. @"%.0f second(s)",
  584. timeout);
  585. }
  586. completion(credential, nil, nil);
  587. }];
  588. }];
  589. }];
  590. }
  591. - (void)reCAPTCHAFlowWithUIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  592. completion:(FIRVerifyClientCallback)completion {
  593. NSString *eventID = [FIRAuthWebUtils randomStringWithLength:10];
  594. [self
  595. reCAPTCHAURLWithEventID:eventID
  596. completion:^(NSURL *_Nullable reCAPTCHAURL, NSError *_Nullable error) {
  597. if (error) {
  598. completion(nil, nil, error);
  599. return;
  600. }
  601. FIRAuthURLCallbackMatcher callbackMatcher =
  602. ^BOOL(NSURL *_Nullable callbackURL) {
  603. return [FIRAuthWebUtils isExpectedCallbackURL:callbackURL
  604. eventID:eventID
  605. authType:kAuthTypeVerifyApp
  606. callbackScheme:self->_callbackScheme];
  607. };
  608. [self->_auth.authURLPresenter
  609. presentURL:reCAPTCHAURL
  610. UIDelegate:UIDelegate
  611. callbackMatcher:callbackMatcher
  612. completion:^(NSURL *_Nullable callbackURL, NSError *_Nullable error) {
  613. if (error) {
  614. completion(nil, nil, error);
  615. return;
  616. }
  617. NSError *reCAPTCHAError;
  618. NSString *reCAPTCHAToken =
  619. [self reCAPTCHATokenForURL:callbackURL error:&reCAPTCHAError];
  620. if (!reCAPTCHAToken) {
  621. completion(nil, nil, reCAPTCHAError);
  622. return;
  623. } else {
  624. completion(nil, reCAPTCHAToken, nil);
  625. return;
  626. }
  627. }];
  628. }];
  629. }
  630. /** @fn reCAPTCHAURLWithEventID:completion:
  631. @brief Constructs a URL used for opening a reCAPTCHA app verification flow using a given event
  632. ID.
  633. @param eventID The event ID used for this purpose.
  634. @param completion The callback invoked after the URL has been constructed or an error
  635. has been encountered.
  636. */
  637. - (void)reCAPTCHAURLWithEventID:(NSString *)eventID completion:(FIRReCAPTCHAURLCallBack)completion {
  638. [FIRAuthWebUtils
  639. fetchAuthDomainWithRequestConfiguration:_auth.requestConfiguration
  640. completion:^(NSString *_Nullable authDomain,
  641. NSError *_Nullable error) {
  642. if (error) {
  643. if (completion) {
  644. completion(nil, error);
  645. return;
  646. }
  647. }
  648. NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
  649. NSString *clientID = self->_auth.app.options.clientID;
  650. NSString *apiKey = self->_auth.requestConfiguration.APIKey;
  651. NSMutableArray<NSURLQueryItem *> *queryItems = [@[
  652. [NSURLQueryItem queryItemWithName:@"apiKey" value:apiKey],
  653. [NSURLQueryItem queryItemWithName:@"authType"
  654. value:kAuthTypeVerifyApp],
  655. [NSURLQueryItem queryItemWithName:@"ibi"
  656. value:bundleID ?: @""],
  657. [NSURLQueryItem queryItemWithName:@"clientId"
  658. value:clientID],
  659. [NSURLQueryItem
  660. queryItemWithName:@"v"
  661. value:[FIRAuthBackend authUserAgent]],
  662. [NSURLQueryItem queryItemWithName:@"eventId" value:eventID]
  663. ] mutableCopy];
  664. if (self->_auth.requestConfiguration.languageCode) {
  665. [queryItems
  666. addObject:[NSURLQueryItem
  667. queryItemWithName:@"hl"
  668. value:self->_auth
  669. .requestConfiguration
  670. .languageCode]];
  671. }
  672. NSURLComponents *components = [[NSURLComponents alloc]
  673. initWithString:
  674. [NSString stringWithFormat:kReCAPTCHAURLStringFormat,
  675. authDomain]];
  676. [components setQueryItems:queryItems];
  677. if (completion) {
  678. completion([components URL], nil);
  679. }
  680. }];
  681. }
  682. @end
  683. NS_ASSUME_NONNULL_END
  684. #endif