FIRUser.m 46 KB

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