FIRUser.m 52 KB

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