FIRPhoneAuthProvider.m 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 "FIRPhoneAuthProvider.h"
  17. #import <GoogleToolboxForMac/GTMNSDictionary+URLArguments.h>
  18. #import <FirebaseCore/FIRLogger.h>
  19. #import "FIRPhoneAuthCredential_Internal.h"
  20. #import <FirebaseCore/FIRApp.h>
  21. #import "FIRAuthAPNSToken.h"
  22. #import "FIRAuthAPNSTokenManager.h"
  23. #import "FIRAuthAppCredential.h"
  24. #import "FIRAuthAppCredentialManager.h"
  25. #import "FIRAuthGlobalWorkQueue.h"
  26. #import "FIRAuth_Internal.h"
  27. #import "FIRAuthURLPresenter.h"
  28. #import "FIRAuthNotificationManager.h"
  29. #import "FIRAuthErrorUtils.h"
  30. #import "FIRAuthBackend.h"
  31. #import "FirebaseAuthVersion.h"
  32. #import <FirebaseCore/FIROptions.h>
  33. #import "FIRGetProjectConfigRequest.h"
  34. #import "FIRGetProjectConfigResponse.h"
  35. #import "FIRSendVerificationCodeRequest.h"
  36. #import "FIRSendVerificationCodeResponse.h"
  37. #import "FIRVerifyClientRequest.h"
  38. #import "FIRVerifyClientResponse.h"
  39. NS_ASSUME_NONNULL_BEGIN
  40. /** @typedef FIRReCAPTCHAURLCallBack
  41. @brief The callback invoked at the end of the flow to fetch a reCAPTCHA URL.
  42. @param reCAPTCHAURL The reCAPTCHA URL.
  43. @param error The error that occured while fetching the reCAPTCHAURL, if any.
  44. */
  45. typedef void (^FIRReCAPTCHAURLCallBack)(NSURL *_Nullable reCAPTCHAURL, NSError *_Nullable error);
  46. /** @typedef FIRVerifyClientCallback
  47. @brief The callback invoked at the end of a client verification flow.
  48. @param appCredential credential that proves the identity of the app during a phone
  49. authentication flow.
  50. @param error The error that occured while verifying the app, if any.
  51. */
  52. typedef void (^FIRVerifyClientCallback)(FIRAuthAppCredential *_Nullable appCredential,
  53. NSError *_Nullable error);
  54. /** @typedef FIRFetchAuthDomainCallback
  55. @brief The callback invoked at the end of the flow to fetch the Auth domain.
  56. @param authDomain The Auth domain.
  57. @param error The error that occured while fetching the auth domain, if any.
  58. */
  59. typedef void (^FIRFetchAuthDomainCallback)(NSString *_Nullable authDomain,
  60. NSError *_Nullable error);
  61. /** @var kAuthDomainSuffix
  62. @brief The suffix of the auth domain pertiaining to a given Firebase project.
  63. */
  64. static NSString *const kAuthDomainSuffix = @"firebaseapp.com";
  65. /** @var kauthTypeVerifyApp
  66. @brief The auth type to be specified in the app verification request.
  67. */
  68. static NSString *const kAuthTypeVerifyApp = @"verifyApp";
  69. /** @var kReCAPTCHAURLStringFormat
  70. @brief The format of the URL used to open the reCAPTCHA page during app verification.
  71. */
  72. NSString *const kReCAPTCHAURLStringFormat = @"https://%@/__/auth/handler?%@";
  73. @implementation FIRPhoneAuthProvider {
  74. /** @var _auth
  75. @brief The auth instance used for verifying the phone number.
  76. */
  77. FIRAuth *_auth;
  78. /** @var _callbackScheme
  79. @brief The callback URL scheme used for reCAPTCHA fallback.
  80. */
  81. NSString *_callbackScheme;
  82. }
  83. /** @fn initWithAuth:
  84. @brief returns an instance of @c FIRPhoneAuthProvider assocaited with the provided auth
  85. instance.
  86. @return An Instance of @c FIRPhoneAuthProvider.
  87. */
  88. - (nullable instancetype)initWithAuth:(FIRAuth *)auth {
  89. self = [super init];
  90. if (self) {
  91. _auth = auth;
  92. _callbackScheme = [[[_auth.app.options.clientID componentsSeparatedByString:@"."]
  93. reverseObjectEnumerator].allObjects componentsJoinedByString:@"."];
  94. }
  95. return self;
  96. }
  97. - (void)verifyPhoneNumber:(NSString *)phoneNumber
  98. completion:(nullable FIRVerificationResultCallback)completion {
  99. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  100. [self internalVerifyPhoneNumber:phoneNumber completion:^(NSString *_Nullable verificationID,
  101. NSError *_Nullable error) {
  102. if (completion) {
  103. dispatch_async(dispatch_get_main_queue(), ^{
  104. completion(verificationID, error);
  105. });
  106. }
  107. }];
  108. });
  109. }
  110. - (void)verifyPhoneNumber:(NSString *)phoneNumber
  111. UIDelegate:(nullable id<FIRAuthUIDelegate>)UIDelegate
  112. completion:(nullable FIRVerificationResultCallback)completion {
  113. if (![self isCallbackSchemeRegistered]) {
  114. [NSException raise:NSInternalInconsistencyException
  115. format:@"Please register custom URL scheme '%@' in the app's Info.plist file.",
  116. _callbackScheme];
  117. }
  118. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  119. FIRVerificationResultCallback callBackOnMainThread = ^(NSString *_Nullable verificationID,
  120. NSError *_Nullable error) {
  121. if (completion) {
  122. dispatch_async(dispatch_get_main_queue(), ^{
  123. completion(verificationID, error);
  124. });
  125. }
  126. };
  127. [self internalVerifyPhoneNumber:phoneNumber completion:^(NSString *_Nullable verificationID,
  128. NSError *_Nullable error) {
  129. if (!error) {
  130. callBackOnMainThread(verificationID, nil);
  131. return;
  132. }
  133. NSError *underlyingError = error.userInfo[NSUnderlyingErrorKey];
  134. BOOL isInvalidAppCredential = error.code == FIRAuthErrorCodeInternalError &&
  135. underlyingError.code == FIRAuthErrorCodeInvalidAppCredential;
  136. if (error.code != FIRAuthErrorCodeMissingAppToken && !isInvalidAppCredential) {
  137. callBackOnMainThread(nil, error);
  138. return;
  139. }
  140. NSMutableString *eventID = [[NSMutableString alloc] init];
  141. for (int i=0; i<10; i++) {
  142. [eventID appendString:
  143. [NSString stringWithFormat:@"%c", 'a' + arc4random_uniform('z' - 'a' + 1)]];
  144. }
  145. [self reCAPTCHAURLWithEventID:eventID completion:^(NSURL *_Nullable reCAPTCHAURL,
  146. NSError *_Nullable error) {
  147. if (error) {
  148. callBackOnMainThread(nil, error);
  149. return;
  150. }
  151. FIRAuthURLCallbackMatcher callbackMatcher = ^BOOL(NSURL *_Nullable callbackURL) {
  152. return [self isVerifyAppURL:callbackURL eventID:eventID];
  153. };
  154. [_auth.authURLPresenter presentURL:reCAPTCHAURL
  155. UIDelegate:UIDelegate
  156. callbackMatcher:callbackMatcher
  157. completion:^(NSURL *_Nullable callbackURL,
  158. NSError *_Nullable error) {
  159. if (error) {
  160. callBackOnMainThread(nil, error);
  161. return;
  162. }
  163. NSError *reCAPTCHAError;
  164. NSString *reCAPTCHAToken = [self reCAPTCHATokenForURL:callbackURL error:&reCAPTCHAError];
  165. if (!reCAPTCHAToken) {
  166. callBackOnMainThread(nil, reCAPTCHAError);
  167. return;
  168. }
  169. FIRSendVerificationCodeRequest *request =
  170. [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber
  171. appCredential:nil
  172. reCAPTCHAToken:reCAPTCHAToken
  173. requestConfiguration:_auth.requestConfiguration];
  174. [FIRAuthBackend sendVerificationCode:request
  175. callback:^(FIRSendVerificationCodeResponse
  176. *_Nullable response, NSError *_Nullable error) {
  177. if (error) {
  178. callBackOnMainThread(nil, error);
  179. return;
  180. }
  181. callBackOnMainThread(response.verificationID, nil);
  182. }];
  183. }];
  184. }];
  185. }];
  186. });
  187. }
  188. - (FIRPhoneAuthCredential *)credentialWithVerificationID:(NSString *)verificationID
  189. verificationCode:(NSString *)verificationCode {
  190. return [[FIRPhoneAuthCredential alloc] initWithProviderID:FIRPhoneAuthProviderID
  191. verificationID:verificationID
  192. verificationCode:verificationCode];
  193. }
  194. + (instancetype)provider {
  195. return [[self alloc]initWithAuth:[FIRAuth auth]];
  196. }
  197. + (instancetype)providerWithAuth:(FIRAuth *)auth {
  198. return [[self alloc]initWithAuth:auth];
  199. }
  200. #pragma mark - Internal Methods
  201. /** @fn isCallbackSchemeRegistered
  202. @brief Checks whether or not the expected callback scheme has been registered by the app.
  203. @remarks This method is thread-safe.
  204. */
  205. - (BOOL)isCallbackSchemeRegistered {
  206. NSString *expectedCustomScheme = [_callbackScheme lowercaseString];
  207. NSArray *urlTypes = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleURLTypes"];
  208. for (NSDictionary *urlType in urlTypes) {
  209. NSArray *urlTypeSchemes = urlType[@"CFBundleURLSchemes"];
  210. for (NSString *urlTypeScheme in urlTypeSchemes) {
  211. if ([urlTypeScheme.lowercaseString isEqualToString:expectedCustomScheme]) {
  212. return YES;
  213. }
  214. }
  215. }
  216. return NO;
  217. }
  218. /** @fn reCAPTCHATokenForURL:error:
  219. @brief Parses the reCAPTCHA URL and returns.
  220. @param URL The url to be parsed for a reCAPTCHA token.
  221. @param error The error that occurred if any.
  222. @return The reCAPTCHA token if successful.
  223. */
  224. - (NSString *)reCAPTCHATokenForURL:(NSURL *)URL error:(NSError **)error {
  225. NSDictionary<NSString *, NSString *> *URLQueryItems =
  226. [NSDictionary gtm_dictionaryWithHttpArgumentsString:URL.query];
  227. NSURL *deepLinkURL = [NSURL URLWithString:URLQueryItems[@"deep_link_id"]];
  228. URLQueryItems =
  229. [NSDictionary gtm_dictionaryWithHttpArgumentsString:deepLinkURL.query];
  230. if (URLQueryItems[@"recaptchaToken"]) {
  231. return URLQueryItems[@"recaptchaToken"];
  232. }
  233. NSData *errorData = [URLQueryItems[@"firebaseError"] dataUsingEncoding:NSUTF8StringEncoding];
  234. NSError *jsonError;
  235. NSDictionary *errorDict = [NSJSONSerialization JSONObjectWithData:errorData
  236. options:0
  237. error:&jsonError];
  238. if (jsonError) {
  239. *error = [FIRAuthErrorUtils JSONSerializationErrorWithUnderlyingError:jsonError];
  240. return nil;
  241. }
  242. *error = [FIRAuthErrorUtils URLResponseErrorWithCode:errorDict[@"code"]
  243. message:errorDict[@"message"]];
  244. if (!*error) {
  245. NSString *reason;
  246. if(errorDict[@"code"] && errorDict[@"message"]) {
  247. reason = [NSString stringWithFormat:@"[%@] - %@",errorDict[@"code"], errorDict[@"message"]];
  248. } else {
  249. reason = [NSString stringWithFormat:@"An unknown error occurred with the following "
  250. "response: %@", deepLinkURL];
  251. }
  252. *error = [FIRAuthErrorUtils appVerificationUserInteractionFailureWithReason:reason];
  253. }
  254. return nil;
  255. }
  256. /** @fn isVerifyAppURL:
  257. @brief Parses a URL into all available query items.
  258. @param URL The url to be checked against the authType string.
  259. @return Whether or not the URL matches authType.
  260. */
  261. - (BOOL)isVerifyAppURL:(nullable NSURL *)URL eventID:(NSString *)eventID {
  262. if (!URL) {
  263. return NO;
  264. }
  265. NSURLComponents *actualURLComponents =
  266. [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO];
  267. actualURLComponents.query = nil;
  268. actualURLComponents.fragment = nil;
  269. NSURLComponents *expectedURLComponents = [NSURLComponents new];
  270. expectedURLComponents.scheme = _callbackScheme;
  271. expectedURLComponents.host = @"firebaseauth";
  272. expectedURLComponents.path = @"/link";
  273. if (!([[expectedURLComponents URL] isEqual:[actualURLComponents URL]])) {
  274. return NO;
  275. }
  276. NSDictionary<NSString *, NSString *> *URLQueryItems =
  277. [NSDictionary gtm_dictionaryWithHttpArgumentsString:URL.query];
  278. NSURL *deeplinkURL = [NSURL URLWithString:URLQueryItems[@"deep_link_id"]];
  279. NSDictionary<NSString *, NSString *> *deeplinkQueryItems =
  280. [NSDictionary gtm_dictionaryWithHttpArgumentsString:deeplinkURL.query];
  281. if ([deeplinkQueryItems[@"authType"] isEqualToString:kAuthTypeVerifyApp] &&
  282. [deeplinkQueryItems[@"eventId"] isEqualToString:eventID]) {
  283. return YES;
  284. }
  285. return NO;
  286. }
  287. /** @fn internalVerifyPhoneNumber:completion:
  288. @brief Starts the phone number authentication flow by sending a verifcation code to the
  289. specified phone number.
  290. @param phoneNumber The phone number to be verified.
  291. @param completion The callback to be invoked when the verification flow is finished.
  292. */
  293. - (void)internalVerifyPhoneNumber:(NSString *)phoneNumber
  294. completion:(nullable FIRVerificationResultCallback)completion {
  295. if (!phoneNumber.length) {
  296. completion(nil, [FIRAuthErrorUtils missingPhoneNumberErrorWithMessage:nil]);
  297. return;
  298. }
  299. [_auth.notificationManager checkNotificationForwardingWithCallback:
  300. ^(BOOL isNotificationBeingForwarded) {
  301. if (!isNotificationBeingForwarded) {
  302. completion(nil, [FIRAuthErrorUtils notificationNotForwardedError]);
  303. return;
  304. }
  305. FIRVerificationResultCallback callback = ^(NSString *_Nullable verificationID,
  306. NSError *_Nullable error) {
  307. if (completion) {
  308. completion(verificationID, error);
  309. }
  310. };
  311. [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber
  312. retryOnInvalidAppCredential:YES
  313. callback:callback];
  314. }];
  315. }
  316. /** @fn verifyClientAndSendVerificationCodeToPhoneNumber:retryOnInvalidAppCredential:callback:
  317. @brief Starts the flow to verify the client via silent push notification.
  318. @param retryOnInvalidAppCredential Whether of not the flow should be retried if an
  319. FIRAuthErrorCodeInvalidAppCredential error is returned from the backend.
  320. @param phoneNumber The phone number to be verified.
  321. @param callback The callback to be invoked on the global work queue when the flow is
  322. finished.
  323. */
  324. - (void)verifyClientAndSendVerificationCodeToPhoneNumber:(NSString *)phoneNumber
  325. retryOnInvalidAppCredential:(BOOL)retryOnInvalidAppCredential
  326. callback:(FIRVerificationResultCallback)callback {
  327. [self verifyClientWithCompletion:^(FIRAuthAppCredential *_Nullable appCredential,
  328. NSError *_Nullable error) {
  329. if (error) {
  330. callback(nil, error);
  331. return;
  332. }
  333. FIRSendVerificationCodeRequest *request =
  334. [[FIRSendVerificationCodeRequest alloc] initWithPhoneNumber:phoneNumber
  335. appCredential:appCredential
  336. reCAPTCHAToken:nil
  337. requestConfiguration:_auth.requestConfiguration];
  338. [FIRAuthBackend sendVerificationCode:request
  339. callback:^(FIRSendVerificationCodeResponse *_Nullable response,
  340. NSError *_Nullable error) {
  341. if (error) {
  342. if (error.code == FIRAuthErrorCodeInvalidAppCredential) {
  343. if (retryOnInvalidAppCredential) {
  344. [_auth.appCredentialManager clearCredential];
  345. [self verifyClientAndSendVerificationCodeToPhoneNumber:phoneNumber
  346. retryOnInvalidAppCredential:NO
  347. callback:callback];
  348. return;
  349. }
  350. callback(nil, [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:nil
  351. underlyingError:error]);
  352. return;
  353. }
  354. callback(nil, error);
  355. return;
  356. }
  357. callback(response.verificationID, nil);
  358. }];
  359. }];
  360. }
  361. /** @fn verifyClientWithCompletion:completion:
  362. @brief Continues the flow to verify the client via silent push notification.
  363. @param completion The callback to be invoked when the client verification flow is finished.
  364. */
  365. - (void)verifyClientWithCompletion:(FIRVerifyClientCallback)completion {
  366. if (_auth.appCredentialManager.credential) {
  367. completion(_auth.appCredentialManager.credential, nil);
  368. return;
  369. }
  370. [_auth.tokenManager getTokenWithCallback:^(FIRAuthAPNSToken *_Nullable token,
  371. NSError *_Nullable error) {
  372. if (!token) {
  373. completion(nil, [FIRAuthErrorUtils missingAppTokenErrorWithUnderlyingError:error]);
  374. return;
  375. }
  376. FIRVerifyClientRequest *request =
  377. [[FIRVerifyClientRequest alloc] initWithAppToken:token.string
  378. isSandbox:token.type == FIRAuthAPNSTokenTypeSandbox
  379. requestConfiguration:_auth.requestConfiguration];
  380. [FIRAuthBackend verifyClient:request callback:^(FIRVerifyClientResponse *_Nullable response,
  381. NSError *_Nullable error) {
  382. if (error) {
  383. completion(nil, error);
  384. return;
  385. }
  386. NSTimeInterval timeout = [response.suggestedTimeOutDate timeIntervalSinceNow];
  387. [_auth.appCredentialManager
  388. didStartVerificationWithReceipt:response.receipt
  389. timeout:timeout
  390. callback:^(FIRAuthAppCredential *credential) {
  391. if (!credential.secret) {
  392. FIRLogWarning(kFIRLoggerAuth, @"I-AUT000014",
  393. @"Failed to receive remote notification to verify app identity within "
  394. @"%.0f second(s)", timeout);
  395. }
  396. completion(credential, nil);
  397. }];
  398. }];
  399. }];
  400. }
  401. /** @fn reCAPTCHAURLWithEventID:completion:
  402. @brief Constructs a URL used for opening a reCAPTCHA app verification flow using a given event
  403. ID.
  404. @param eventID The event ID used for this purpose.
  405. @param completion The callback invoked after the URL has been constructed or an error
  406. has been encountered.
  407. */
  408. - (void)reCAPTCHAURLWithEventID:(NSString *)eventID completion:(FIRReCAPTCHAURLCallBack)completion {
  409. [self fetchAuthDomainWithCompletion:^(NSString *_Nullable authDomain,
  410. NSError *_Nullable error) {
  411. if (error) {
  412. completion(nil, error);
  413. return;
  414. }
  415. NSString *bundleID = [NSBundle mainBundle].bundleIdentifier;
  416. NSString *clienID = _auth.app.options.clientID;
  417. NSString *apiKey = _auth.requestConfiguration.APIKey;
  418. NSMutableDictionary *urlArguments = [[NSMutableDictionary alloc] initWithDictionary: @{
  419. @"apiKey" : apiKey,
  420. @"authType" : kAuthTypeVerifyApp,
  421. @"ibi" : bundleID ?: @"",
  422. @"clientId" : clienID,
  423. @"v" : [FIRAuthBackend authUserAgent],
  424. @"eventId" : eventID,
  425. }];
  426. if (_auth.requestConfiguration.languageCode) {
  427. urlArguments[@"hl"] = _auth.requestConfiguration.languageCode;
  428. }
  429. NSString *argumentsString = [urlArguments gtm_httpArgumentsString];
  430. NSString *URLString =
  431. [NSString stringWithFormat:kReCAPTCHAURLStringFormat, authDomain, argumentsString];
  432. completion([NSURL URLWithString:URLString], nil);
  433. }];
  434. }
  435. /** @fn fetchAuthDomainWithCompletion:completion:
  436. @brief Fetches the auth domain associated with the Firebase Project.
  437. @param completion The callback invoked after the auth domain has been constructed or an error
  438. has been encountered.
  439. */
  440. - (void)fetchAuthDomainWithCompletion:(FIRFetchAuthDomainCallback)completion {
  441. FIRGetProjectConfigRequest *request =
  442. [[FIRGetProjectConfigRequest alloc] initWithRequestConfiguration:_auth.requestConfiguration];
  443. [FIRAuthBackend getProjectConfig:request
  444. callback:^(FIRGetProjectConfigResponse *_Nullable response,
  445. NSError *_Nullable error) {
  446. if (error) {
  447. completion(nil, error);
  448. return;
  449. }
  450. NSString *authDomain;
  451. for (NSString *domain in response.authorizedDomains) {
  452. NSInteger index = domain.length - kAuthDomainSuffix.length;
  453. if (index >= 2) {
  454. if ([domain hasSuffix:kAuthDomainSuffix] && domain.length >= kAuthDomainSuffix.length + 2) {
  455. authDomain = domain;
  456. break;
  457. }
  458. }
  459. }
  460. if (!authDomain.length) {
  461. completion(nil, [FIRAuthErrorUtils unexpectedErrorResponseWithDeserializedResponse:response]);
  462. return;
  463. }
  464. completion(authDomain, nil);
  465. }];
  466. }
  467. @end
  468. NS_ASSUME_NONNULL_END