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.

1536 lines
62 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
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 "FIRUser_Internal.h"
  17. #import <FirebaseCore/FIRLogger.h>
  18. #import "FIRAdditionalUserInfo_Internal.h"
  19. #import "FIRAuth.h"
  20. #import "FIRAuthCredential_Internal.h"
  21. #import "FIRAuthDataResult_Internal.h"
  22. #import "FIRAuthErrorUtils.h"
  23. #import "FIRAuthGlobalWorkQueue.h"
  24. #import "FIRAuthSerialTaskQueue.h"
  25. #import "FIRAuthOperationType.h"
  26. #import "FIRAuth_Internal.h"
  27. #import "FIRAuthBackend.h"
  28. #import "FIRAuthRequestConfiguration.h"
  29. #import "FIRAuthTokenResult_Internal.h"
  30. #import "FIRAuthWebUtils.h"
  31. #import "FIRDeleteAccountRequest.h"
  32. #import "FIRDeleteAccountResponse.h"
  33. #import "FIREmailAuthProvider.h"
  34. #import "FIREmailPasswordAuthCredential.h"
  35. #import "FIREmailLinkSignInRequest.h"
  36. #import "FIRGameCenterAuthCredential.h"
  37. #import "FIRGetAccountInfoRequest.h"
  38. #import "FIRGetAccountInfoResponse.h"
  39. #import "FIRGetOOBConfirmationCodeRequest.h"
  40. #import "FIRGetOOBConfirmationCodeResponse.h"
  41. #import "FIROAuthCredential_Internal.h"
  42. #import "FIRSecureTokenService.h"
  43. #import "FIRSetAccountInfoRequest.h"
  44. #import "FIRSetAccountInfoResponse.h"
  45. #import "FIRSignInWithGameCenterRequest.h"
  46. #import "FIRSignInWithGameCenterResponse.h"
  47. #import "FIRUserInfoImpl.h"
  48. #import "FIRUserMetadata_Internal.h"
  49. #import "FIRVerifyAssertionRequest.h"
  50. #import "FIRVerifyAssertionResponse.h"
  51. #import "FIRVerifyCustomTokenRequest.h"
  52. #import "FIRVerifyCustomTokenResponse.h"
  53. #import "FIRVerifyPasswordRequest.h"
  54. #import "FIRVerifyPasswordResponse.h"
  55. #import "FIRVerifyPhoneNumberRequest.h"
  56. #import "FIRVerifyPhoneNumberResponse.h"
  57. #if TARGET_OS_IOS
  58. #import "FIRPhoneAuthProvider.h"
  59. #import "FIRPhoneAuthCredential_Internal.h"
  60. #endif
  61. NS_ASSUME_NONNULL_BEGIN
  62. /** @var kUserIDCodingKey
  63. @brief The key used to encode the user ID for NSSecureCoding.
  64. */
  65. static NSString *const kUserIDCodingKey = @"userID";
  66. /** @var kHasEmailPasswordCredentialCodingKey
  67. @brief The key used to encode the hasEmailPasswordCredential property for NSSecureCoding.
  68. */
  69. static NSString *const kHasEmailPasswordCredentialCodingKey = @"hasEmailPassword";
  70. /** @var kAnonymousCodingKey
  71. @brief The key used to encode the anonymous property for NSSecureCoding.
  72. */
  73. static NSString *const kAnonymousCodingKey = @"anonymous";
  74. /** @var kEmailCodingKey
  75. @brief The key used to encode the email property for NSSecureCoding.
  76. */
  77. static NSString *const kEmailCodingKey = @"email";
  78. /** @var kPhoneNumberCodingKey
  79. @brief The key used to encode the phoneNumber property for NSSecureCoding.
  80. */
  81. static NSString *const kPhoneNumberCodingKey = @"phoneNumber";
  82. /** @var kEmailVerifiedCodingKey
  83. @brief The key used to encode the isEmailVerified property for NSSecureCoding.
  84. */
  85. static NSString *const kEmailVerifiedCodingKey = @"emailVerified";
  86. /** @var kDisplayNameCodingKey
  87. @brief The key used to encode the displayName property for NSSecureCoding.
  88. */
  89. static NSString *const kDisplayNameCodingKey = @"displayName";
  90. /** @var kPhotoURLCodingKey
  91. @brief The key used to encode the photoURL property for NSSecureCoding.
  92. */
  93. static NSString *const kPhotoURLCodingKey = @"photoURL";
  94. /** @var kProviderDataKey
  95. @brief The key used to encode the providerData instance variable for NSSecureCoding.
  96. */
  97. static NSString *const kProviderDataKey = @"providerData";
  98. /** @var kAPIKeyCodingKey
  99. @brief The key used to encode the APIKey instance variable for NSSecureCoding.
  100. */
  101. static NSString *const kAPIKeyCodingKey = @"APIKey";
  102. /** @var kTokenServiceCodingKey
  103. @brief The key used to encode the tokenService instance variable for NSSecureCoding.
  104. */
  105. static NSString *const kTokenServiceCodingKey = @"tokenService";
  106. /** @var kMetadataCodingKey
  107. @brief The key used to encode the metadata instance variable for NSSecureCoding.
  108. */
  109. static NSString *const kMetadataCodingKey = @"metadata";
  110. /** @var kMissingUsersErrorMessage
  111. @brief The error message when there is no users array in the getAccountInfo response.
  112. */
  113. static NSString *const kMissingUsersErrorMessage = @"users";
  114. /** @typedef CallbackWithError
  115. @brief The type for a callback block that only takes an error parameter.
  116. */
  117. typedef void (^CallbackWithError)(NSError *_Nullable);
  118. /** @typedef CallbackWithUserAndError
  119. @brief The type for a callback block that takes a user parameter and an error parameter.
  120. */
  121. typedef void (^CallbackWithUserAndError)(FIRUser *_Nullable, NSError *_Nullable);
  122. /** @typedef CallbackWithUserAndError
  123. @brief The type for a callback block that takes a user parameter and an error parameter.
  124. */
  125. typedef void (^CallbackWithAuthDataResultAndError)(FIRAuthDataResult *_Nullable,
  126. NSError *_Nullable);
  127. /** @var kMissingPasswordReason
  128. @brief The reason why the @c FIRAuthErrorCodeWeakPassword error is thrown.
  129. @remarks This error message will be localized in the future.
  130. */
  131. static NSString *const kMissingPasswordReason = @"Missing Password";
  132. /** @fn callInMainThreadWithError
  133. @brief Calls a callback in main thread with error.
  134. @param callback The callback to be called in main thread.
  135. @param error The error to pass to callback.
  136. */
  137. static void callInMainThreadWithError(_Nullable CallbackWithError callback,
  138. NSError *_Nullable error) {
  139. if (callback) {
  140. dispatch_async(dispatch_get_main_queue(), ^{
  141. callback(error);
  142. });
  143. }
  144. }
  145. /** @fn callInMainThreadWithUserAndError
  146. @brief Calls a callback in main thread with user and error.
  147. @param callback The callback to be called in main thread.
  148. @param user The user to pass to callback if there is no error.
  149. @param error The error to pass to callback.
  150. */
  151. static void callInMainThreadWithUserAndError(_Nullable CallbackWithUserAndError callback,
  152. FIRUser *_Nonnull user,
  153. NSError *_Nullable error) {
  154. if (callback) {
  155. dispatch_async(dispatch_get_main_queue(), ^{
  156. callback(error ? nil : user, error);
  157. });
  158. }
  159. }
  160. /** @fn callInMainThreadWithUserAndError
  161. @brief Calls a callback in main thread with user and error.
  162. @param callback The callback to be called in main thread.
  163. @param result The result to pass to callback if there is no error.
  164. @param error The error to pass to callback.
  165. */
  166. static void callInMainThreadWithAuthDataResultAndError(
  167. _Nullable CallbackWithAuthDataResultAndError callback,
  168. FIRAuthDataResult *_Nullable result,
  169. NSError *_Nullable error) {
  170. if (callback) {
  171. dispatch_async(dispatch_get_main_queue(), ^{
  172. callback(result, error);
  173. });
  174. }
  175. }
  176. @interface FIRUserProfileChangeRequest ()
  177. /** @fn initWithUser:
  178. @brief Designated initializer.
  179. @param user The user for which we are updating profile information.
  180. */
  181. - (nullable instancetype)initWithUser:(FIRUser *)user NS_DESIGNATED_INITIALIZER;
  182. @end
  183. @interface FIRUser ()
  184. /** @property anonymous
  185. @brief Whether the current user is anonymous.
  186. */
  187. @property(nonatomic, readwrite) BOOL anonymous;
  188. @end
  189. @implementation FIRUser {
  190. /** @var _hasEmailPasswordCredential
  191. @brief Whether or not the user can be authenticated by using Firebase email and password.
  192. */
  193. BOOL _hasEmailPasswordCredential;
  194. /** @var _providerData
  195. @brief Provider specific user data.
  196. */
  197. NSDictionary<NSString *, FIRUserInfoImpl *> *_providerData;
  198. /** @var _taskQueue
  199. @brief Used to serialize the update profile calls.
  200. */
  201. FIRAuthSerialTaskQueue *_taskQueue;
  202. /** @var _tokenService
  203. @brief A secure token service associated with this user. For performing token exchanges and
  204. refreshing access tokens.
  205. */
  206. FIRSecureTokenService *_tokenService;
  207. }
  208. #pragma mark - Properties
  209. // Explicitly @synthesize because these properties are defined in FIRUserInfo protocol.
  210. @synthesize uid = _userID;
  211. @synthesize displayName = _displayName;
  212. @synthesize photoURL = _photoURL;
  213. @synthesize email = _email;
  214. @synthesize phoneNumber = _phoneNumber;
  215. #pragma mark -
  216. + (void)retrieveUserWithAuth:(FIRAuth *)auth
  217. accessToken:(nullable NSString *)accessToken
  218. accessTokenExpirationDate:(nullable NSDate *)accessTokenExpirationDate
  219. refreshToken:(nullable NSString *)refreshToken
  220. anonymous:(BOOL)anonymous
  221. callback:(FIRRetrieveUserCallback)callback {
  222. FIRSecureTokenService *tokenService =
  223. [[FIRSecureTokenService alloc] initWithRequestConfiguration:auth.requestConfiguration
  224. accessToken:accessToken
  225. accessTokenExpirationDate:accessTokenExpirationDate
  226. refreshToken:refreshToken];
  227. FIRUser *user = [[self alloc] initWithTokenService:tokenService];
  228. user.auth = auth;
  229. user.requestConfiguration = auth.requestConfiguration;
  230. [user internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  231. if (error) {
  232. callback(nil, error);
  233. return;
  234. }
  235. FIRGetAccountInfoRequest *getAccountInfoRequest =
  236. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  237. requestConfiguration:auth.requestConfiguration];
  238. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  239. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  240. NSError *_Nullable error) {
  241. if (error) {
  242. // No need to sign out user here for errors because the user hasn't been signed in yet.
  243. callback(nil, error);
  244. return;
  245. }
  246. user.anonymous = anonymous;
  247. [user updateWithGetAccountInfoResponse:response];
  248. callback(user, nil);
  249. }];
  250. }];
  251. }
  252. - (instancetype)initWithTokenService:(FIRSecureTokenService *)tokenService {
  253. self = [super init];
  254. if (self) {
  255. _providerData = @{ };
  256. _taskQueue = [[FIRAuthSerialTaskQueue alloc] init];
  257. _tokenService = tokenService;
  258. }
  259. return self;
  260. }
  261. #pragma mark - NSSecureCoding
  262. + (BOOL)supportsSecureCoding {
  263. return YES;
  264. }
  265. - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder {
  266. NSString *userID = [aDecoder decodeObjectOfClass:[NSString class] forKey:kUserIDCodingKey];
  267. BOOL hasAnonymousKey = [aDecoder containsValueForKey:kAnonymousCodingKey];
  268. BOOL anonymous = [aDecoder decodeBoolForKey:kAnonymousCodingKey];
  269. BOOL hasEmailPasswordCredential =
  270. [aDecoder decodeBoolForKey:kHasEmailPasswordCredentialCodingKey];
  271. NSString *displayName =
  272. [aDecoder decodeObjectOfClass:[NSString class] forKey:kDisplayNameCodingKey];
  273. NSURL *photoURL =
  274. [aDecoder decodeObjectOfClass:[NSURL class] forKey:kPhotoURLCodingKey];
  275. NSString *email =
  276. [aDecoder decodeObjectOfClass:[NSString class] forKey:kEmailCodingKey];
  277. NSString *phoneNumber =
  278. [aDecoder decodeObjectOfClass:[NSString class] forKey:kPhoneNumberCodingKey];
  279. BOOL emailVerified = [aDecoder decodeBoolForKey:kEmailVerifiedCodingKey];
  280. NSSet *providerDataClasses = [NSSet setWithArray:@[
  281. [NSDictionary class],
  282. [NSString class],
  283. [FIRUserInfoImpl class]
  284. ]];
  285. NSDictionary<NSString *, FIRUserInfoImpl *> *providerData =
  286. [aDecoder decodeObjectOfClasses:providerDataClasses forKey:kProviderDataKey];
  287. FIRSecureTokenService *tokenService =
  288. [aDecoder decodeObjectOfClass:[FIRSecureTokenService class] forKey:kTokenServiceCodingKey];
  289. FIRUserMetadata *metadata =
  290. [aDecoder decodeObjectOfClass:[FIRUserMetadata class] forKey:kMetadataCodingKey];
  291. NSString *APIKey =
  292. [aDecoder decodeObjectOfClass:[NSString class] forKey:kAPIKeyCodingKey];
  293. if (!userID || !tokenService) {
  294. return nil;
  295. }
  296. self = [self initWithTokenService:tokenService];
  297. if (self) {
  298. _userID = userID;
  299. // Previous version of this code didn't save 'anonymous' bit directly but deduced it from
  300. // 'hasEmailPasswordCredential' and 'providerData' instead, so here backward compatibility is
  301. // provided to read old format data.
  302. _anonymous = hasAnonymousKey ? anonymous : (!hasEmailPasswordCredential && !providerData.count);
  303. _hasEmailPasswordCredential = hasEmailPasswordCredential;
  304. _email = email;
  305. _emailVerified = emailVerified;
  306. _displayName = displayName;
  307. _photoURL = photoURL;
  308. _providerData = providerData;
  309. _phoneNumber = phoneNumber;
  310. _metadata = metadata ?: [[FIRUserMetadata alloc] initWithCreationDate:nil lastSignInDate:nil];
  311. _requestConfiguration = [[FIRAuthRequestConfiguration alloc] initWithAPIKey:APIKey];
  312. }
  313. return self;
  314. }
  315. - (void)encodeWithCoder:(NSCoder *)aCoder {
  316. [aCoder encodeObject:_userID forKey:kUserIDCodingKey];
  317. [aCoder encodeBool:self.anonymous forKey:kAnonymousCodingKey];
  318. [aCoder encodeBool:_hasEmailPasswordCredential forKey:kHasEmailPasswordCredentialCodingKey];
  319. [aCoder encodeObject:_providerData forKey:kProviderDataKey];
  320. [aCoder encodeObject:_email forKey:kEmailCodingKey];
  321. [aCoder encodeObject:_phoneNumber forKey:kPhoneNumberCodingKey];
  322. [aCoder encodeBool:_emailVerified forKey:kEmailVerifiedCodingKey];
  323. [aCoder encodeObject:_photoURL forKey:kPhotoURLCodingKey];
  324. [aCoder encodeObject:_displayName forKey:kDisplayNameCodingKey];
  325. [aCoder encodeObject:_metadata forKey:kMetadataCodingKey];
  326. [aCoder encodeObject:_auth.requestConfiguration.APIKey forKey:kAPIKeyCodingKey];
  327. [aCoder encodeObject:_tokenService forKey:kTokenServiceCodingKey];
  328. }
  329. #pragma mark -
  330. - (void)setAuth:(nullable FIRAuth *)auth {
  331. _auth = auth;
  332. _tokenService.requestConfiguration = auth.requestConfiguration;
  333. }
  334. - (NSString *)providerID {
  335. return @"Firebase";
  336. }
  337. - (NSArray<id<FIRUserInfo>> *)providerData {
  338. return _providerData.allValues;
  339. }
  340. /** @fn getAccountInfoRefreshingCache:
  341. @brief Gets the users's account data from the server, updating our local values.
  342. @param callback Invoked when the request to getAccountInfo has completed, or when an error has
  343. been detected. Invoked asynchronously on the auth global work queue in the future.
  344. */
  345. - (void)getAccountInfoRefreshingCache:(void(^)(FIRGetAccountInfoResponseUser *_Nullable user,
  346. NSError *_Nullable error))callback {
  347. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken, NSError *_Nullable error) {
  348. if (error) {
  349. callback(nil, error);
  350. return;
  351. }
  352. FIRGetAccountInfoRequest *getAccountInfoRequest =
  353. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  354. requestConfiguration:self->_auth.requestConfiguration];
  355. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  356. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  357. NSError *_Nullable error) {
  358. if (error) {
  359. [self signOutIfTokenIsInvalidWithError:error];
  360. callback(nil, error);
  361. return;
  362. }
  363. [self updateWithGetAccountInfoResponse:response];
  364. if (![self updateKeychain:&error]) {
  365. callback(nil, error);
  366. return;
  367. }
  368. callback(response.users.firstObject, nil);
  369. }];
  370. }];
  371. }
  372. - (void)updateWithGetAccountInfoResponse:(FIRGetAccountInfoResponse *)response {
  373. FIRGetAccountInfoResponseUser *user = response.users.firstObject;
  374. _userID = user.localID;
  375. _email = user.email;
  376. _emailVerified = user.emailVerified;
  377. _displayName = user.displayName;
  378. _photoURL = user.photoURL;
  379. _phoneNumber = user.phoneNumber;
  380. _hasEmailPasswordCredential = user.passwordHash.length > 0;
  381. _metadata =
  382. [[FIRUserMetadata alloc]initWithCreationDate:user.creationDate
  383. lastSignInDate:user.lastLoginDate];
  384. NSMutableDictionary<NSString *, FIRUserInfoImpl *> *providerData =
  385. [NSMutableDictionary dictionary];
  386. for (FIRGetAccountInfoResponseProviderUserInfo *providerUserInfo in user.providerUserInfo) {
  387. FIRUserInfoImpl *userInfo =
  388. [FIRUserInfoImpl userInfoWithGetAccountInfoResponseProviderUserInfo:providerUserInfo];
  389. if (userInfo) {
  390. providerData[providerUserInfo.providerID] = userInfo;
  391. }
  392. }
  393. _providerData = [providerData copy];
  394. }
  395. /** @fn executeUserUpdateWithChanges:callback:
  396. @brief Performs a setAccountInfo request by mutating the results of a getAccountInfo response,
  397. atomically in regards to other calls to this method.
  398. @param changeBlock A block responsible for mutating a template @c FIRSetAccountInfoRequest
  399. @param callback A block to invoke when the change is complete. Invoked asynchronously on the
  400. auth global work queue in the future.
  401. */
  402. - (void)executeUserUpdateWithChanges:(void(^)(FIRGetAccountInfoResponseUser *,
  403. FIRSetAccountInfoRequest *))changeBlock
  404. callback:(nonnull FIRUserProfileChangeCallback)callback {
  405. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  406. [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user,
  407. NSError *_Nullable error) {
  408. if (error) {
  409. complete();
  410. callback(error);
  411. return;
  412. }
  413. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  414. NSError *_Nullable error) {
  415. if (error) {
  416. complete();
  417. callback(error);
  418. return;
  419. }
  420. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  421. // Mutate setAccountInfoRequest in block:
  422. FIRSetAccountInfoRequest *setAccountInfoRequest =
  423. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:configuration];
  424. setAccountInfoRequest.accessToken = accessToken;
  425. changeBlock(user, setAccountInfoRequest);
  426. // Execute request:
  427. [FIRAuthBackend setAccountInfo:setAccountInfoRequest
  428. callback:^(FIRSetAccountInfoResponse *_Nullable response,
  429. NSError *_Nullable error) {
  430. if (error) {
  431. [self signOutIfTokenIsInvalidWithError:error];
  432. complete();
  433. callback(error);
  434. return;
  435. }
  436. if (response.IDToken && response.refreshToken) {
  437. FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc]
  438. initWithRequestConfiguration:configuration
  439. accessToken:response.IDToken
  440. accessTokenExpirationDate:response.approximateExpirationDate
  441. refreshToken:response.refreshToken];
  442. [self setTokenService:tokenService callback:^(NSError *_Nullable error) {
  443. complete();
  444. callback(error);
  445. }];
  446. return;
  447. }
  448. complete();
  449. callback(nil);
  450. }];
  451. }];
  452. }];
  453. }];
  454. }
  455. /** @fn updateKeychain:
  456. @brief Updates the keychain for user token or info changes.
  457. @param error The error if NO is returned.
  458. @return Whether the operation is successful.
  459. */
  460. - (BOOL)updateKeychain:(NSError *_Nullable *_Nullable)error {
  461. return [_auth updateKeychainWithUser:self error:error];
  462. }
  463. /** @fn setTokenService:callback:
  464. @brief Sets a new token service for the @c FIRUser instance.
  465. @param tokenService The new token service object.
  466. @param callback The block to be called in the global auth working queue once finished.
  467. @remarks The method makes sure the token service has access and refresh token and the new tokens
  468. are saved in the keychain before calling back.
  469. */
  470. - (void)setTokenService:(FIRSecureTokenService *)tokenService
  471. callback:(nonnull CallbackWithError)callback {
  472. [tokenService fetchAccessTokenForcingRefresh:NO
  473. callback:^(NSString *_Nullable token,
  474. NSError *_Nullable error,
  475. BOOL tokenUpdated) {
  476. if (error) {
  477. callback(error);
  478. return;
  479. }
  480. self->_tokenService = tokenService;
  481. if (![self updateKeychain:&error]) {
  482. callback(error);
  483. return;
  484. }
  485. callback(nil);
  486. }];
  487. }
  488. #pragma mark -
  489. /** @fn updateEmail:password:callback:
  490. @brief Updates email address and/or password for the current user.
  491. @remarks May fail if there is already an email/password-based account for the same email
  492. address.
  493. @param email The email address for the user, if to be updated.
  494. @param password The new password for the user, if to be updated.
  495. @param callback The block called when the user profile change has finished. Invoked
  496. asynchronously on the auth global work queue in the future.
  497. @remarks May fail with a @c FIRAuthErrorCodeRequiresRecentLogin error code.
  498. Call @c reauthentateWithCredential:completion: beforehand to avoid this error case.
  499. */
  500. - (void)updateEmail:(nullable NSString *)email
  501. password:(nullable NSString *)password
  502. callback:(nonnull FIRUserProfileChangeCallback)callback {
  503. if (password && ![password length]) {
  504. callback([FIRAuthErrorUtils weakPasswordErrorWithServerResponseReason:kMissingPasswordReason]);
  505. return;
  506. }
  507. BOOL hadEmailPasswordCredential = _hasEmailPasswordCredential;
  508. [self executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user,
  509. FIRSetAccountInfoRequest *request) {
  510. if (email) {
  511. request.email = email;
  512. }
  513. if (password) {
  514. request.password = password;
  515. }
  516. }
  517. callback:^(NSError *error) {
  518. if (error) {
  519. callback(error);
  520. return;
  521. }
  522. if (email) {
  523. self->_email = [email copy];
  524. }
  525. if (self->_email) {
  526. if (!hadEmailPasswordCredential) {
  527. // The list of providers need to be updated for the newly added email-password provider.
  528. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  529. NSError *_Nullable error) {
  530. if (error) {
  531. callback(error);
  532. return;
  533. }
  534. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  535. FIRGetAccountInfoRequest *getAccountInfoRequest =
  536. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  537. requestConfiguration:requestConfiguration];
  538. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  539. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  540. NSError *_Nullable error) {
  541. if (error) {
  542. [self signOutIfTokenIsInvalidWithError:error];
  543. callback(error);
  544. return;
  545. }
  546. for (FIRGetAccountInfoResponseUser *userAccountInfo in response.users) {
  547. // Set the account to non-anonymous if there are any providers, even if
  548. // they're not email/password ones.
  549. if (userAccountInfo.providerUserInfo.count > 0) {
  550. self.anonymous = NO;
  551. }
  552. for (FIRGetAccountInfoResponseProviderUserInfo *providerUserInfo in
  553. userAccountInfo.providerUserInfo) {
  554. if ([providerUserInfo.providerID isEqualToString:FIREmailAuthProviderID]) {
  555. self->_hasEmailPasswordCredential = YES;
  556. break;
  557. }
  558. }
  559. }
  560. [self updateWithGetAccountInfoResponse:response];
  561. if (![self updateKeychain:&error]) {
  562. callback(error);
  563. return;
  564. }
  565. callback(nil);
  566. }];
  567. }];
  568. return;
  569. }
  570. }
  571. if (![self updateKeychain:&error]) {
  572. callback(error);
  573. return;
  574. }
  575. callback(nil);
  576. }];
  577. }
  578. - (void)updateEmail:(NSString *)email completion:(nullable FIRUserProfileChangeCallback)completion {
  579. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  580. [self updateEmail:email password:nil callback:^(NSError *_Nullable error) {
  581. callInMainThreadWithError(completion, error);
  582. }];
  583. });
  584. }
  585. - (void)updatePassword:(NSString *)password
  586. completion:(nullable FIRUserProfileChangeCallback)completion {
  587. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  588. [self updateEmail:nil password:password callback:^(NSError *_Nullable error){
  589. callInMainThreadWithError(completion, error);
  590. }];
  591. });
  592. }
  593. #if TARGET_OS_IOS
  594. /** @fn internalUpdateOrLinkPhoneNumberCredential:completion:
  595. @brief Updates the phone number for the user. On success, the cached user profile data is
  596. updated.
  597. @param phoneAuthCredential The new phone number credential corresponding to the phone number
  598. to be added to the Firebase account, if a phone number is already linked to the account this
  599. new phone number will replace it.
  600. @param isLinkOperation Boolean value indicating whether or not this is a link operation.
  601. @param completion Optionally; the block invoked when the user profile change has finished.
  602. Invoked asynchronously on the global work queue in the future.
  603. */
  604. - (void)internalUpdateOrLinkPhoneNumberCredential:(FIRPhoneAuthCredential *)phoneAuthCredential
  605. isLinkOperation:(BOOL)isLinkOperation
  606. completion:(FIRUserProfileChangeCallback)completion {
  607. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  608. NSError *_Nullable error) {
  609. if (error) {
  610. completion(error);
  611. return;
  612. }
  613. FIRAuthOperationType operation =
  614. isLinkOperation ? FIRAuthOperationTypeLink : FIRAuthOperationTypeUpdate;
  615. FIRVerifyPhoneNumberRequest *request = [[FIRVerifyPhoneNumberRequest alloc]
  616. initWithVerificationID:phoneAuthCredential.verificationID
  617. verificationCode:phoneAuthCredential.verificationCode
  618. operation:operation
  619. requestConfiguration:self->_auth.requestConfiguration];
  620. request.accessToken = accessToken;
  621. [FIRAuthBackend verifyPhoneNumber:request
  622. callback:^(FIRVerifyPhoneNumberResponse *_Nullable response,
  623. NSError *_Nullable error) {
  624. if (error) {
  625. [self signOutIfTokenIsInvalidWithError:error];
  626. completion(error);
  627. return;
  628. }
  629. // Get account info to update cached user info.
  630. [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user,
  631. NSError *_Nullable error) {
  632. if (error) {
  633. [self signOutIfTokenIsInvalidWithError:error];
  634. completion(error);
  635. return;
  636. }
  637. self.anonymous = NO;
  638. if (![self updateKeychain:&error]) {
  639. completion(error);
  640. return;
  641. }
  642. completion(nil);
  643. }];
  644. }];
  645. }];
  646. }
  647. - (void)updatePhoneNumberCredential:(FIRPhoneAuthCredential *)phoneAuthCredential
  648. completion:(nullable FIRUserProfileChangeCallback)completion {
  649. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  650. [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential
  651. isLinkOperation:NO
  652. completion:^(NSError *_Nullable error) {
  653. callInMainThreadWithError(completion, error);
  654. }];
  655. });
  656. }
  657. #endif
  658. - (FIRUserProfileChangeRequest *)profileChangeRequest {
  659. __block FIRUserProfileChangeRequest *result;
  660. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  661. result = [[FIRUserProfileChangeRequest alloc] initWithUser:self];
  662. });
  663. return result;
  664. }
  665. - (void)setDisplayName:(NSString *)displayName {
  666. _displayName = [displayName copy];
  667. }
  668. - (void)setPhotoURL:(NSURL *)photoURL {
  669. _photoURL = [photoURL copy];
  670. }
  671. - (NSString *)rawAccessToken {
  672. return _tokenService.rawAccessToken;
  673. }
  674. - (NSDate *)accessTokenExpirationDate {
  675. return _tokenService.accessTokenExpirationDate;
  676. }
  677. #pragma mark -
  678. - (void)reloadWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  679. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  680. [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user,
  681. NSError *_Nullable error) {
  682. callInMainThreadWithError(completion, error);
  683. }];
  684. });
  685. }
  686. #pragma mark -
  687. #pragma clang diagnostic push
  688. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  689. - (void)reauthenticateWithCredential:(FIRAuthCredential *) credential
  690. completion:(nullable FIRAuthDataResultCallback) completion {
  691. [self reauthenticateAndRetrieveDataWithCredential:credential completion:completion];
  692. }
  693. #pragma clang diagnostic pop
  694. - (void)reauthenticateAndRetrieveDataWithCredential:(FIRAuthCredential *) credential
  695. completion:(nullable FIRAuthDataResultCallback) completion {
  696. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  697. [self->_auth internalSignInAndRetrieveDataWithCredential:credential
  698. isReauthentication:YES
  699. callback:^(FIRAuthDataResult *_Nullable
  700. authResult,
  701. NSError *_Nullable error) {
  702. if (error) {
  703. // If "user not found" error returned by backend, translate to user mismatch error which is
  704. // more accurate.
  705. if (error.code == FIRAuthErrorCodeUserNotFound) {
  706. error = [FIRAuthErrorUtils userMismatchError];
  707. }
  708. callInMainThreadWithAuthDataResultAndError(completion, authResult, error);
  709. return;
  710. }
  711. if (![authResult.user.uid isEqual:[self->_auth getUserID]]) {
  712. callInMainThreadWithAuthDataResultAndError(completion, authResult,
  713. [FIRAuthErrorUtils userMismatchError]);
  714. return;
  715. }
  716. // Successful reauthenticate
  717. [self setTokenService:authResult.user->_tokenService callback:^(NSError *_Nullable error) {
  718. callInMainThreadWithAuthDataResultAndError(completion, authResult, error);
  719. }];
  720. }];
  721. });
  722. }
  723. - (nullable NSString *)refreshToken {
  724. __block NSString *result;
  725. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  726. result = self->_tokenService.refreshToken;
  727. });
  728. return result;
  729. }
  730. - (void)getIDTokenWithCompletion:(nullable FIRAuthTokenCallback)completion {
  731. // |getIDTokenForcingRefresh:completion:| is also a public API so there is no need to dispatch to
  732. // global work queue here.
  733. [self getIDTokenForcingRefresh:NO completion:completion];
  734. }
  735. - (void)getIDTokenForcingRefresh:(BOOL)forceRefresh
  736. completion:(nullable FIRAuthTokenCallback)completion {
  737. [self getIDTokenResultForcingRefresh:forceRefresh
  738. completion:^(FIRAuthTokenResult *_Nullable tokenResult,
  739. NSError *_Nullable error) {
  740. if (completion) {
  741. dispatch_async(dispatch_get_main_queue(), ^{
  742. completion(tokenResult.token, error);
  743. });
  744. }
  745. }];
  746. }
  747. - (void)getIDTokenResultWithCompletion:(nullable FIRAuthTokenResultCallback)completion {
  748. [self getIDTokenResultForcingRefresh:NO
  749. completion:^(FIRAuthTokenResult *_Nullable tokenResult,
  750. NSError *_Nullable error) {
  751. if (completion) {
  752. dispatch_async(dispatch_get_main_queue(), ^{
  753. completion(tokenResult, error);
  754. });
  755. }
  756. }];
  757. }
  758. - (void)getIDTokenResultForcingRefresh:(BOOL)forceRefresh
  759. completion:(nullable FIRAuthTokenResultCallback)completion {
  760. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  761. [self internalGetTokenForcingRefresh:forceRefresh
  762. callback:^(NSString *_Nullable token, NSError *_Nullable error) {
  763. FIRAuthTokenResult *tokenResult;
  764. if (token) {
  765. tokenResult = [self parseIDToken:token error:&error];
  766. }
  767. if (completion) {
  768. dispatch_async(dispatch_get_main_queue(), ^{
  769. completion(tokenResult, error);
  770. });
  771. }
  772. }];
  773. });
  774. }
  775. /** @fn parseIDToken:error:
  776. @brief Parses the provided IDToken and returns an instance of FIRAuthTokenResult containing
  777. claims obtained from the IDToken.
  778. @param token The raw text of the Firebase IDToken encoded in base64.
  779. @param error An out parameter which would contain any error that occurs during parsing.
  780. @return An instance of FIRAuthTokenResult containing claims obtained from the IDToken.
  781. @remarks IDToken returned from the backend in some cases is of a length that is not a multiple
  782. of 4. In these cases this function pads the token with as many "=" characters as needed and
  783. then attempts to parse the token. If the token cannot be parsed an error is returned via the
  784. "error" out parameter.
  785. */
  786. - (nullable FIRAuthTokenResult *)parseIDToken:(NSString *)token error:(NSError **)error {
  787. // Though this is an internal method, errors returned here are surfaced in user-visible
  788. // callbacks.
  789. if (error) {
  790. *error = nil;
  791. }
  792. NSArray *tokenStringArray = [token componentsSeparatedByString:@"."];
  793. // The JWT should have three parts, though we only use the second in this method.
  794. if (tokenStringArray.count != 3) {
  795. if (error) {
  796. *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil];
  797. }
  798. return nil;
  799. }
  800. // The token payload is always the second index of the array.
  801. NSString *idToken = tokenStringArray[1];
  802. // Convert the base64URL encoded string to a base64 encoded string.
  803. // Replace "_" with "/"
  804. NSMutableString *tokenPayload =
  805. [[idToken stringByReplacingOccurrencesOfString:@"_" withString:@"/"] mutableCopy];
  806. // Replace "-" with "+"
  807. [tokenPayload replaceOccurrencesOfString:@"-"
  808. withString:@"+"
  809. options:kNilOptions
  810. range:NSMakeRange(0, tokenPayload.length)];
  811. // Pad the token payload with "=" signs if the payload's length is not a multiple of 4.
  812. while ((tokenPayload.length % 4) != 0) {
  813. [tokenPayload appendFormat:@"="];
  814. }
  815. NSData *decodedTokenPayloadData =
  816. [[NSData alloc] initWithBase64EncodedString:tokenPayload
  817. options:NSDataBase64DecodingIgnoreUnknownCharacters];
  818. if (!decodedTokenPayloadData) {
  819. if (error) {
  820. *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil];
  821. }
  822. return nil;
  823. }
  824. NSError *jsonError = nil;
  825. NSJSONReadingOptions options = NSJSONReadingMutableContainers|NSJSONReadingAllowFragments;
  826. NSDictionary *tokenPayloadDictionary =
  827. [NSJSONSerialization JSONObjectWithData:decodedTokenPayloadData
  828. options:options
  829. error:&jsonError];
  830. if (jsonError != nil) {
  831. if (error) {
  832. *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:jsonError];
  833. }
  834. return nil;
  835. }
  836. if (!tokenPayloadDictionary) {
  837. if (error) {
  838. *error = [FIRAuthErrorUtils malformedJWTErrorWithToken:token underlyingError:nil];
  839. }
  840. return nil;
  841. }
  842. // These are dates since 00:00:00 January 1 1970, as described by the Terminology section in
  843. // the JWT spec. https://tools.ietf.org/html/rfc7519
  844. NSDate *expDate =
  845. [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"exp"] doubleValue]];
  846. NSDate *authDate =
  847. [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"auth_time"] doubleValue]];
  848. NSDate *issuedDate =
  849. [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"iat"] doubleValue]];
  850. FIRAuthTokenResult *result =
  851. [[FIRAuthTokenResult alloc] initWithToken:token
  852. expirationDate:expDate
  853. authDate:authDate
  854. issuedAtDate:issuedDate
  855. signInProvider:tokenPayloadDictionary[@"sign_in_provider"]
  856. claims:tokenPayloadDictionary];
  857. return result;
  858. }
  859. /** @fn internalGetTokenForcingRefresh:callback:
  860. @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  861. @param callback The block to invoke when the token is available. Invoked asynchronously on the
  862. global work thread in the future.
  863. */
  864. - (void)internalGetTokenWithCallback:(nonnull FIRAuthTokenCallback)callback {
  865. [self internalGetTokenForcingRefresh:NO callback:callback];
  866. }
  867. - (void)internalGetTokenForcingRefresh:(BOOL)forceRefresh
  868. callback:(nonnull FIRAuthTokenCallback)callback {
  869. [_tokenService fetchAccessTokenForcingRefresh:forceRefresh
  870. callback:^(NSString *_Nullable token,
  871. NSError *_Nullable error,
  872. BOOL tokenUpdated) {
  873. if (error) {
  874. [self signOutIfTokenIsInvalidWithError:error];
  875. callback(nil, error);
  876. return;
  877. }
  878. if (tokenUpdated) {
  879. if (![self updateKeychain:&error]) {
  880. callback(nil, error);
  881. return;
  882. }
  883. }
  884. callback(token, nil);
  885. }];
  886. }
  887. - (void)internalVerifyBeforeUpdateEmailWithNewEmail:(NSString *)newEmail
  888. actionCodeSettings:(nullable FIRActionCodeSettings *)actionCodeSettings
  889. completion:(FIRVerifyBeforeUpdateEmailCallback)completion {
  890. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  891. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  892. NSError *_Nullable error) {
  893. if (error) {
  894. callInMainThreadWithError(completion, error);
  895. return;
  896. }
  897. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  898. FIRActionCodeSettings *settings = actionCodeSettings;
  899. FIRGetOOBConfirmationCodeRequest *request =
  900. [FIRGetOOBConfirmationCodeRequest verifyBeforeUpdateEmailWithAccessToken:accessToken
  901. newEmail:newEmail
  902. actionCodeSettings:settings
  903. requestConfiguration:configuration];
  904. [FIRAuthBackend getOOBConfirmationCode:request
  905. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable
  906. response,
  907. NSError *_Nullable error) {
  908. callInMainThreadWithError(completion, error);
  909. }];
  910. }];
  911. });
  912. }
  913. #pragma clang diagnostic push
  914. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  915. - (void)linkWithCredential:(FIRAuthCredential *)credential
  916. completion:(nullable FIRAuthDataResultCallback)completion {
  917. [self linkAndRetrieveDataWithCredential:credential completion:completion];
  918. }
  919. #pragma clang diagnostic pop
  920. - (void)linkAndRetrieveDataWithCredential:(FIRAuthCredential *)credential
  921. completion:(nullable FIRAuthDataResultCallback)completion {
  922. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  923. if (self->_providerData[credential.provider]) {
  924. callInMainThreadWithAuthDataResultAndError(completion,
  925. nil,
  926. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  927. return;
  928. }
  929. FIRAuthDataResult *result =
  930. [[FIRAuthDataResult alloc] initWithUser:self additionalUserInfo:nil];
  931. if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) {
  932. if (self->_hasEmailPasswordCredential) {
  933. callInMainThreadWithAuthDataResultAndError(completion,
  934. nil,
  935. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  936. return;
  937. }
  938. FIREmailPasswordAuthCredential *emailPasswordCredential =
  939. (FIREmailPasswordAuthCredential *)credential;
  940. if (emailPasswordCredential.password) {
  941. [self updateEmail:emailPasswordCredential.email
  942. password:emailPasswordCredential.password
  943. callback:^(NSError *error) {
  944. if (error) {
  945. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  946. } else {
  947. callInMainThreadWithAuthDataResultAndError(completion, result, nil);
  948. }
  949. }];
  950. } else {
  951. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  952. NSError *_Nullable error) {
  953. NSDictionary<NSString *, NSString *> *queryItems = [FIRAuthWebUtils parseURL:emailPasswordCredential.link];
  954. if (![queryItems count]) {
  955. NSURLComponents *urlComponents = [NSURLComponents componentsWithString:emailPasswordCredential.link];
  956. queryItems = [FIRAuthWebUtils parseURL:urlComponents.query];
  957. }
  958. NSString *actionCode = queryItems[@"oobCode"];
  959. FIRAuthRequestConfiguration *requestConfiguration = self.auth.requestConfiguration;
  960. FIREmailLinkSignInRequest *request =
  961. [[FIREmailLinkSignInRequest alloc] initWithEmail:emailPasswordCredential.email
  962. oobCode:actionCode
  963. requestConfiguration:requestConfiguration];
  964. request.IDToken = accessToken;
  965. [FIRAuthBackend emailLinkSignin:request
  966. callback:^(FIREmailLinkSignInResponse *_Nullable response,
  967. NSError *_Nullable error) {
  968. if (error){
  969. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  970. } else {
  971. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  972. NSError *_Nullable error) {
  973. if (error) {
  974. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  975. return;
  976. }
  977. FIRGetAccountInfoRequest *getAccountInfoRequest =
  978. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  979. requestConfiguration:requestConfiguration];
  980. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  981. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  982. NSError *_Nullable error) {
  983. if (error) {
  984. [self signOutIfTokenIsInvalidWithError:error];
  985. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  986. return;
  987. }
  988. self.anonymous = NO;
  989. [self updateWithGetAccountInfoResponse:response];
  990. if (![self updateKeychain:&error]) {
  991. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  992. return;
  993. }
  994. callInMainThreadWithAuthDataResultAndError(completion, result, nil);
  995. }];
  996. }];
  997. }
  998. }];
  999. }];
  1000. }
  1001. return;
  1002. }
  1003. if ([credential isKindOfClass:[FIRGameCenterAuthCredential class]]) {
  1004. FIRGameCenterAuthCredential *gameCenterCredential = (FIRGameCenterAuthCredential *)credential;
  1005. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1006. NSError *_Nullable error) {
  1007. FIRAuthRequestConfiguration *requestConfiguration = self.auth.requestConfiguration;
  1008. FIRSignInWithGameCenterRequest *gameCenterRequest =
  1009. [[FIRSignInWithGameCenterRequest alloc] initWithPlayerID:gameCenterCredential.playerID
  1010. publicKeyURL:gameCenterCredential.publicKeyURL
  1011. signature:gameCenterCredential.signature
  1012. salt:gameCenterCredential.salt
  1013. timestamp:gameCenterCredential.timestamp
  1014. displayName:gameCenterCredential.displayName
  1015. requestConfiguration:requestConfiguration];
  1016. gameCenterRequest.accessToken = accessToken;
  1017. [FIRAuthBackend signInWithGameCenter:gameCenterRequest
  1018. callback:^(FIRSignInWithGameCenterResponse *_Nullable response,
  1019. NSError *_Nullable error) {
  1020. if (error){
  1021. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1022. } else {
  1023. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1024. NSError *_Nullable error) {
  1025. if (error) {
  1026. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1027. return;
  1028. }
  1029. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1030. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  1031. requestConfiguration:requestConfiguration];
  1032. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  1033. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1034. NSError *_Nullable error) {
  1035. if (error) {
  1036. [self signOutIfTokenIsInvalidWithError:error];
  1037. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1038. return;
  1039. }
  1040. self.anonymous = NO;
  1041. [self updateWithGetAccountInfoResponse:response];
  1042. if (![self updateKeychain:&error]) {
  1043. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1044. return;
  1045. }
  1046. callInMainThreadWithAuthDataResultAndError(completion, result, nil);
  1047. }];
  1048. }];
  1049. }
  1050. }];
  1051. }];
  1052. return;
  1053. }
  1054. #if TARGET_OS_IOS
  1055. if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) {
  1056. FIRPhoneAuthCredential *phoneAuthCredential = (FIRPhoneAuthCredential *)credential;
  1057. [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential
  1058. isLinkOperation:YES
  1059. completion:^(NSError *_Nullable error) {
  1060. if (error){
  1061. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  1062. } else {
  1063. callInMainThreadWithAuthDataResultAndError(completion, result, nil);
  1064. }
  1065. }];
  1066. return;
  1067. }
  1068. #endif
  1069. [self->_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  1070. CallbackWithAuthDataResultAndError completeWithError =
  1071. ^(FIRAuthDataResult *result, NSError *error) {
  1072. complete();
  1073. callInMainThreadWithAuthDataResultAndError(completion, result, error);
  1074. };
  1075. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1076. NSError *_Nullable error) {
  1077. if (error) {
  1078. completeWithError(nil, error);
  1079. return;
  1080. }
  1081. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  1082. FIRVerifyAssertionRequest *request =
  1083. [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider
  1084. requestConfiguration:requestConfiguration];
  1085. [credential prepareVerifyAssertionRequest:request];
  1086. request.accessToken = accessToken;
  1087. [FIRAuthBackend verifyAssertion:request
  1088. callback:^(FIRVerifyAssertionResponse *response, NSError *error) {
  1089. if (error) {
  1090. [self signOutIfTokenIsInvalidWithError:error];
  1091. completeWithError(nil, error);
  1092. return;
  1093. }
  1094. FIRAdditionalUserInfo *additionalUserInfo =
  1095. [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response];
  1096. FIROAuthCredential *updatedOAuthCredential =
  1097. [[FIROAuthCredential alloc] initWithVerifyAssertionResponse:response];
  1098. FIRAuthDataResult *result =
  1099. [[FIRAuthDataResult alloc] initWithUser:self
  1100. additionalUserInfo:additionalUserInfo
  1101. credential:updatedOAuthCredential];
  1102. // Update the new token and refresh user info again.
  1103. self->_tokenService = [[FIRSecureTokenService alloc]
  1104. initWithRequestConfiguration:requestConfiguration
  1105. accessToken:response.IDToken
  1106. accessTokenExpirationDate:response.approximateExpirationDate
  1107. refreshToken:response.refreshToken];
  1108. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1109. NSError *_Nullable error) {
  1110. if (error) {
  1111. completeWithError(nil, error);
  1112. return;
  1113. }
  1114. FIRGetAccountInfoRequest *getAccountInfoRequest =
  1115. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  1116. requestConfiguration:requestConfiguration];
  1117. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  1118. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  1119. NSError *_Nullable error) {
  1120. if (error) {
  1121. [self signOutIfTokenIsInvalidWithError:error];
  1122. completeWithError(nil, error);
  1123. return;
  1124. }
  1125. self.anonymous = NO;
  1126. [self updateWithGetAccountInfoResponse:response];
  1127. if (![self updateKeychain:&error]) {
  1128. completeWithError(nil, error);
  1129. return;
  1130. }
  1131. completeWithError(result, nil);
  1132. }];
  1133. }];
  1134. }];
  1135. }];
  1136. }];
  1137. });
  1138. }
  1139. - (void)unlinkFromProvider:(NSString *)provider
  1140. completion:(nullable FIRAuthResultCallback)completion {
  1141. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  1142. CallbackWithError completeAndCallbackWithError = ^(NSError *error) {
  1143. complete();
  1144. callInMainThreadWithUserAndError(completion, self, error);
  1145. };
  1146. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1147. NSError *_Nullable error) {
  1148. if (error) {
  1149. completeAndCallbackWithError(error);
  1150. return;
  1151. }
  1152. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  1153. FIRSetAccountInfoRequest *setAccountInfoRequest =
  1154. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:requestConfiguration];
  1155. setAccountInfoRequest.accessToken = accessToken;
  1156. if ([provider isEqualToString:FIREmailAuthProviderID]) {
  1157. if (!self->_hasEmailPasswordCredential) {
  1158. completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]);
  1159. return;
  1160. }
  1161. setAccountInfoRequest.deleteAttributes = @[ FIRSetAccountInfoUserAttributePassword ];
  1162. } else {
  1163. if (!self->_providerData[provider]) {
  1164. completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]);
  1165. return;
  1166. }
  1167. setAccountInfoRequest.deleteProviders = @[ provider ];
  1168. }
  1169. [FIRAuthBackend setAccountInfo:setAccountInfoRequest
  1170. callback:^(FIRSetAccountInfoResponse *_Nullable response,
  1171. NSError *_Nullable error) {
  1172. if (error) {
  1173. [self signOutIfTokenIsInvalidWithError:error];
  1174. completeAndCallbackWithError(error);
  1175. return;
  1176. }
  1177. // We can't just use the provider info objects in FIRSetAccountInfoResponse because they
  1178. // don't have localID and email fields. Remove the specific provider manually.
  1179. NSMutableDictionary *mutableProviderData = [self->_providerData mutableCopy];
  1180. [mutableProviderData removeObjectForKey:provider];
  1181. self->_providerData = [mutableProviderData copy];
  1182. if ([provider isEqualToString:FIREmailAuthProviderID]) {
  1183. self->_hasEmailPasswordCredential = NO;
  1184. }
  1185. #if TARGET_OS_IOS
  1186. // After successfully unlinking a phone auth provider, remove the phone number from the
  1187. // cached user info.
  1188. if ([provider isEqualToString:FIRPhoneAuthProviderID]) {
  1189. self->_phoneNumber = nil;
  1190. }
  1191. #endif
  1192. if (response.IDToken && response.refreshToken) {
  1193. FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc]
  1194. initWithRequestConfiguration:requestConfiguration
  1195. accessToken:response.IDToken
  1196. accessTokenExpirationDate:response.approximateExpirationDate
  1197. refreshToken:response.refreshToken];
  1198. [self setTokenService:tokenService callback:^(NSError *_Nullable error) {
  1199. completeAndCallbackWithError(error);
  1200. }];
  1201. return;
  1202. }
  1203. if (![self updateKeychain:&error]) {
  1204. completeAndCallbackWithError(error);
  1205. return;
  1206. }
  1207. completeAndCallbackWithError(nil);
  1208. }];
  1209. }];
  1210. }];
  1211. }
  1212. - (void)sendEmailVerificationWithCompletion:(nullable FIRSendEmailVerificationCallback)completion {
  1213. [self sendEmailVerificationWithNullableActionCodeSettings:nil completion:completion];
  1214. }
  1215. - (void)sendEmailVerificationWithActionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings
  1216. completion:(nullable FIRSendEmailVerificationCallback)
  1217. completion {
  1218. [self sendEmailVerificationWithNullableActionCodeSettings:actionCodeSettings
  1219. completion:completion];
  1220. }
  1221. /** @fn sendEmailVerificationWithNullableActionCodeSettings:completion:
  1222. @brief Initiates email verification for the user.
  1223. @param actionCodeSettings Optionally, a @c FIRActionCodeSettings object containing settings
  1224. related to the handling action codes.
  1225. */
  1226. - (void)sendEmailVerificationWithNullableActionCodeSettings:(nullable FIRActionCodeSettings *)
  1227. actionCodeSettings
  1228. completion:
  1229. (nullable FIRSendEmailVerificationCallback)
  1230. completion {
  1231. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1232. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1233. NSError *_Nullable error) {
  1234. if (error) {
  1235. callInMainThreadWithError(completion, error);
  1236. return;
  1237. }
  1238. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  1239. FIRGetOOBConfirmationCodeRequest *request =
  1240. [FIRGetOOBConfirmationCodeRequest verifyEmailRequestWithAccessToken:accessToken
  1241. actionCodeSettings:actionCodeSettings
  1242. requestConfiguration:configuration];
  1243. [FIRAuthBackend getOOBConfirmationCode:request
  1244. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable
  1245. response,
  1246. NSError *_Nullable error) {
  1247. [self signOutIfTokenIsInvalidWithError:error];
  1248. callInMainThreadWithError(completion, error);
  1249. }];
  1250. }];
  1251. });
  1252. }
  1253. - (void)deleteWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1254. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1255. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1256. NSError *_Nullable error) {
  1257. if (error) {
  1258. callInMainThreadWithError(completion, error);
  1259. return;
  1260. }
  1261. FIRDeleteAccountRequest *deleteUserRequest =
  1262. [[FIRDeleteAccountRequest alloc] initWitLocalID:self->_userID
  1263. accessToken:accessToken
  1264. requestConfiguration:self->_auth.requestConfiguration];
  1265. [FIRAuthBackend deleteAccount:deleteUserRequest callback:^(NSError *_Nullable error) {
  1266. if (error) {
  1267. callInMainThreadWithError(completion, error);
  1268. return;
  1269. }
  1270. if (![self->_auth signOutByForceWithUserID:self->_userID error:&error]) {
  1271. callInMainThreadWithError(completion, error);
  1272. return;
  1273. }
  1274. callInMainThreadWithError(completion, error);
  1275. }];
  1276. }];
  1277. });
  1278. }
  1279. /** @fn signOutIfTokenIsInvalidWithError:
  1280. @brief Signs out this user if the user or the token is invalid.
  1281. @param error The error from the server.
  1282. */
  1283. - (void)signOutIfTokenIsInvalidWithError:(nullable NSError *)error {
  1284. NSInteger errorCode = error.code;
  1285. if (errorCode == FIRAuthErrorCodeUserNotFound ||
  1286. errorCode == FIRAuthErrorCodeUserDisabled ||
  1287. errorCode == FIRAuthErrorCodeInvalidUserToken ||
  1288. errorCode == FIRAuthErrorCodeUserTokenExpired) {
  1289. FIRLogNotice(kFIRLoggerAuth, @"I-AUT000016",
  1290. @"Invalid user token detected, user is automatically signed out.");
  1291. [_auth signOutByForceWithUserID:_userID error:NULL];
  1292. }
  1293. }
  1294. @end
  1295. @implementation FIRUserProfileChangeRequest {
  1296. /** @var _user
  1297. @brief The user associated with the change request.
  1298. */
  1299. FIRUser *_user;
  1300. /** @var _displayName
  1301. @brief The display name value to set if @c _displayNameSet is YES.
  1302. */
  1303. NSString *_displayName;
  1304. /** @var _displayNameSet
  1305. @brief Indicates the display name should be part of the change request.
  1306. */
  1307. BOOL _displayNameSet;
  1308. /** @var _photoURL
  1309. @brief The photo URL value to set if @c _displayNameSet is YES.
  1310. */
  1311. NSURL *_photoURL;
  1312. /** @var _photoURLSet
  1313. @brief Indicates the photo URL should be part of the change request.
  1314. */
  1315. BOOL _photoURLSet;
  1316. /** @var _consumed
  1317. @brief Indicates the @c commitChangesWithCallback: method has already been invoked.
  1318. */
  1319. BOOL _consumed;
  1320. }
  1321. - (nullable instancetype)initWithUser:(FIRUser *)user {
  1322. self = [super init];
  1323. if (self) {
  1324. _user = user;
  1325. }
  1326. return self;
  1327. }
  1328. - (nullable NSString *)displayName {
  1329. return _displayName;
  1330. }
  1331. - (void)setDisplayName:(nullable NSString *)displayName {
  1332. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1333. if (self->_consumed) {
  1334. [NSException raise:NSInternalInconsistencyException
  1335. format:@"%@",
  1336. @"Invalid call to setDisplayName: after commitChangesWithCallback:."];
  1337. return;
  1338. }
  1339. self->_displayNameSet = YES;
  1340. self->_displayName = [displayName copy];
  1341. });
  1342. }
  1343. - (nullable NSURL *)photoURL {
  1344. return _photoURL;
  1345. }
  1346. - (void)setPhotoURL:(nullable NSURL *)photoURL {
  1347. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1348. if (self->_consumed) {
  1349. [NSException raise:NSInternalInconsistencyException
  1350. format:@"%@",
  1351. @"Invalid call to setPhotoURL: after commitChangesWithCallback:."];
  1352. return;
  1353. }
  1354. self->_photoURLSet = YES;
  1355. self->_photoURL = [photoURL copy];
  1356. });
  1357. }
  1358. /** @fn hasUpdates
  1359. @brief Indicates at least one field has a value which needs to be committed.
  1360. */
  1361. - (BOOL)hasUpdates {
  1362. return _displayNameSet || _photoURLSet;
  1363. }
  1364. - (void)commitChangesWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1365. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1366. if (self->_consumed) {
  1367. [NSException raise:NSInternalInconsistencyException
  1368. format:@"%@",
  1369. @"commitChangesWithCallback: should only be called once."];
  1370. return;
  1371. }
  1372. self->_consumed = YES;
  1373. // Return fast if there is nothing to update:
  1374. if (![self hasUpdates]) {
  1375. callInMainThreadWithError(completion, nil);
  1376. return;
  1377. }
  1378. NSString *displayName = [self->_displayName copy];
  1379. BOOL displayNameWasSet = self->_displayNameSet;
  1380. NSURL *photoURL = [self->_photoURL copy];
  1381. BOOL photoURLWasSet = self->_photoURLSet;
  1382. [self->_user executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user,
  1383. FIRSetAccountInfoRequest *request) {
  1384. if (photoURLWasSet) {
  1385. request.photoURL = photoURL;
  1386. }
  1387. if (displayNameWasSet) {
  1388. request.displayName = displayName;
  1389. }
  1390. }
  1391. callback:^(NSError *_Nullable error) {
  1392. if (error) {
  1393. callInMainThreadWithError(completion, error);
  1394. return;
  1395. }
  1396. if (displayNameWasSet) {
  1397. [self->_user setDisplayName:displayName];
  1398. }
  1399. if (photoURLWasSet) {
  1400. [self->_user setPhotoURL:photoURL];
  1401. }
  1402. if (![self->_user updateKeychain:&error]) {
  1403. callInMainThreadWithError(completion, error);
  1404. return;
  1405. }
  1406. callInMainThreadWithError(completion, nil);
  1407. }];
  1408. });
  1409. }
  1410. @end
  1411. NS_ASSUME_NONNULL_END