FIRPhoneAuthProvider.m 40 KB

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