FIRUser.m 44 KB

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