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.

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