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.

1873 lines
74 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 "FIRAuth_Internal.h"
  18. #import <FirebaseCore/FIRAppAssociationRegistration.h>
  19. #import <FirebaseCore/FIRAppInternal.h>
  20. #import <FirebaseCore/FIRLogger.h>
  21. #import <FirebaseCore/FIROptions.h>
  22. #import "AuthProviders/EmailPassword/FIREmailPasswordAuthCredential.h"
  23. #import "FIRAdditionalUserInfo_Internal.h"
  24. #import "FIRAuthCredential_Internal.h"
  25. #import "FIRAuthDataResult_Internal.h"
  26. #import "FIRAuthDispatcher.h"
  27. #import "FIRAuthErrorUtils.h"
  28. #import "FIRAuthExceptionUtils.h"
  29. #import "FIRAuthGlobalWorkQueue.h"
  30. #import "FIRAuthKeychain.h"
  31. #import "FIRAuthOperationType.h"
  32. #import "FIRAuthSettings.h"
  33. #import "FIRUser_Internal.h"
  34. #import "FirebaseAuth.h"
  35. #import "FIRAuthBackend.h"
  36. #import "FIRAuthRequestConfiguration.h"
  37. #import "FIRCreateAuthURIRequest.h"
  38. #import "FIRCreateAuthURIResponse.h"
  39. #import "FIREmailLinkSignInRequest.h"
  40. #import "FIREmailLinkSignInResponse.h"
  41. #import "FIRGetOOBConfirmationCodeRequest.h"
  42. #import "FIRGetOOBConfirmationCodeResponse.h"
  43. #import "FIRResetPasswordRequest.h"
  44. #import "FIRResetPasswordResponse.h"
  45. #import "FIRSendVerificationCodeRequest.h"
  46. #import "FIRSendVerificationCodeResponse.h"
  47. #import "FIRSetAccountInfoRequest.h"
  48. #import "FIRSetAccountInfoResponse.h"
  49. #import "FIRSignUpNewUserRequest.h"
  50. #import "FIRSignUpNewUserResponse.h"
  51. #import "FIRVerifyAssertionRequest.h"
  52. #import "FIRVerifyAssertionResponse.h"
  53. #import "FIRVerifyCustomTokenRequest.h"
  54. #import "FIRVerifyCustomTokenResponse.h"
  55. #import "FIRVerifyPasswordRequest.h"
  56. #import "FIRVerifyPasswordResponse.h"
  57. #import "FIRVerifyPhoneNumberRequest.h"
  58. #import "FIRVerifyPhoneNumberResponse.h"
  59. #if TARGET_OS_IOS
  60. #import <UIKit/UIKit.h>
  61. #import "FIRAuthAPNSToken.h"
  62. #import "FIRAuthAPNSTokenManager.h"
  63. #import "FIRAuthAppCredentialManager.h"
  64. #import "FIRAuthAppDelegateProxy.h"
  65. #import "AuthProviders/Phone/FIRPhoneAuthCredential_Internal.h"
  66. #import "FIRAuthNotificationManager.h"
  67. #import "FIRAuthURLPresenter.h"
  68. #endif
  69. #pragma mark - Constants
  70. #if defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  71. const NSNotificationName FIRAuthStateDidChangeNotification = @"FIRAuthStateDidChangeNotification";
  72. #else
  73. NSString *const FIRAuthStateDidChangeNotification = @"FIRAuthStateDidChangeNotification";
  74. #endif // defined(__IPHONE_10_0) && __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
  75. /** @var kMaxWaitTimeForBackoff
  76. @brief The maximum wait time before attempting to retry auto refreshing tokens after a failed
  77. attempt.
  78. @remarks This is the upper limit (in seconds) of the exponential backoff used for retrying
  79. token refresh.
  80. */
  81. static NSTimeInterval kMaxWaitTimeForBackoff = 16 * 60;
  82. /** @var kTokenRefreshHeadStart
  83. @brief The amount of time before the token expires that proactive refresh should be attempted.
  84. */
  85. NSTimeInterval kTokenRefreshHeadStart = 5 * 60;
  86. /** @var kUserKey
  87. @brief Key of user stored in the keychain. Prefixed with a Firebase app name.
  88. */
  89. static NSString *const kUserKey = @"%@_firebase_user";
  90. /** @var kMissingEmailInvalidParameterExceptionReason
  91. @brief The reason for @c invalidParameterException when the email used to initiate password
  92. reset is nil.
  93. */
  94. static NSString *const kMissingEmailInvalidParameterExceptionReason =
  95. @"The email used to initiate password reset cannot be nil.";
  96. /** @var kHandleCodeInAppFalseExceptionReason
  97. @brief The reason for @c invalidParameterException when the handleCodeInApp parameter is false
  98. on the ActionCodeSettings object used to send the link for Email-link Authentication.
  99. */
  100. static NSString *const kHandleCodeInAppFalseExceptionReason =
  101. @"You must set handleCodeInApp in your ActionCodeSettings to true for Email-link "
  102. "Authentication.";
  103. static NSString *const kInvalidEmailSignInLinkExceptionMessage =
  104. @"The link provided is not valid for email/link sign-in. Please check the link by calling "
  105. "isSignInWithEmailLink:link: on Auth before attempting to use it for email/link sign-in.";
  106. /** @var kPasswordResetRequestType
  107. @brief The action code type value for resetting password in the check action code response.
  108. */
  109. static NSString *const kPasswordResetRequestType = @"PASSWORD_RESET";
  110. /** @var kVerifyEmailRequestType
  111. @brief The action code type value for verifying email in the check action code response.
  112. */
  113. static NSString *const kVerifyEmailRequestType = @"VERIFY_EMAIL";
  114. /** @var kRecoverEmailRequestType
  115. @brief The action code type value for recovering email in the check action code response.
  116. */
  117. static NSString *const kRecoverEmailRequestType = @"RECOVER_EMAIL";
  118. /** @var kEmailLinkSignInRequestType
  119. @brief The action code type value for an email sign-in link in the check action code response.
  120. */
  121. static NSString *const kEmailLinkSignInRequestType = @"EMAIL_SIGNIN";
  122. /** @var kMissingPasswordReason
  123. @brief The reason why the @c FIRAuthErrorCodeWeakPassword error is thrown.
  124. @remarks This error message will be localized in the future.
  125. */
  126. static NSString *const kMissingPasswordReason = @"Missing Password";
  127. /** @var gKeychainServiceNameForAppName
  128. @brief A map from Firebase app name to keychain service names.
  129. @remarks This map is needed for looking up the keychain service name after the FIRApp instance
  130. is deleted, to remove the associated keychain item. Accessing should occur within a
  131. @syncronized([FIRAuth class]) context.
  132. */
  133. static NSMutableDictionary *gKeychainServiceNameForAppName;
  134. #pragma mark - FIRActionCodeInfo
  135. @implementation FIRActionCodeInfo {
  136. /** @var _email
  137. @brief The email address to which the code was sent. The new email address in the case of
  138. FIRActionCodeOperationRecoverEmail.
  139. */
  140. NSString *_email;
  141. /** @var _fromEmail
  142. @brief The current email address in the case of FIRActionCodeOperationRecoverEmail.
  143. */
  144. NSString *_fromEmail;
  145. }
  146. - (NSString *)dataForKey:(FIRActionDataKey)key{
  147. switch (key) {
  148. case FIRActionCodeEmailKey:
  149. return _email;
  150. case FIRActionCodeFromEmailKey:
  151. return _fromEmail;
  152. }
  153. }
  154. - (instancetype)initWithOperation:(FIRActionCodeOperation)operation
  155. email:(NSString *)email
  156. newEmail:(nullable NSString *)newEmail {
  157. self = [super init];
  158. if (self) {
  159. _operation = operation;
  160. if (newEmail) {
  161. _email = [newEmail copy];
  162. _fromEmail = [email copy];
  163. } else {
  164. _email = [email copy];
  165. }
  166. }
  167. return self;
  168. }
  169. /** @fn actionCodeOperationForRequestType:
  170. @brief Returns the corresponding operation type per provided request type string.
  171. @param requestType Request type returned in in the server response.
  172. @return The corresponding FIRActionCodeOperation for the supplied request type.
  173. */
  174. + (FIRActionCodeOperation)actionCodeOperationForRequestType:(NSString *)requestType {
  175. if ([requestType isEqualToString:kPasswordResetRequestType]) {
  176. return FIRActionCodeOperationPasswordReset;
  177. }
  178. if ([requestType isEqualToString:kVerifyEmailRequestType]) {
  179. return FIRActionCodeOperationVerifyEmail;
  180. }
  181. if ([requestType isEqualToString:kRecoverEmailRequestType]) {
  182. return FIRActionCodeOperationRecoverEmail;
  183. }
  184. if ([requestType isEqualToString:kEmailLinkSignInRequestType]) {
  185. return FIRActionCodeOperationEmailLink;
  186. }
  187. return FIRActionCodeOperationUnknown;
  188. }
  189. @end
  190. #pragma mark - FIRAuth
  191. #if TARGET_OS_IOS
  192. @interface FIRAuth () <FIRAuthAppDelegateHandler>
  193. #else
  194. @interface FIRAuth ()
  195. #endif
  196. /** @property firebaseAppId
  197. @brief The Firebase app ID.
  198. */
  199. @property(nonatomic, copy, readonly) NSString *firebaseAppId;
  200. /** @property additionalFrameworkMarker
  201. @brief Additional framework marker that will be added as part of the header of every request.
  202. */
  203. @property(nonatomic, copy, nullable) NSString *additionalFrameworkMarker;
  204. /** @fn initWithApp:
  205. @brief Creates a @c FIRAuth instance associated with the provided @c FIRApp instance.
  206. @param app The application to associate the auth instance with.
  207. */
  208. - (instancetype)initWithApp:(FIRApp *)app;
  209. @end
  210. @implementation FIRAuth {
  211. /** @var _currentUser
  212. @brief The current user.
  213. */
  214. FIRUser *_currentUser;
  215. /** @var _firebaseAppName
  216. @brief The Firebase app name.
  217. */
  218. NSString *_firebaseAppName;
  219. /** @var _listenerHandles
  220. @brief Handles returned from @c NSNotificationCenter for blocks which are "auth state did
  221. change" notification listeners.
  222. @remarks Mutations should occur within a @syncronized(self) context.
  223. */
  224. NSMutableArray<FIRAuthStateDidChangeListenerHandle> *_listenerHandles;
  225. /** @var _keychain
  226. @brief The keychain service.
  227. */
  228. FIRAuthKeychain *_keychain;
  229. /** @var _lastNotifiedUserToken
  230. @brief The user access (ID) token used last time for posting auth state changed notification.
  231. */
  232. NSString *_lastNotifiedUserToken;
  233. /** @var _autoRefreshTokens
  234. @brief This flag denotes whether or not tokens should be automatically refreshed.
  235. @remarks Will only be set to @YES if the another Firebase service is included (additionally to
  236. Firebase Auth).
  237. */
  238. BOOL _autoRefreshTokens;
  239. /** @var _autoRefreshScheduled
  240. @brief Whether or not token auto-refresh is currently scheduled.
  241. */
  242. BOOL _autoRefreshScheduled;
  243. /** @var _isAppInBackground
  244. @brief A flag that is set to YES if the app is put in the background and no when the app is
  245. returned to the foreground.
  246. */
  247. BOOL _isAppInBackground;
  248. /** @var _applicationDidBecomeActiveObserver
  249. @brief An opaque object to act as the observer for UIApplicationDidBecomeActiveNotification.
  250. */
  251. id<NSObject> _applicationDidBecomeActiveObserver;
  252. /** @var _applicationDidBecomeActiveObserver
  253. @brief An opaque object to act as the observer for
  254. UIApplicationDidEnterBackgroundNotification.
  255. */
  256. id<NSObject> _applicationDidEnterBackgroundObserver;
  257. }
  258. + (void)load {
  259. static dispatch_once_t onceToken;
  260. dispatch_once(&onceToken, ^{
  261. gKeychainServiceNameForAppName = [[NSMutableDictionary alloc] init];
  262. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  263. // Ensures the @c FIRAuth instance for a given app gets loaded as soon as the app is ready.
  264. [defaultCenter addObserverForName:kFIRAppReadyToConfigureSDKNotification
  265. object:[FIRApp class]
  266. queue:nil
  267. usingBlock:^(NSNotification *notification) {
  268. [FIRAuth authWithApp:[FIRApp appNamed:notification.userInfo[kFIRAppNameKey]]];
  269. }];
  270. // Ensures the saved user is cleared when the app is deleted.
  271. [defaultCenter addObserverForName:kFIRAppDeleteNotification
  272. object:[FIRApp class]
  273. queue:nil
  274. usingBlock:^(NSNotification *notification) {
  275. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  276. // This doesn't stop any request already issued, see b/27704535 .
  277. NSString *appName = notification.userInfo[kFIRAppNameKey];
  278. NSString *keychainServiceName = [FIRAuth keychainServiceNameForAppName:appName];
  279. if (keychainServiceName) {
  280. [self deleteKeychainServiceNameForAppName:appName];
  281. FIRAuthKeychain *keychain = [[FIRAuthKeychain alloc] initWithService:keychainServiceName];
  282. NSString *userKey = [NSString stringWithFormat:kUserKey, appName];
  283. [keychain removeDataForKey:userKey error:NULL];
  284. }
  285. dispatch_async(dispatch_get_main_queue(), ^{
  286. [[NSNotificationCenter defaultCenter]
  287. postNotificationName:FIRAuthStateDidChangeNotification
  288. object:nil];
  289. });
  290. });
  291. }];
  292. });
  293. }
  294. + (FIRAuth *)auth {
  295. FIRApp *defaultApp = [FIRApp defaultApp];
  296. if (!defaultApp) {
  297. [NSException raise:NSInternalInconsistencyException
  298. format:@"The default FIRApp instance must be configured before the default FIRAuth"
  299. @"instance can be initialized. One way to ensure that is to call "
  300. @"`[FIRApp configure];` (`FirebaseApp.configure()` in Swift) in the App "
  301. @"Delegate's `application:didFinishLaunchingWithOptions:` "
  302. @"(`application(_:didFinishLaunchingWithOptions:)` in Swift)."];
  303. }
  304. return [self authWithApp:defaultApp];
  305. }
  306. + (FIRAuth *)authWithApp:(FIRApp *)app {
  307. return [FIRAppAssociationRegistration registeredObjectWithHost:app
  308. key:NSStringFromClass(self)
  309. creationBlock:^FIRAuth *_Nullable() {
  310. return [[FIRAuth alloc] initWithApp:app];
  311. }];
  312. }
  313. - (instancetype)initWithApp:(FIRApp *)app {
  314. [FIRAuth setKeychainServiceNameForApp:app];
  315. self = [self initWithAPIKey:app.options.APIKey appName:app.name];
  316. if (self) {
  317. _app = app;
  318. __weak FIRAuth *weakSelf = self;
  319. app.getTokenImplementation = ^(BOOL forceRefresh, FIRTokenCallback callback) {
  320. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  321. FIRAuth *strongSelf = weakSelf;
  322. // Enable token auto-refresh if not aleady enabled.
  323. if (strongSelf && !strongSelf->_autoRefreshTokens) {
  324. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000002", @"Token auto-refresh enabled.");
  325. strongSelf->_autoRefreshTokens = YES;
  326. [strongSelf scheduleAutoTokenRefresh];
  327. #if TARGET_OS_IOS // TODO: Is a similar mechanism needed on macOS?
  328. strongSelf->_applicationDidBecomeActiveObserver = [[NSNotificationCenter defaultCenter]
  329. addObserverForName:UIApplicationDidBecomeActiveNotification
  330. object:nil
  331. queue:nil
  332. usingBlock:^(NSNotification *notification) {
  333. FIRAuth *strongSelf = weakSelf;
  334. if (strongSelf) {
  335. strongSelf->_isAppInBackground = NO;
  336. if (!strongSelf->_autoRefreshScheduled) {
  337. [weakSelf scheduleAutoTokenRefresh];
  338. }
  339. }
  340. }];
  341. strongSelf->_applicationDidEnterBackgroundObserver = [[NSNotificationCenter defaultCenter]
  342. addObserverForName:UIApplicationDidEnterBackgroundNotification
  343. object:nil
  344. queue:nil
  345. usingBlock:^(NSNotification *notification) {
  346. FIRAuth *strongSelf = weakSelf;
  347. if (strongSelf) {
  348. strongSelf->_isAppInBackground = YES;
  349. }
  350. }];
  351. #endif
  352. }
  353. // Call back with 'nil' if there is no current user.
  354. if (!strongSelf || !strongSelf->_currentUser) {
  355. dispatch_async(dispatch_get_main_queue(), ^{
  356. callback(nil, nil);
  357. });
  358. return;
  359. }
  360. // Call back with current user token.
  361. [strongSelf->_currentUser internalGetTokenForcingRefresh:forceRefresh
  362. callback:^(NSString *_Nullable token,
  363. NSError *_Nullable error) {
  364. dispatch_async(dispatch_get_main_queue(), ^{
  365. callback(token, error);
  366. });
  367. }];
  368. });
  369. };
  370. app.getUIDImplementation = ^NSString *_Nullable() {
  371. __block NSString *uid;
  372. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  373. uid = [weakSelf getUID];
  374. });
  375. return uid;
  376. };
  377. #if TARGET_OS_IOS
  378. _authURLPresenter = [[FIRAuthURLPresenter alloc] init];
  379. #endif
  380. }
  381. return self;
  382. }
  383. - (instancetype)initWithAPIKey:(NSString *)APIKey appName:(NSString *)appName {
  384. self = [super init];
  385. if (self) {
  386. _listenerHandles = [NSMutableArray array];
  387. _requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey];
  388. _settings = [[FIRAuthSettings alloc] init];
  389. _firebaseAppName = [appName copy];
  390. #if TARGET_OS_IOS
  391. UIApplication *application = [UIApplication sharedApplication];
  392. // Initialize the shared FIRAuthAppDelegateProxy instance in the main thread if not already.
  393. [FIRAuthAppDelegateProxy sharedInstance];
  394. #endif
  395. // Continue with the rest of initialization in the work thread.
  396. __weak FIRAuth *weakSelf = self;
  397. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  398. // Load current user from Keychain.
  399. FIRAuth *strongSelf = weakSelf;
  400. if (!strongSelf) {
  401. return;
  402. }
  403. NSString *keychainServiceName =
  404. [FIRAuth keychainServiceNameForAppName:strongSelf->_firebaseAppName];
  405. if (keychainServiceName) {
  406. strongSelf->_keychain = [[FIRAuthKeychain alloc] initWithService:keychainServiceName];
  407. }
  408. FIRUser *user;
  409. NSError *error;
  410. if ([strongSelf getUser:&user error:&error]) {
  411. [strongSelf updateCurrentUser:user byForce:NO savingToDisk:NO error:&error];
  412. self->_lastNotifiedUserToken = user.rawAccessToken;
  413. } else {
  414. FIRLogError(kFIRLoggerAuth, @"I-AUT000001",
  415. @"Error loading saved user when starting up: %@", error);
  416. }
  417. #if TARGET_OS_IOS
  418. // Initialize for phone number auth.
  419. strongSelf->_tokenManager =
  420. [[FIRAuthAPNSTokenManager alloc] initWithApplication:application];
  421. strongSelf->_appCredentialManager =
  422. [[FIRAuthAppCredentialManager alloc] initWithKeychain:strongSelf->_keychain];
  423. strongSelf->_notificationManager = [[FIRAuthNotificationManager alloc]
  424. initWithApplication:application
  425. appCredentialManager:strongSelf->_appCredentialManager];
  426. [[FIRAuthAppDelegateProxy sharedInstance] addHandler:strongSelf];
  427. #endif
  428. });
  429. }
  430. return self;
  431. }
  432. - (void)dealloc {
  433. @synchronized (self) {
  434. NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
  435. while (_listenerHandles.count != 0) {
  436. FIRAuthStateDidChangeListenerHandle handleToRemove = _listenerHandles.lastObject;
  437. [defaultCenter removeObserver:handleToRemove];
  438. [_listenerHandles removeLastObject];
  439. }
  440. #if TARGET_OS_IOS
  441. [defaultCenter removeObserver:_applicationDidBecomeActiveObserver
  442. name:UIApplicationDidBecomeActiveNotification
  443. object:nil];
  444. [defaultCenter removeObserver:_applicationDidEnterBackgroundObserver
  445. name:UIApplicationDidEnterBackgroundNotification
  446. object:nil];
  447. #endif
  448. }
  449. }
  450. #pragma mark - Public API
  451. - (FIRUser *)currentUser {
  452. __block FIRUser *result;
  453. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  454. result = self->_currentUser;
  455. });
  456. return result;
  457. }
  458. - (void)fetchProvidersForEmail:(NSString *)email
  459. completion:(FIRProviderQueryCallback)completion {
  460. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  461. FIRCreateAuthURIRequest *request =
  462. [[FIRCreateAuthURIRequest alloc] initWithIdentifier:email
  463. continueURI:@"http://www.google.com/"
  464. requestConfiguration:self->_requestConfiguration];
  465. [FIRAuthBackend createAuthURI:request callback:^(FIRCreateAuthURIResponse *_Nullable response,
  466. NSError *_Nullable error) {
  467. if (completion) {
  468. dispatch_async(dispatch_get_main_queue(), ^{
  469. completion(response.allProviders, error);
  470. });
  471. }
  472. }];
  473. });
  474. }
  475. - (void)fetchSignInMethodsForEmail:(nonnull NSString *)email
  476. completion:(nullable FIRSignInMethodQueryCallback)completion {
  477. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  478. FIRCreateAuthURIRequest *request =
  479. [[FIRCreateAuthURIRequest alloc] initWithIdentifier:email
  480. continueURI:@"http://www.google.com/"
  481. requestConfiguration:self->_requestConfiguration];
  482. [FIRAuthBackend createAuthURI:request callback:^(FIRCreateAuthURIResponse *_Nullable response,
  483. NSError *_Nullable error) {
  484. if (completion) {
  485. dispatch_async(dispatch_get_main_queue(), ^{
  486. completion(response.signinMethods, error);
  487. });
  488. }
  489. }];
  490. });
  491. }
  492. - (void)signInWithEmail:(NSString *)email
  493. password:(NSString *)password
  494. completion:(FIRAuthDataResultCallback)completion {
  495. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  496. FIRAuthDataResultCallback decoratedCallback =
  497. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  498. [self internalSignInAndRetrieveDataWithEmail:email
  499. password:password
  500. completion:^(FIRAuthDataResult *_Nullable authResult,
  501. NSError *_Nullable error) {
  502. decoratedCallback(authResult, error);
  503. }];
  504. });
  505. }
  506. - (void)signInWithEmail:(NSString *)email
  507. link:(NSString *)link
  508. completion:(FIRAuthDataResultCallback)completion {
  509. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  510. FIRAuthDataResultCallback decoratedCallback =
  511. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  512. FIREmailPasswordAuthCredential *credential =
  513. [[FIREmailPasswordAuthCredential alloc] initWithEmail:email link:link];
  514. [self internalSignInAndRetrieveDataWithCredential:credential
  515. isReauthentication:NO
  516. callback:^(FIRAuthDataResult *_Nullable authResult,
  517. NSError *_Nullable error) {
  518. decoratedCallback(authResult, error);
  519. }];
  520. });
  521. }
  522. /** @fn signInWithEmail:password:callback:
  523. @brief Signs in using an email address and password.
  524. @param email The user's email address.
  525. @param password The user's password.
  526. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  527. asynchronously on the global auth work queue in the future.
  528. @remarks This is the internal counterpart of this method, which uses a callback that does not
  529. update the current user.
  530. */
  531. - (void)signInWithEmail:(NSString *)email
  532. password:(NSString *)password
  533. callback:(FIRAuthResultCallback)callback {
  534. FIRVerifyPasswordRequest *request =
  535. [[FIRVerifyPasswordRequest alloc] initWithEmail:email
  536. password:password
  537. requestConfiguration:_requestConfiguration];
  538. if (![request.password length]) {
  539. callback(nil, [FIRAuthErrorUtils wrongPasswordErrorWithMessage:nil]);
  540. return;
  541. }
  542. [FIRAuthBackend verifyPassword:request
  543. callback:^(FIRVerifyPasswordResponse *_Nullable response,
  544. NSError *_Nullable error) {
  545. if (error) {
  546. callback(nil, error);
  547. return;
  548. }
  549. [self completeSignInWithAccessToken:response.IDToken
  550. accessTokenExpirationDate:response.approximateExpirationDate
  551. refreshToken:response.refreshToken
  552. anonymous:NO
  553. callback:callback];
  554. }];
  555. }
  556. - (void)signInAndRetrieveDataWithEmail:(NSString *)email
  557. password:(NSString *)password
  558. completion:(FIRAuthDataResultCallback)completion {
  559. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  560. FIRAuthDataResultCallback decoratedCallback =
  561. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  562. [self internalSignInAndRetrieveDataWithEmail:email
  563. password:password
  564. completion:decoratedCallback];
  565. });
  566. }
  567. /** @fn internalSignInAndRetrieveDataWithEmail:password:callback:
  568. @brief Signs in using an email address and password.
  569. @param email The user's email address.
  570. @param password The user's password.
  571. @param completion A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  572. asynchronously on the global auth work queue in the future.
  573. @remarks This is the internal counterpart of this method, which uses a callback that does not
  574. update the current user.
  575. */
  576. - (void)internalSignInAndRetrieveDataWithEmail:(NSString *)email
  577. password:(NSString *)password
  578. completion:(FIRAuthDataResultCallback)completion {
  579. FIREmailPasswordAuthCredential *credentail =
  580. [[FIREmailPasswordAuthCredential alloc] initWithEmail:email password:password];
  581. [self internalSignInAndRetrieveDataWithCredential:credentail
  582. isReauthentication:NO
  583. callback:completion];
  584. }
  585. /** @fn internalSignInWithEmail:link:completion:
  586. @brief Signs in using an email and email sign-in link.
  587. @param email The user's email address.
  588. @param link The email sign-in link.
  589. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  590. asynchronously on the global auth work queue in the future.
  591. */
  592. - (void)internalSignInWithEmail:(nonnull NSString *)email
  593. link:(nonnull NSString *)link
  594. callback:(nullable FIRAuthResultCallback)callback {
  595. if (![self isSignInWithEmailLink:link]) {
  596. [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason:
  597. kInvalidEmailSignInLinkExceptionMessage];
  598. return;
  599. }
  600. NSDictionary<NSString *, NSString *> *queryItems = FIRAuthParseURL(link);
  601. if (![queryItems count]) {
  602. NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link];
  603. queryItems = FIRAuthParseURL(urlComponents.query);
  604. }
  605. NSString *actionCode = queryItems[@"oobCode"];
  606. FIREmailLinkSignInRequest *request =
  607. [[FIREmailLinkSignInRequest alloc] initWithEmail:email
  608. oobCode:actionCode
  609. requestConfiguration:_requestConfiguration];
  610. [FIRAuthBackend emailLinkSignin:request
  611. callback:^(FIREmailLinkSignInResponse *_Nullable response,
  612. NSError *_Nullable error) {
  613. if (error) {
  614. callback(nil, error);
  615. return;
  616. }
  617. [self completeSignInWithAccessToken:response.IDToken
  618. accessTokenExpirationDate:response.approximateExpirationDate
  619. refreshToken:response.refreshToken
  620. anonymous:NO
  621. callback:callback];
  622. }];
  623. }
  624. - (void)signInWithCredential:(FIRAuthCredential *)credential
  625. completion:(FIRAuthResultCallback)completion {
  626. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  627. FIRAuthResultCallback callback =
  628. [self signInFlowAuthResultCallbackByDecoratingCallback:completion];
  629. [self internalSignInWithCredential:credential callback:callback];
  630. });
  631. }
  632. - (void)signInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential
  633. completion:(nullable FIRAuthDataResultCallback)completion {
  634. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  635. FIRAuthDataResultCallback callback =
  636. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  637. [self internalSignInAndRetrieveDataWithCredential:credential
  638. isReauthentication:NO
  639. callback:callback];
  640. });
  641. }
  642. - (void)internalSignInWithCredential:(FIRAuthCredential *)credential
  643. callback:(FIRAuthResultCallback)callback {
  644. [self internalSignInAndRetrieveDataWithCredential:credential
  645. isReauthentication:NO
  646. callback:^(FIRAuthDataResult *_Nullable authResult,
  647. NSError *_Nullable error) {
  648. callback(authResult.user, error);
  649. }];
  650. }
  651. - (void)internalSignInAndRetrieveDataWithCredential:(FIRAuthCredential *)credential
  652. isReauthentication:(BOOL)isReauthentication
  653. callback:(nullable FIRAuthDataResultCallback)callback {
  654. if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) {
  655. // Special case for email/password credentials
  656. FIREmailPasswordAuthCredential *emailPasswordCredential =
  657. (FIREmailPasswordAuthCredential *)credential;
  658. FIRAuthResultCallback completeEmailSignIn = ^(FIRUser *user, NSError *error) {
  659. if (callback) {
  660. if (error) {
  661. callback(nil, error);
  662. return;
  663. }
  664. FIRAdditionalUserInfo *additionalUserInfo =
  665. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  666. profile:nil
  667. username:nil
  668. isNewUser:NO];
  669. FIRAuthDataResult *result = [[FIRAuthDataResult alloc] initWithUser:user
  670. additionalUserInfo:additionalUserInfo];
  671. callback(result, error);
  672. }
  673. };
  674. if (emailPasswordCredential.link) {
  675. [self internalSignInWithEmail:emailPasswordCredential.email
  676. link:emailPasswordCredential.link
  677. callback:completeEmailSignIn];
  678. } else {
  679. [self signInWithEmail:emailPasswordCredential.email
  680. password:emailPasswordCredential.password
  681. callback:completeEmailSignIn];
  682. }
  683. return;
  684. }
  685. #if TARGET_OS_IOS
  686. if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) {
  687. // Special case for phone auth credentials
  688. FIRPhoneAuthCredential *phoneCredential = (FIRPhoneAuthCredential *)credential;
  689. FIRAuthOperationType operation =
  690. isReauthentication ? FIRAuthOperationTypeReauth : FIRAuthOperationTypeSignUpOrSignIn;
  691. [self signInWithPhoneCredential:phoneCredential
  692. operation:operation
  693. callback:^(FIRVerifyPhoneNumberResponse *_Nullable response,
  694. NSError *_Nullable error) {
  695. if (callback) {
  696. if (error) {
  697. callback(nil, error);
  698. return;
  699. }
  700. [self completeSignInWithAccessToken:response.IDToken
  701. accessTokenExpirationDate:response.approximateExpirationDate
  702. refreshToken:response.refreshToken
  703. anonymous:NO
  704. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  705. FIRAdditionalUserInfo *additionalUserInfo =
  706. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIRPhoneAuthProviderID
  707. profile:nil
  708. username:nil
  709. isNewUser:response.isNewUser];
  710. FIRAuthDataResult *result = user ?
  711. [[FIRAuthDataResult alloc] initWithUser:user
  712. additionalUserInfo:additionalUserInfo] : nil;
  713. callback(result, error);
  714. }];
  715. }
  716. }];
  717. return;
  718. }
  719. #endif
  720. FIRVerifyAssertionRequest *request =
  721. [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider
  722. requestConfiguration:_requestConfiguration];
  723. request.autoCreate = !isReauthentication;
  724. [credential prepareVerifyAssertionRequest:request];
  725. [FIRAuthBackend verifyAssertion:request
  726. callback:^(FIRVerifyAssertionResponse *response, NSError *error) {
  727. if (error) {
  728. if (callback) {
  729. callback(nil, error);
  730. }
  731. return;
  732. }
  733. if (response.needConfirmation) {
  734. if (callback) {
  735. NSString *email = response.email;
  736. callback(nil, [FIRAuthErrorUtils accountExistsWithDifferentCredentialErrorWithEmail:email]);
  737. }
  738. return;
  739. }
  740. if (!response.providerID.length) {
  741. if (callback) {
  742. callback(nil, [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:response]);
  743. }
  744. return;
  745. }
  746. [self completeSignInWithAccessToken:response.IDToken
  747. accessTokenExpirationDate:response.approximateExpirationDate
  748. refreshToken:response.refreshToken
  749. anonymous:NO
  750. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  751. if (callback) {
  752. FIRAdditionalUserInfo *additionalUserInfo =
  753. [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response];
  754. FIRAuthDataResult *result = user ?
  755. [[FIRAuthDataResult alloc] initWithUser:user
  756. additionalUserInfo:additionalUserInfo] : nil;
  757. callback(result, error);
  758. }
  759. }];
  760. }];
  761. }
  762. - (void)signInWithCredential:(FIRAuthCredential *)credential
  763. callback:(FIRAuthResultCallback)callback {
  764. [self signInAndRetrieveDataWithCredential:credential
  765. completion:^(FIRAuthDataResult *_Nullable authResult,
  766. NSError *_Nullable error) {
  767. callback(authResult.user, error);
  768. }];
  769. }
  770. - (void)signInAnonymouslyAndRetrieveDataWithCompletion:(FIRAuthDataResultCallback)completion {
  771. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  772. FIRAuthDataResultCallback decoratedCallback =
  773. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  774. if (self->_currentUser.anonymous) {
  775. FIRAdditionalUserInfo *additionalUserInfo =
  776. [[FIRAdditionalUserInfo alloc] initWithProviderID:nil
  777. profile:nil
  778. username:nil
  779. isNewUser:NO];
  780. FIRAuthDataResult *authDataResult =
  781. [[FIRAuthDataResult alloc] initWithUser:self->_currentUser
  782. additionalUserInfo:additionalUserInfo];
  783. decoratedCallback(authDataResult, nil);
  784. return;
  785. }
  786. [self internalSignInAnonymouslyWithCompletion:^(FIRSignUpNewUserResponse *_Nullable response,
  787. NSError *_Nullable error) {
  788. if (error) {
  789. decoratedCallback(nil, error);
  790. return;
  791. }
  792. [self completeSignInWithAccessToken:response.IDToken
  793. accessTokenExpirationDate:response.approximateExpirationDate
  794. refreshToken:response.refreshToken
  795. anonymous:YES
  796. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  797. FIRAdditionalUserInfo *additionalUserInfo =
  798. [[FIRAdditionalUserInfo alloc] initWithProviderID:nil
  799. profile:nil
  800. username:nil
  801. isNewUser:YES];
  802. FIRAuthDataResult *authDataResult =
  803. [[FIRAuthDataResult alloc] initWithUser:user
  804. additionalUserInfo:additionalUserInfo];
  805. decoratedCallback(authDataResult, nil);
  806. }];
  807. }];
  808. });
  809. }
  810. - (void)signInAnonymouslyWithCompletion:(FIRAuthDataResultCallback)completion {
  811. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  812. FIRAuthDataResultCallback decoratedCallback =
  813. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  814. if (self->_currentUser.anonymous) {
  815. FIRAuthDataResult *result =
  816. [[FIRAuthDataResult alloc] initWithUser:self->_currentUser additionalUserInfo:nil];
  817. decoratedCallback(result, nil);
  818. return;
  819. }
  820. [self internalSignInAnonymouslyWithCompletion:^(FIRSignUpNewUserResponse *_Nullable response,
  821. NSError *_Nullable error) {
  822. if (error) {
  823. decoratedCallback(nil, error);
  824. return;
  825. }
  826. [self completeSignInWithAccessToken:response.IDToken
  827. accessTokenExpirationDate:response.approximateExpirationDate
  828. refreshToken:response.refreshToken
  829. anonymous:YES
  830. callback:^(FIRUser * _Nullable user, NSError * _Nullable error) {
  831. FIRAdditionalUserInfo *additionalUserInfo =
  832. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  833. profile:nil
  834. username:nil
  835. isNewUser:YES];
  836. FIRAuthDataResult *authDataResult =
  837. [[FIRAuthDataResult alloc] initWithUser:user
  838. additionalUserInfo:additionalUserInfo];
  839. decoratedCallback(authDataResult, nil);
  840. }];
  841. }];
  842. });
  843. }
  844. - (void)signInWithCustomToken:(NSString *)token
  845. completion:(nullable FIRAuthDataResultCallback)completion {
  846. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  847. FIRAuthDataResultCallback decoratedCallback =
  848. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  849. [self internalSignInAndRetrieveDataWithCustomToken:token
  850. completion:^(FIRAuthDataResult *_Nullable authResult,
  851. NSError *_Nullable error) {
  852. decoratedCallback(authResult, error);
  853. }];
  854. });
  855. }
  856. - (void)signInAndRetrieveDataWithCustomToken:(NSString *)token
  857. completion:(nullable FIRAuthDataResultCallback)completion {
  858. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  859. FIRAuthDataResultCallback decoratedCallback =
  860. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  861. [self internalSignInAndRetrieveDataWithCustomToken:token completion:decoratedCallback];
  862. });
  863. }
  864. - (void)createUserWithEmail:(NSString *)email
  865. password:(NSString *)password
  866. completion:(nullable FIRAuthDataResultCallback)completion {
  867. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  868. FIRAuthDataResultCallback decoratedCallback =
  869. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  870. [self internalCreateUserWithEmail:email
  871. password:password
  872. completion:^(FIRSignUpNewUserResponse *_Nullable response,
  873. NSError *_Nullable error) {
  874. if (error) {
  875. decoratedCallback(nil, error);
  876. return;
  877. }
  878. [self completeSignInWithAccessToken:response.IDToken
  879. accessTokenExpirationDate:response.approximateExpirationDate
  880. refreshToken:response.refreshToken
  881. anonymous:NO
  882. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  883. FIRAdditionalUserInfo *additionalUserInfo =
  884. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  885. profile:nil
  886. username:nil
  887. isNewUser:YES];
  888. FIRAuthDataResult *authDataResult =
  889. [[FIRAuthDataResult alloc] initWithUser:user
  890. additionalUserInfo:additionalUserInfo];
  891. decoratedCallback(authDataResult, nil);
  892. }];
  893. }];
  894. });
  895. }
  896. - (void)createUserAndRetrieveDataWithEmail:(NSString *)email
  897. password:(NSString *)password
  898. completion:(FIRAuthDataResultCallback)completion {
  899. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  900. FIRAuthDataResultCallback decoratedCallback =
  901. [self signInFlowAuthDataResultCallbackByDecoratingCallback:completion];
  902. [self internalCreateUserWithEmail:email
  903. password:password
  904. completion:^(FIRSignUpNewUserResponse *_Nullable response,
  905. NSError *_Nullable error) {
  906. if (error) {
  907. decoratedCallback(nil, error);
  908. return;
  909. }
  910. [self completeSignInWithAccessToken:response.IDToken
  911. accessTokenExpirationDate:response.approximateExpirationDate
  912. refreshToken:response.refreshToken
  913. anonymous:NO
  914. callback:^(FIRUser *_Nullable user, NSError *_Nullable error) {
  915. FIRAdditionalUserInfo *additionalUserInfo =
  916. [[FIRAdditionalUserInfo alloc] initWithProviderID:FIREmailAuthProviderID
  917. profile:nil
  918. username:nil
  919. isNewUser:YES];
  920. FIRAuthDataResult *authDataResult =
  921. [[FIRAuthDataResult alloc] initWithUser:user
  922. additionalUserInfo:additionalUserInfo];
  923. decoratedCallback(authDataResult, nil);
  924. }];
  925. }];
  926. });
  927. }
  928. - (void)confirmPasswordResetWithCode:(NSString *)code
  929. newPassword:(NSString *)newPassword
  930. completion:(FIRConfirmPasswordResetCallback)completion {
  931. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  932. FIRResetPasswordRequest *request =
  933. [[FIRResetPasswordRequest alloc] initWithOobCode:code
  934. newPassword:newPassword
  935. requestConfiguration:self->_requestConfiguration];
  936. [FIRAuthBackend resetPassword:request callback:^(FIRResetPasswordResponse *_Nullable response,
  937. NSError *_Nullable error) {
  938. if (completion) {
  939. dispatch_async(dispatch_get_main_queue(), ^{
  940. if (error) {
  941. completion(error);
  942. return;
  943. }
  944. completion(nil);
  945. });
  946. }
  947. }];
  948. });
  949. }
  950. - (void)checkActionCode:(NSString *)code completion:(FIRCheckActionCodeCallBack)completion {
  951. dispatch_async(FIRAuthGlobalWorkQueue(), ^ {
  952. FIRResetPasswordRequest *request =
  953. [[FIRResetPasswordRequest alloc] initWithOobCode:code
  954. newPassword:nil
  955. requestConfiguration:self->_requestConfiguration];
  956. [FIRAuthBackend resetPassword:request callback:^(FIRResetPasswordResponse *_Nullable response,
  957. NSError *_Nullable error) {
  958. if (completion) {
  959. if (error) {
  960. dispatch_async(dispatch_get_main_queue(), ^{
  961. completion(nil, error);
  962. });
  963. return;
  964. }
  965. FIRActionCodeOperation operation =
  966. [FIRActionCodeInfo actionCodeOperationForRequestType:response.requestType];
  967. FIRActionCodeInfo *actionCodeInfo =
  968. [[FIRActionCodeInfo alloc] initWithOperation:operation
  969. email:response.email
  970. newEmail:response.verifiedEmail];
  971. dispatch_async(dispatch_get_main_queue(), ^{
  972. completion(actionCodeInfo, nil);
  973. });
  974. }
  975. }];
  976. });
  977. }
  978. - (void)verifyPasswordResetCode:(NSString *)code
  979. completion:(FIRVerifyPasswordResetCodeCallback)completion {
  980. [self checkActionCode:code completion:^(FIRActionCodeInfo *_Nullable info,
  981. NSError *_Nullable error) {
  982. if (completion) {
  983. if (error) {
  984. completion(nil, error);
  985. return;
  986. }
  987. completion([info dataForKey:FIRActionCodeEmailKey], nil);
  988. }
  989. }];
  990. }
  991. - (void)applyActionCode:(NSString *)code completion:(FIRApplyActionCodeCallback)completion {
  992. dispatch_async(FIRAuthGlobalWorkQueue(), ^ {
  993. FIRSetAccountInfoRequest *request =
  994. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:self->_requestConfiguration];
  995. request.OOBCode = code;
  996. [FIRAuthBackend setAccountInfo:request callback:^(FIRSetAccountInfoResponse *_Nullable response,
  997. NSError *_Nullable error) {
  998. if (completion) {
  999. dispatch_async(dispatch_get_main_queue(), ^{
  1000. completion(error);
  1001. });
  1002. }
  1003. }];
  1004. });
  1005. }
  1006. - (void)sendPasswordResetWithEmail:(NSString *)email
  1007. completion:(nullable FIRSendPasswordResetCallback)completion {
  1008. [self sendPasswordResetWithNullableActionCodeSettings:nil email:email completion:completion];
  1009. }
  1010. - (void)sendPasswordResetWithEmail:(NSString *)email
  1011. actionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings
  1012. completion:(nullable FIRSendPasswordResetCallback)completion {
  1013. [self sendPasswordResetWithNullableActionCodeSettings:actionCodeSettings
  1014. email:email
  1015. completion:completion];
  1016. }
  1017. /** @fn sendPasswordResetWithNullableActionCodeSettings:actionCodeSetting:email:completion:
  1018. @brief Initiates a password reset for the given email address and @FIRActionCodeSettings object.
  1019. @param actionCodeSettings Optionally, An @c FIRActionCodeSettings object containing settings
  1020. related to the handling action codes.
  1021. @param email The email address of the user.
  1022. @param completion Optionally; a block which is invoked when the request finishes. Invoked
  1023. asynchronously on the main thread in the future.
  1024. */
  1025. - (void)sendPasswordResetWithNullableActionCodeSettings:(nullable FIRActionCodeSettings *)
  1026. actionCodeSettings
  1027. email:(NSString *)email
  1028. completion:(nullable FIRSendPasswordResetCallback)
  1029. completion {
  1030. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1031. if (!email) {
  1032. [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason:
  1033. kMissingEmailInvalidParameterExceptionReason];
  1034. }
  1035. FIRGetOOBConfirmationCodeRequest *request =
  1036. [FIRGetOOBConfirmationCodeRequest passwordResetRequestWithEmail:email
  1037. actionCodeSettings:actionCodeSettings
  1038. requestConfiguration:self->_requestConfiguration
  1039. ];
  1040. [FIRAuthBackend getOOBConfirmationCode:request
  1041. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1042. NSError *_Nullable error) {
  1043. if (completion) {
  1044. dispatch_async(dispatch_get_main_queue(), ^{
  1045. completion(error);
  1046. });
  1047. }
  1048. }];
  1049. });
  1050. }
  1051. - (void)sendSignInLinkToEmail:(nonnull NSString *)email
  1052. actionCodeSettings:(nonnull FIRActionCodeSettings *)actionCodeSettings
  1053. completion:(nullable FIRSendSignInLinkToEmailCallback)completion {
  1054. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1055. if (!email) {
  1056. [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason:
  1057. kMissingEmailInvalidParameterExceptionReason];
  1058. }
  1059. if (!actionCodeSettings.handleCodeInApp) {
  1060. [FIRAuthExceptionUtils raiseInvalidParameterExceptionWithReason:
  1061. kHandleCodeInAppFalseExceptionReason];
  1062. }
  1063. FIRGetOOBConfirmationCodeRequest *request =
  1064. [FIRGetOOBConfirmationCodeRequest signInWithEmailLinkRequest:email
  1065. actionCodeSettings:actionCodeSettings
  1066. requestConfiguration:self->_requestConfiguration];
  1067. [FIRAuthBackend getOOBConfirmationCode:request
  1068. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable response,
  1069. NSError *_Nullable error) {
  1070. if (completion) {
  1071. dispatch_async(dispatch_get_main_queue(), ^{
  1072. completion(error);
  1073. });
  1074. }
  1075. }];
  1076. });
  1077. }
  1078. - (void)updateCurrentUser:(FIRUser *)user completion:(nullable FIRUserUpdateCallback)completion {
  1079. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1080. if (!user) {
  1081. if (completion) {
  1082. dispatch_async(dispatch_get_main_queue(), ^{
  1083. completion([FIRAuthErrorUtils nullUserErrorWithMessage:nil]);
  1084. });
  1085. }
  1086. return;
  1087. }
  1088. void (^updateUserBlock)(FIRUser *user) = ^(FIRUser *user) {
  1089. NSError *error;
  1090. [self updateCurrentUser:user byForce:YES savingToDisk:YES error:(&error)];
  1091. if (error) {
  1092. if (completion) {
  1093. dispatch_async(dispatch_get_main_queue(), ^{
  1094. completion(error);
  1095. });
  1096. }
  1097. return;
  1098. } if (completion) {
  1099. dispatch_async(dispatch_get_main_queue(), ^{
  1100. completion(nil);
  1101. });
  1102. }
  1103. };
  1104. if (![user.requestConfiguration.APIKey isEqualToString:self->_requestConfiguration.APIKey]) {
  1105. // If the API keys are different, then we need to confirm that the user belongs to the same
  1106. // project before proceeding.
  1107. user.requestConfiguration = self->_requestConfiguration;
  1108. [user reloadWithCompletion:^(NSError *_Nullable error) {
  1109. if (error) {
  1110. if (completion) {
  1111. dispatch_async(dispatch_get_main_queue(), ^{
  1112. completion(error);
  1113. });
  1114. }
  1115. return;
  1116. }
  1117. updateUserBlock(user);
  1118. }];
  1119. } else {
  1120. updateUserBlock(user);
  1121. }
  1122. });
  1123. }
  1124. - (BOOL)signOut:(NSError *_Nullable __autoreleasing *_Nullable)error {
  1125. __block BOOL result = YES;
  1126. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1127. if (!self->_currentUser) {
  1128. return;
  1129. }
  1130. result = [self updateCurrentUser:nil byForce:NO savingToDisk:YES error:error];
  1131. });
  1132. return result;
  1133. }
  1134. - (BOOL)signOutByForceWithUserID:(NSString *)userID error:(NSError *_Nullable *_Nullable)error {
  1135. if (_currentUser.uid != userID) {
  1136. return YES;
  1137. }
  1138. return [self updateCurrentUser:nil byForce:YES savingToDisk:YES error:error];
  1139. }
  1140. - (BOOL)isSignInWithEmailLink:(NSString *)link {
  1141. if (link.length == 0) {
  1142. return NO;
  1143. }
  1144. NSDictionary<NSString *, NSString *> *queryItems = FIRAuthParseURL(link);
  1145. if (![queryItems count]) {
  1146. NSURLComponents *urlComponents = [NSURLComponents componentsWithString:link];
  1147. if (!urlComponents.query) {
  1148. return NO;
  1149. }
  1150. queryItems = FIRAuthParseURL(urlComponents.query);
  1151. }
  1152. if (![queryItems count]) {
  1153. return NO;
  1154. }
  1155. NSString *actionCode = queryItems[@"oobCode"];
  1156. NSString *mode = queryItems[@"mode"];
  1157. if (actionCode && [mode isEqualToString:@"signIn"]) {
  1158. return YES;
  1159. }
  1160. return NO;
  1161. }
  1162. /** @fn FIRAuthParseURL:NSString
  1163. @brief Parses an incoming URL into all available query items.
  1164. @param urlString The url to be parsed.
  1165. @return A dictionary of available query items in the target URL.
  1166. */
  1167. static NSDictionary<NSString *, NSString *> *FIRAuthParseURL(NSString *urlString) {
  1168. NSString *linkURL = [NSURLComponents componentsWithString:urlString].query;
  1169. if (!linkURL) {
  1170. return @{};
  1171. }
  1172. NSArray<NSString *> *URLComponents = [linkURL componentsSeparatedByString:@"&"];
  1173. NSMutableDictionary<NSString *, NSString *> *queryItems =
  1174. [[NSMutableDictionary alloc] initWithCapacity:URLComponents.count];
  1175. for (NSString *component in URLComponents) {
  1176. NSRange equalRange = [component rangeOfString:@"="];
  1177. if (equalRange.location != NSNotFound) {
  1178. NSString *queryItemKey =
  1179. [[component substringToIndex:equalRange.location] stringByRemovingPercentEncoding];
  1180. NSString *queryItemValue =
  1181. [[component substringFromIndex:equalRange.location + 1] stringByRemovingPercentEncoding];
  1182. if (queryItemKey && queryItemValue) {
  1183. queryItems[queryItemKey] = queryItemValue;
  1184. }
  1185. }
  1186. }
  1187. return queryItems;
  1188. }
  1189. - (FIRAuthStateDidChangeListenerHandle)addAuthStateDidChangeListener:
  1190. (FIRAuthStateDidChangeListenerBlock)listener {
  1191. __block BOOL firstInvocation = YES;
  1192. __block NSString *previousUserID;
  1193. return [self addIDTokenDidChangeListener:^(FIRAuth *_Nonnull auth, FIRUser *_Nullable user) {
  1194. BOOL shouldCallListener = firstInvocation ||
  1195. !(previousUserID == user.uid || [previousUserID isEqualToString:user.uid]);
  1196. firstInvocation = NO;
  1197. previousUserID = [user.uid copy];
  1198. if (shouldCallListener) {
  1199. listener(auth, user);
  1200. }
  1201. }];
  1202. }
  1203. - (void)removeAuthStateDidChangeListener:(FIRAuthStateDidChangeListenerHandle)listenerHandle {
  1204. [self removeIDTokenDidChangeListener:listenerHandle];
  1205. }
  1206. - (FIRIDTokenDidChangeListenerHandle)addIDTokenDidChangeListener:
  1207. (FIRIDTokenDidChangeListenerBlock)listener {
  1208. if (!listener) {
  1209. [NSException raise:NSInvalidArgumentException format:@"listener must not be nil."];
  1210. return nil;
  1211. }
  1212. FIRAuthStateDidChangeListenerHandle handle;
  1213. NSNotificationCenter *notifications = [NSNotificationCenter defaultCenter];
  1214. handle = [notifications addObserverForName:FIRAuthStateDidChangeNotification
  1215. object:self
  1216. queue:[NSOperationQueue mainQueue]
  1217. usingBlock:^(NSNotification *_Nonnull notification) {
  1218. FIRAuth *auth = notification.object;
  1219. listener(auth, auth.currentUser);
  1220. }];
  1221. @synchronized (self) {
  1222. [_listenerHandles addObject:handle];
  1223. }
  1224. dispatch_async(dispatch_get_main_queue(), ^{
  1225. listener(self, self->_currentUser);
  1226. });
  1227. return handle;
  1228. }
  1229. - (void)removeIDTokenDidChangeListener:(FIRIDTokenDidChangeListenerHandle)listenerHandle {
  1230. [[NSNotificationCenter defaultCenter] removeObserver:listenerHandle];
  1231. @synchronized (self) {
  1232. [_listenerHandles removeObject:listenerHandle];
  1233. }
  1234. }
  1235. - (void)useAppLanguage {
  1236. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1237. self->_requestConfiguration.languageCode =
  1238. [NSBundle mainBundle].preferredLocalizations.firstObject;
  1239. });
  1240. }
  1241. - (nullable NSString *)languageCode {
  1242. return _requestConfiguration.languageCode;
  1243. }
  1244. - (void)setLanguageCode:(nullable NSString *)languageCode {
  1245. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1246. self->_requestConfiguration.languageCode = [languageCode copy];
  1247. });
  1248. }
  1249. - (NSString *)additionalFrameworkMarker {
  1250. return self->_requestConfiguration.additionalFrameworkMarker;
  1251. }
  1252. - (void)setAdditionalFrameworkMarker:(NSString *)additionalFrameworkMarker {
  1253. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1254. self->_requestConfiguration.additionalFrameworkMarker = [additionalFrameworkMarker copy];
  1255. });
  1256. }
  1257. #if TARGET_OS_IOS
  1258. - (NSData *)APNSToken {
  1259. __block NSData *result = nil;
  1260. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1261. result = self->_tokenManager.token.data;
  1262. });
  1263. return result;
  1264. }
  1265. - (void)setAPNSToken:(NSData *)APNSToken {
  1266. [self setAPNSToken:APNSToken type:FIRAuthAPNSTokenTypeUnknown];
  1267. }
  1268. - (void)setAPNSToken:(NSData *)token type:(FIRAuthAPNSTokenType)type {
  1269. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1270. self->_tokenManager.token = [[FIRAuthAPNSToken alloc] initWithData:token type:type];
  1271. });
  1272. }
  1273. - (void)handleAPNSTokenError:(NSError *)error {
  1274. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1275. [self->_tokenManager cancelWithError:error];
  1276. });
  1277. }
  1278. - (BOOL)canHandleNotification:(NSDictionary *)userInfo {
  1279. __block BOOL result = NO;
  1280. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1281. result = [self->_notificationManager canHandleNotification:userInfo];
  1282. });
  1283. return result;
  1284. }
  1285. - (BOOL)canHandleURL:(NSURL *)URL {
  1286. __block BOOL result = NO;
  1287. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1288. result = [self->_authURLPresenter canHandleURL:URL];
  1289. });
  1290. return result;
  1291. }
  1292. #endif
  1293. #pragma mark - Internal Methods
  1294. #if TARGET_OS_IOS
  1295. /** @fn signInWithPhoneCredential:callback:
  1296. @brief Signs in using a phone credential.
  1297. @param credential The Phone Auth credential used to sign in.
  1298. @param operation The type of operation for which this sign-in attempt is initiated.
  1299. @param callback A block which is invoked when the sign in finishes (or is cancelled.) Invoked
  1300. asynchronously on the global auth work queue in the future.
  1301. */
  1302. - (void)signInWithPhoneCredential:(FIRPhoneAuthCredential *)credential
  1303. operation:(FIRAuthOperationType)operation
  1304. callback:(FIRVerifyPhoneNumberResponseCallback)callback {
  1305. if (credential.temporaryProof.length && credential.phoneNumber.length) {
  1306. FIRVerifyPhoneNumberRequest *request =
  1307. [[FIRVerifyPhoneNumberRequest alloc] initWithTemporaryProof:credential.temporaryProof
  1308. phoneNumber:credential.phoneNumber
  1309. operation:operation
  1310. requestConfiguration:_requestConfiguration];
  1311. [FIRAuthBackend verifyPhoneNumber:request callback:callback];
  1312. return;
  1313. }
  1314. if (!credential.verificationID.length) {
  1315. callback(nil, [FIRAuthErrorUtils missingVerificationIDErrorWithMessage:nil]);
  1316. return;
  1317. }
  1318. if (!credential.verificationCode.length) {
  1319. callback(nil, [FIRAuthErrorUtils missingVerificationCodeErrorWithMessage:nil]);
  1320. return;
  1321. }
  1322. FIRVerifyPhoneNumberRequest *request =
  1323. [[FIRVerifyPhoneNumberRequest alloc]initWithVerificationID:credential.verificationID
  1324. verificationCode:credential.verificationCode
  1325. operation:operation
  1326. requestConfiguration:_requestConfiguration];
  1327. [FIRAuthBackend verifyPhoneNumber:request callback:callback];
  1328. }
  1329. #endif
  1330. /** @fn internalSignInAndRetrieveDataWithCustomToken:completion:
  1331. @brief Signs in a Firebase user given a custom token.
  1332. @param token A self-signed custom auth token.
  1333. @param completion A block which is invoked when the custom token sign in request completes.
  1334. */
  1335. - (void)internalSignInAndRetrieveDataWithCustomToken:(NSString *)token
  1336. completion:(nullable FIRAuthDataResultCallback)
  1337. completion {
  1338. FIRVerifyCustomTokenRequest *request =
  1339. [[FIRVerifyCustomTokenRequest alloc] initWithToken:token
  1340. requestConfiguration:_requestConfiguration];
  1341. [FIRAuthBackend verifyCustomToken:request
  1342. callback:^(FIRVerifyCustomTokenResponse *_Nullable response,
  1343. NSError *_Nullable error) {
  1344. if (error) {
  1345. if (completion) {
  1346. completion(nil, error);
  1347. return;
  1348. }
  1349. }
  1350. [self completeSignInWithAccessToken:response.IDToken
  1351. accessTokenExpirationDate:response.approximateExpirationDate
  1352. refreshToken:response.refreshToken
  1353. anonymous:NO
  1354. callback:^(FIRUser *_Nullable user,
  1355. NSError *_Nullable error) {
  1356. if (error) {
  1357. if (completion) {
  1358. completion(nil, error);
  1359. }
  1360. return;
  1361. }
  1362. FIRAdditionalUserInfo *additonalUserInfo =
  1363. [[FIRAdditionalUserInfo alloc] initWithProviderID:nil
  1364. profile:nil
  1365. username:nil
  1366. isNewUser:response.isNewUser];
  1367. FIRAuthDataResult *result =
  1368. [[FIRAuthDataResult alloc] initWithUser:user additionalUserInfo:additonalUserInfo];
  1369. if (completion) {
  1370. completion(result, nil);
  1371. }
  1372. }];
  1373. }];
  1374. }
  1375. /** @fn internalCreateUserWithEmail:password:completion:
  1376. @brief Makes a backend request attempting to create a new Firebase user given an email address
  1377. and password.
  1378. @param email The email address used to create the new Firebase user.
  1379. @param password The password used to create the new Firebase user.
  1380. @param completion Optionally; a block which is invoked when the request finishes.
  1381. */
  1382. - (void)internalCreateUserWithEmail:(NSString *)email
  1383. password:(NSString *)password
  1384. completion:(nullable FIRSignupNewUserCallback)completion {
  1385. FIRSignUpNewUserRequest *request =
  1386. [[FIRSignUpNewUserRequest alloc] initWithEmail:email
  1387. password:password
  1388. displayName:nil
  1389. requestConfiguration:_requestConfiguration];
  1390. if (![request.password length]) {
  1391. completion(nil, [FIRAuthErrorUtils
  1392. weakPasswordErrorWithServerResponseReason:kMissingPasswordReason]);
  1393. return;
  1394. }
  1395. if (![request.email length]) {
  1396. completion(nil, [FIRAuthErrorUtils missingEmailErrorWithMessage:nil]);
  1397. return;
  1398. }
  1399. [FIRAuthBackend signUpNewUser:request callback:completion];
  1400. }
  1401. /** @fn internalSignInAnonymouslyWithCompletion:
  1402. @param completion A block which is invoked when the anonymous sign in request completes.
  1403. */
  1404. - (void)internalSignInAnonymouslyWithCompletion:(FIRSignupNewUserCallback)completion {
  1405. FIRSignUpNewUserRequest *request =
  1406. [[FIRSignUpNewUserRequest alloc]initWithRequestConfiguration:_requestConfiguration];
  1407. [FIRAuthBackend signUpNewUser:request
  1408. callback:completion];
  1409. }
  1410. /** @fn possiblyPostAuthStateChangeNotification
  1411. @brief Posts the auth state change notificaton if current user's token has been changed.
  1412. */
  1413. - (void)possiblyPostAuthStateChangeNotification {
  1414. NSString *token = _currentUser.rawAccessToken;
  1415. if (_lastNotifiedUserToken == token || [_lastNotifiedUserToken isEqualToString:token]) {
  1416. return;
  1417. }
  1418. _lastNotifiedUserToken = token;
  1419. if (_autoRefreshTokens) {
  1420. // Shedule new refresh task after successful attempt.
  1421. [self scheduleAutoTokenRefresh];
  1422. }
  1423. NSMutableDictionary *internalNotificationParameters = [NSMutableDictionary dictionary];
  1424. if (self.app) {
  1425. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationAppKey] = self.app;
  1426. }
  1427. if (token.length) {
  1428. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationTokenKey] = token;
  1429. }
  1430. internalNotificationParameters[FIRAuthStateDidChangeInternalNotificationUIDKey] = _currentUser.uid;
  1431. NSNotificationCenter *notifications = [NSNotificationCenter defaultCenter];
  1432. dispatch_async(dispatch_get_main_queue(), ^{
  1433. [notifications postNotificationName:FIRAuthStateDidChangeInternalNotification
  1434. object:self
  1435. userInfo:internalNotificationParameters];
  1436. [notifications postNotificationName:FIRAuthStateDidChangeNotification
  1437. object:self];
  1438. });
  1439. }
  1440. - (BOOL)updateKeychainWithUser:(FIRUser *)user error:(NSError *_Nullable *_Nullable)error {
  1441. if (user != _currentUser) {
  1442. // No-op if the user is no longer signed in. This is not considered an error as we don't check
  1443. // whether the user is still current on other callbacks of user operations either.
  1444. return YES;
  1445. }
  1446. if ([self saveUser:user error:error]) {
  1447. [self possiblyPostAuthStateChangeNotification];
  1448. return YES;
  1449. }
  1450. return NO;
  1451. }
  1452. /** @fn setKeychainServiceNameForApp
  1453. @brief Sets the keychain service name global data for the particular app.
  1454. @param app The Firebase app to set keychain service name for.
  1455. */
  1456. + (void)setKeychainServiceNameForApp:(FIRApp *)app {
  1457. @synchronized (self) {
  1458. gKeychainServiceNameForAppName[app.name] =
  1459. [@"firebase_auth_" stringByAppendingString:app.options.googleAppID];
  1460. }
  1461. }
  1462. /** @fn keychainServiceNameForAppName:
  1463. @brief Gets the keychain service name global data for the particular app by name.
  1464. @param appName The name of the Firebase app to get keychain service name for.
  1465. */
  1466. + (NSString *)keychainServiceNameForAppName:(NSString *)appName {
  1467. @synchronized (self) {
  1468. return gKeychainServiceNameForAppName[appName];
  1469. }
  1470. }
  1471. /** @fn deleteKeychainServiceNameForAppName:
  1472. @brief Deletes the keychain service name global data for the particular app by name.
  1473. @param appName The name of the Firebase app to delete keychain service name for.
  1474. */
  1475. + (void)deleteKeychainServiceNameForAppName:(NSString *)appName {
  1476. @synchronized (self) {
  1477. [gKeychainServiceNameForAppName removeObjectForKey:appName];
  1478. }
  1479. }
  1480. /** @fn scheduleAutoTokenRefreshWithDelay:
  1481. @brief Schedules a task to automatically refresh tokens on the current user. The token refresh
  1482. is scheduled 5 minutes before the scheduled expiration time.
  1483. @remarks If the token expires in less than 5 minutes, schedule the token refresh immediately.
  1484. */
  1485. - (void)scheduleAutoTokenRefresh {
  1486. NSTimeInterval tokenExpirationInterval =
  1487. [_currentUser.accessTokenExpirationDate timeIntervalSinceNow] - kTokenRefreshHeadStart;
  1488. [self scheduleAutoTokenRefreshWithDelay:MAX(tokenExpirationInterval, 0) retry:NO];
  1489. }
  1490. /** @fn scheduleAutoTokenRefreshWithDelay:
  1491. @brief Schedules a task to automatically refresh tokens on the current user.
  1492. @param delay The delay in seconds after which the token refresh task should be scheduled to be
  1493. executed.
  1494. @param retry Flag to determine whether the invocation is a retry attempt or not.
  1495. */
  1496. - (void)scheduleAutoTokenRefreshWithDelay:(NSTimeInterval)delay retry:(BOOL)retry {
  1497. NSString *accessToken = _currentUser.rawAccessToken;
  1498. if (!accessToken) {
  1499. return;
  1500. }
  1501. if (retry) {
  1502. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000003",
  1503. @"Token auto-refresh re-scheduled in %02d:%02d "
  1504. @"because of error on previous refresh attempt.",
  1505. (int)ceil(delay) / 60, (int)ceil(delay) % 60);
  1506. } else {
  1507. FIRLogInfo(kFIRLoggerAuth, @"I-AUT000004",
  1508. @"Token auto-refresh scheduled in %02d:%02d for the new token.",
  1509. (int)ceil(delay) / 60, (int)ceil(delay) % 60);
  1510. }
  1511. _autoRefreshScheduled = YES;
  1512. __weak FIRAuth *weakSelf = self;
  1513. [[FIRAuthDispatcher sharedInstance] dispatchAfterDelay:delay
  1514. queue:FIRAuthGlobalWorkQueue()
  1515. task:^(void) {
  1516. FIRAuth *strongSelf = weakSelf;
  1517. if (!strongSelf) {
  1518. return;
  1519. }
  1520. if (![strongSelf->_currentUser.rawAccessToken isEqualToString:accessToken]) {
  1521. // Another auto refresh must have been scheduled, so keep _autoRefreshScheduled unchanged.
  1522. return;
  1523. }
  1524. strongSelf->_autoRefreshScheduled = NO;
  1525. if (strongSelf->_isAppInBackground) {
  1526. return;
  1527. }
  1528. NSString *uid = strongSelf->_currentUser.uid;
  1529. [strongSelf->_currentUser internalGetTokenForcingRefresh:YES
  1530. callback:^(NSString *_Nullable token,
  1531. NSError *_Nullable error) {
  1532. if (![strongSelf->_currentUser.uid isEqualToString:uid]) {
  1533. return;
  1534. }
  1535. if (error) {
  1536. // Kicks off exponential back off logic to retry failed attempt. Starts with one minute
  1537. // delay (60 seconds) if this is the first failed attempt.
  1538. NSTimeInterval rescheduleDelay;
  1539. if (retry) {
  1540. rescheduleDelay = MIN(delay * 2, kMaxWaitTimeForBackoff);
  1541. } else {
  1542. rescheduleDelay = 60;
  1543. }
  1544. [strongSelf scheduleAutoTokenRefreshWithDelay:rescheduleDelay retry:YES];
  1545. }
  1546. }];
  1547. }];
  1548. }
  1549. #pragma mark -
  1550. /** @fn completeSignInWithTokenService:callback:
  1551. @brief Completes a sign-in flow once we have access and refresh tokens for the user.
  1552. @param accessToken The STS access token.
  1553. @param accessTokenExpirationDate The approximate expiration date of the access token.
  1554. @param refreshToken The STS refresh token.
  1555. @param anonymous Whether or not the user is anonymous.
  1556. @param callback Called when the user has been signed in or when an error occurred. Invoked
  1557. asynchronously on the global auth work queue in the future.
  1558. */
  1559. - (void)completeSignInWithAccessToken:(NSString *)accessToken
  1560. accessTokenExpirationDate:(NSDate *)accessTokenExpirationDate
  1561. refreshToken:(NSString *)refreshToken
  1562. anonymous:(BOOL)anonymous
  1563. callback:(FIRAuthResultCallback)callback {
  1564. [FIRUser retrieveUserWithAuth:self
  1565. accessToken:accessToken
  1566. accessTokenExpirationDate:accessTokenExpirationDate
  1567. refreshToken:refreshToken
  1568. anonymous:anonymous
  1569. callback:callback];
  1570. }
  1571. /** @fn signInFlowAuthResultCallbackByDecoratingCallback:
  1572. @brief Creates a FIRAuthResultCallback block which wraps another FIRAuthResultCallback; trying
  1573. to update the current user before forwarding it's invocations along to a subject block
  1574. @param callback Called when the user has been updated or when an error has occurred. Invoked
  1575. asynchronously on the main thread in the future.
  1576. @return Returns a block that updates the current user.
  1577. @remarks Typically invoked as part of the complete sign-in flow. For any other uses please
  1578. consider alternative ways of updating the current user.
  1579. */
  1580. - (FIRAuthResultCallback)signInFlowAuthResultCallbackByDecoratingCallback:
  1581. (nullable FIRAuthResultCallback)callback {
  1582. return ^(FIRUser *_Nullable user, NSError *_Nullable error) {
  1583. if (error) {
  1584. if (callback) {
  1585. dispatch_async(dispatch_get_main_queue(), ^{
  1586. callback(nil, error);
  1587. });
  1588. }
  1589. return;
  1590. }
  1591. if (![self updateCurrentUser:user byForce:NO savingToDisk:YES error:&error]) {
  1592. if (callback) {
  1593. dispatch_async(dispatch_get_main_queue(), ^{
  1594. callback(nil, error);
  1595. });
  1596. }
  1597. return;
  1598. }
  1599. if (callback) {
  1600. dispatch_async(dispatch_get_main_queue(), ^{
  1601. callback(user, nil);
  1602. });
  1603. }
  1604. };
  1605. }
  1606. /** @fn signInFlowAuthDataResultCallbackByDecoratingCallback:
  1607. @brief Creates a FIRAuthDataResultCallback block which wraps another FIRAuthDataResultCallback;
  1608. trying to update the current user before forwarding it's invocations along to a subject
  1609. block.
  1610. @param callback Called when the user has been updated or when an error has occurred. Invoked
  1611. asynchronously on the main thread in the future.
  1612. @return Returns a block that updates the current user.
  1613. @remarks Typically invoked as part of the complete sign-in flow. For any other uses please
  1614. consider alternative ways of updating the current user.
  1615. */
  1616. - (FIRAuthDataResultCallback)signInFlowAuthDataResultCallbackByDecoratingCallback:
  1617. (nullable FIRAuthDataResultCallback)callback {
  1618. return ^(FIRAuthDataResult *_Nullable authResult, NSError *_Nullable error) {
  1619. if (error) {
  1620. if (callback) {
  1621. dispatch_async(dispatch_get_main_queue(), ^{
  1622. callback(nil, error);
  1623. });
  1624. }
  1625. return;
  1626. }
  1627. if (![self updateCurrentUser:authResult.user byForce:NO savingToDisk:YES error:&error]) {
  1628. if (callback) {
  1629. dispatch_async(dispatch_get_main_queue(), ^{
  1630. callback(nil, error);
  1631. });
  1632. }
  1633. return;
  1634. }
  1635. if (callback) {
  1636. dispatch_async(dispatch_get_main_queue(), ^{
  1637. callback(authResult, nil);
  1638. });
  1639. }
  1640. };
  1641. }
  1642. #pragma mark - User-Related Methods
  1643. /** @fn updateCurrentUser:savingToDisk:
  1644. @brief Update the current user; initializing the user's internal properties correctly, and
  1645. optionally saving the user to disk.
  1646. @remarks This method is called during: sign in and sign out events, as well as during class
  1647. initialization time. The only time the saveToDisk parameter should be set to NO is during
  1648. class initialization time because the user was just read from disk.
  1649. @param user The user to use as the current user (including nil, which is passed at sign out
  1650. time.)
  1651. @param saveToDisk Indicates the method should persist the user data to disk.
  1652. */
  1653. - (BOOL)updateCurrentUser:(FIRUser *)user
  1654. byForce:(BOOL)force
  1655. savingToDisk:(BOOL)saveToDisk
  1656. error:(NSError *_Nullable *_Nullable)error {
  1657. if (user == _currentUser) {
  1658. [self possiblyPostAuthStateChangeNotification];
  1659. return YES;
  1660. }
  1661. BOOL success = YES;
  1662. if (saveToDisk) {
  1663. success = [self saveUser:user error:error];
  1664. }
  1665. if (success || force) {
  1666. _currentUser = user;
  1667. [self possiblyPostAuthStateChangeNotification];
  1668. }
  1669. return success;
  1670. }
  1671. /** @fn saveUser:error:
  1672. @brief Persists user.
  1673. @param user The user to save.
  1674. @param error Return value for any error which occurs.
  1675. @return @YES on success, @NO otherwise.
  1676. */
  1677. - (BOOL)saveUser:(FIRUser *)user
  1678. error:(NSError *_Nullable *_Nullable)error {
  1679. BOOL success;
  1680. NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName];
  1681. if (!user) {
  1682. success = [_keychain removeDataForKey:userKey error:error];
  1683. } else {
  1684. // Encode the user object.
  1685. NSMutableData *archiveData = [NSMutableData data];
  1686. NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:archiveData];
  1687. [archiver encodeObject:user forKey:userKey];
  1688. [archiver finishEncoding];
  1689. // Save the user object's encoded value.
  1690. success = [_keychain setData:archiveData forKey:userKey error:error];
  1691. }
  1692. return success;
  1693. }
  1694. /** @fn getUser:error:
  1695. @brief Retrieves the saved user associated, if one exists, from the keychain.
  1696. @param outUser An out parameter which is populated with the saved user, if one exists.
  1697. @param error Return value for any error which occurs.
  1698. @return YES if the operation was a success (irrespective of whether or not a saved user existed
  1699. for the given @c firebaseAppId,) NO if an error occurred.
  1700. */
  1701. - (BOOL)getUser:(FIRUser *_Nullable *)outUser
  1702. error:(NSError *_Nullable *_Nullable)error {
  1703. NSString *userKey = [NSString stringWithFormat:kUserKey, _firebaseAppName];
  1704. NSError *keychainError;
  1705. NSData *encodedUserData = [_keychain dataForKey:userKey error:&keychainError];
  1706. if (keychainError) {
  1707. if (error) {
  1708. *error = keychainError;
  1709. }
  1710. return NO;
  1711. }
  1712. if (!encodedUserData) {
  1713. *outUser = nil;
  1714. return YES;
  1715. }
  1716. NSKeyedUnarchiver *unarchiver =
  1717. [[NSKeyedUnarchiver alloc] initForReadingWithData:encodedUserData];
  1718. FIRUser *user = [unarchiver decodeObjectOfClass:[FIRUser class] forKey:userKey];
  1719. user.auth = self;
  1720. *outUser = user;
  1721. return YES;
  1722. }
  1723. - (nullable NSString *)getUID {
  1724. return _currentUser.uid;
  1725. }
  1726. @end