FIRUser.m 43 KB

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