FIRUser.m 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362
  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 copy];
  513. }
  514. if (self->_email) {
  515. if (!hadEmailPasswordCredential) {
  516. // The list of providers need to be updated for the newly added email-password provider.
  517. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  518. NSError *_Nullable error) {
  519. if (error) {
  520. callback(error);
  521. return;
  522. }
  523. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  524. FIRGetAccountInfoRequest *getAccountInfoRequest =
  525. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  526. requestConfiguration:requestConfiguration];
  527. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  528. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  529. NSError *_Nullable error) {
  530. if (error) {
  531. [self signOutIfTokenIsInvalidWithError:error];
  532. callback(error);
  533. return;
  534. }
  535. for (FIRGetAccountInfoResponseUser *userAccountInfo in response.users) {
  536. // Set the account to non-anonymous if there are any providers, even if
  537. // they're not email/password ones.
  538. if (userAccountInfo.providerUserInfo.count > 0) {
  539. self->_anonymous = NO;
  540. }
  541. for (FIRGetAccountInfoResponseProviderUserInfo *providerUserInfo in
  542. userAccountInfo.providerUserInfo) {
  543. if ([providerUserInfo.providerID isEqualToString:FIREmailAuthProviderID]) {
  544. self->_hasEmailPasswordCredential = YES;
  545. break;
  546. }
  547. }
  548. }
  549. [self updateWithGetAccountInfoResponse:response];
  550. if (![self updateKeychain:&error]) {
  551. callback(error);
  552. return;
  553. }
  554. callback(nil);
  555. }];
  556. }];
  557. return;
  558. }
  559. }
  560. if (![self updateKeychain:&error]) {
  561. callback(error);
  562. return;
  563. }
  564. callback(nil);
  565. }];
  566. }
  567. - (void)updateEmail:(NSString *)email completion:(nullable FIRUserProfileChangeCallback)completion {
  568. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  569. [self updateEmail:email password:nil callback:^(NSError *_Nullable error) {
  570. callInMainThreadWithError(completion, error);
  571. }];
  572. });
  573. }
  574. - (void)updatePassword:(NSString *)password
  575. completion:(nullable FIRUserProfileChangeCallback)completion {
  576. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  577. [self updateEmail:nil password:password callback:^(NSError *_Nullable error){
  578. callInMainThreadWithError(completion, error);
  579. }];
  580. });
  581. }
  582. #if TARGET_OS_IOS
  583. /** @fn internalUpdateOrLinkPhoneNumberCredential:completion:
  584. @brief Updates the phone number for the user. On success, the cached user profile data is
  585. updated.
  586. @param phoneAuthCredential The new phone number credential corresponding to the phone number
  587. to be added to the Firebase account, if a phone number is already linked to the account this
  588. new phone number will replace it.
  589. @param isLinkOperation Boolean value indicating whether or not this is a link operation.
  590. @param completion Optionally; the block invoked when the user profile change has finished.
  591. Invoked asynchronously on the global work queue in the future.
  592. */
  593. - (void)internalUpdateOrLinkPhoneNumberCredential:(FIRPhoneAuthCredential *)phoneAuthCredential
  594. isLinkOperation:(BOOL)isLinkOperation
  595. completion:(FIRUserProfileChangeCallback)completion {
  596. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  597. NSError *_Nullable error) {
  598. if (error) {
  599. completion(error);
  600. return;
  601. }
  602. FIRAuthOperationType operation =
  603. isLinkOperation ? FIRAuthOperationTypeLink : FIRAuthOperationTypeUpdate;
  604. FIRVerifyPhoneNumberRequest *request = [[FIRVerifyPhoneNumberRequest alloc]
  605. initWithVerificationID:phoneAuthCredential.verificationID
  606. verificationCode:phoneAuthCredential.verificationCode
  607. operation:operation
  608. requestConfiguration:self->_auth.requestConfiguration];
  609. request.accessToken = accessToken;
  610. [FIRAuthBackend verifyPhoneNumber:request
  611. callback:^(FIRVerifyPhoneNumberResponse *_Nullable response,
  612. NSError *_Nullable error) {
  613. if (error) {
  614. [self signOutIfTokenIsInvalidWithError:error];
  615. completion(error);
  616. return;
  617. }
  618. // Get account info to update cached user info.
  619. [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user,
  620. NSError *_Nullable error) {
  621. if (error) {
  622. [self signOutIfTokenIsInvalidWithError:error];
  623. completion(error);
  624. return;
  625. }
  626. self->_anonymous = NO;
  627. if (![self updateKeychain:&error]) {
  628. completion(error);
  629. return;
  630. }
  631. completion(nil);
  632. }];
  633. }];
  634. }];
  635. }
  636. - (void)updatePhoneNumberCredential:(FIRPhoneAuthCredential *)phoneAuthCredential
  637. completion:(nullable FIRUserProfileChangeCallback)completion {
  638. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  639. [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential
  640. isLinkOperation:NO
  641. completion:^(NSError *_Nullable error) {
  642. callInMainThreadWithError(completion, error);
  643. }];
  644. });
  645. }
  646. #endif
  647. - (FIRUserProfileChangeRequest *)profileChangeRequest {
  648. __block FIRUserProfileChangeRequest *result;
  649. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  650. result = [[FIRUserProfileChangeRequest alloc] initWithUser:self];
  651. });
  652. return result;
  653. }
  654. - (void)setDisplayName:(NSString *)displayName {
  655. _displayName = [displayName copy];
  656. }
  657. - (void)setPhotoURL:(NSURL *)photoURL {
  658. _photoURL = [photoURL copy];
  659. }
  660. - (NSString *)rawAccessToken {
  661. return _tokenService.rawAccessToken;
  662. }
  663. - (NSDate *)accessTokenExpirationDate {
  664. return _tokenService.accessTokenExpirationDate;
  665. }
  666. #pragma mark -
  667. - (void)reloadWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  668. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  669. [self getAccountInfoRefreshingCache:^(FIRGetAccountInfoResponseUser *_Nullable user,
  670. NSError *_Nullable error) {
  671. callInMainThreadWithError(completion, error);
  672. }];
  673. });
  674. }
  675. #pragma mark -
  676. - (void)reauthenticateWithCredential:(FIRAuthCredential *)credential
  677. completion:(nullable FIRUserProfileChangeCallback)completion {
  678. FIRAuthDataResultCallback callback = ^(FIRAuthDataResult *_Nullable authResult,
  679. NSError *_Nullable error) {
  680. completion(error);
  681. };
  682. [self reauthenticateAndRetrieveDataWithCredential:credential completion:callback];
  683. }
  684. - (void)
  685. reauthenticateAndRetrieveDataWithCredential:(FIRAuthCredential *) credential
  686. completion:(nullable FIRAuthDataResultCallback) completion {
  687. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  688. [self->_auth internalSignInAndRetrieveDataWithCredential:credential
  689. isReauthentication:YES
  690. callback:^(FIRAuthDataResult *_Nullable
  691. authResult,
  692. NSError *_Nullable error) {
  693. if (error) {
  694. // If "user not found" error returned by backend, translate to user mismatch error which is
  695. // more accurate.
  696. if (error.code == FIRAuthErrorCodeUserNotFound) {
  697. error = [FIRAuthErrorUtils userMismatchError];
  698. }
  699. callInMainThreadWithAuthDataResultAndError(completion, authResult, error);
  700. return;
  701. }
  702. if (![authResult.user.uid isEqual:[self->_auth getUID]]) {
  703. callInMainThreadWithAuthDataResultAndError(completion, authResult,
  704. [FIRAuthErrorUtils userMismatchError]);
  705. return;
  706. }
  707. // Successful reauthenticate
  708. [self setTokenService:authResult.user->_tokenService callback:^(NSError *_Nullable error) {
  709. callInMainThreadWithAuthDataResultAndError(completion, authResult, error);
  710. }];
  711. }];
  712. });
  713. }
  714. - (nullable NSString *)refreshToken {
  715. __block NSString *result;
  716. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  717. result = self->_tokenService.refreshToken;
  718. });
  719. return result;
  720. }
  721. - (void)getIDTokenWithCompletion:(nullable FIRAuthTokenCallback)completion {
  722. // |getIDTokenForcingRefresh:completion:| is also a public API so there is no need to dispatch to
  723. // global work queue here.
  724. [self getIDTokenForcingRefresh:NO completion:completion];
  725. }
  726. - (void)getIDTokenForcingRefresh:(BOOL)forceRefresh
  727. completion:(nullable FIRAuthTokenCallback)completion {
  728. [self getIDTokenResultForcingRefresh:forceRefresh
  729. completion:^(FIRAuthTokenResult *_Nullable tokenResult,
  730. NSError *_Nullable error) {
  731. if (completion) {
  732. dispatch_async(dispatch_get_main_queue(), ^{
  733. completion(tokenResult.token, error);
  734. });
  735. }
  736. }];
  737. }
  738. - (void)getIDTokenResultWithCompletion:(nullable FIRAuthTokenResultCallback)completion {
  739. [self getIDTokenResultForcingRefresh:NO
  740. completion:^(FIRAuthTokenResult *_Nullable tokenResult,
  741. NSError *_Nullable error) {
  742. if (completion) {
  743. dispatch_async(dispatch_get_main_queue(), ^{
  744. completion(tokenResult, error);
  745. });
  746. }
  747. }];
  748. }
  749. - (void)getIDTokenResultForcingRefresh:(BOOL)forceRefresh
  750. completion:(nullable FIRAuthTokenResultCallback)completion {
  751. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  752. [self internalGetTokenForcingRefresh:forceRefresh
  753. callback:^(NSString *_Nullable token, NSError *_Nullable error) {
  754. FIRAuthTokenResult *tokenResult;
  755. if (token) {
  756. tokenResult = [self parseIDToken:token error:&error];
  757. }
  758. if (completion) {
  759. dispatch_async(dispatch_get_main_queue(), ^{
  760. completion(tokenResult, error);
  761. });
  762. }
  763. }];
  764. });
  765. }
  766. /** @fn parseIDToken:error:
  767. @brief Parses the provided IDToken and returns an instance of FIRAuthTokenResult containing
  768. claims obtained from the IDToken.
  769. @param token The raw text of the Firebase IDToken encoded in base64.
  770. @param error An out parameter which would contain any error that occurs during parsing.
  771. @return An instance of FIRAuthTokenResult containing claims obtained from the IDToken.
  772. @remarks IDToken returned from the backend in some cases is of a length that is not a multiple
  773. of 4. In these cases this function pads the token with as many "=" characters as needed and
  774. then attempts to parse the token. If the token cannot be parsed an error is returned via the
  775. "error" out parameter.
  776. */
  777. - (FIRAuthTokenResult *)parseIDToken:(NSString *)token error:(NSError **)error {
  778. *error = nil;
  779. NSArray *tokenStringArray = [token componentsSeparatedByString:@"."];
  780. // The token payload is always the second index of the array.
  781. NSString *idToken = tokenStringArray[1];
  782. // Convert the base64URL encoded string to a base64 encoded string.
  783. // Replace "_" with "/"
  784. NSMutableString *tokenPayload =
  785. [[idToken stringByReplacingOccurrencesOfString:@"_" withString:@"/"] mutableCopy];
  786. // Replace "-" with "+"
  787. tokenPayload =
  788. [[tokenPayload stringByReplacingOccurrencesOfString:@"-" withString:@"+"] mutableCopy];
  789. // Pad the token payload with "=" signs if the payload's length is not a multiple of 4.
  790. while ((tokenPayload.length % 4) != 0) {
  791. [tokenPayload appendFormat:@"="];
  792. }
  793. NSData *decodedTokenPayloadData =
  794. [[NSData alloc] initWithBase64EncodedString:tokenPayload
  795. options:NSDataBase64DecodingIgnoreUnknownCharacters];
  796. if (!decodedTokenPayloadData) {
  797. *error = [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:token];
  798. return nil;
  799. }
  800. NSDictionary *tokenPayloadDictionary =
  801. [NSJSONSerialization JSONObjectWithData:decodedTokenPayloadData
  802. options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
  803. error:error];
  804. if (*error) {
  805. return nil;
  806. }
  807. if (!tokenPayloadDictionary) {
  808. *error = [FIRAuthErrorUtils unexpectedResponseWithDeserializedResponse:token];
  809. return nil;
  810. }
  811. // These are dates since 00:00:00 January 1 1970, as described by the Terminology section in
  812. // the JWT spec. https://tools.ietf.org/html/rfc7519
  813. NSDate *expDate =
  814. [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"exp"] doubleValue]];
  815. NSDate *authDate =
  816. [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"auth_time"] doubleValue]];
  817. NSDate *issuedDate =
  818. [NSDate dateWithTimeIntervalSince1970:[tokenPayloadDictionary[@"iat"] doubleValue]];
  819. FIRAuthTokenResult *result =
  820. [[FIRAuthTokenResult alloc] initWithToken:token
  821. expirationDate:expDate
  822. authDate:authDate
  823. issuedAtDate:issuedDate
  824. signInProvider:tokenPayloadDictionary[@"sign_in_provider"]
  825. claims:tokenPayloadDictionary];
  826. return result;
  827. }
  828. /** @fn internalGetTokenForcingRefresh:callback:
  829. @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  830. @param callback The block to invoke when the token is available. Invoked asynchronously on the
  831. global work thread in the future.
  832. */
  833. - (void)internalGetTokenWithCallback:(nonnull FIRAuthTokenCallback)callback {
  834. [self internalGetTokenForcingRefresh:NO callback:callback];
  835. }
  836. - (void)internalGetTokenForcingRefresh:(BOOL)forceRefresh
  837. callback:(nonnull FIRAuthTokenCallback)callback {
  838. [_tokenService fetchAccessTokenForcingRefresh:forceRefresh
  839. callback:^(NSString *_Nullable token,
  840. NSError *_Nullable error,
  841. BOOL tokenUpdated) {
  842. if (error) {
  843. [self signOutIfTokenIsInvalidWithError:error];
  844. callback(nil, error);
  845. return;
  846. }
  847. if (tokenUpdated) {
  848. if (![self updateKeychain:&error]) {
  849. callback(nil, error);
  850. return;
  851. }
  852. }
  853. callback(token, nil);
  854. }];
  855. }
  856. - (void)linkWithCredential:(FIRAuthCredential *)credential
  857. completion:(nullable FIRAuthResultCallback)completion {
  858. FIRAuthDataResultCallback callback = ^(FIRAuthDataResult *_Nullable authResult,
  859. NSError *_Nullable error) {
  860. completion(authResult.user, error);
  861. };
  862. [self linkAndRetrieveDataWithCredential:credential completion:callback];
  863. }
  864. - (void)linkAndRetrieveDataWithCredential:(FIRAuthCredential *)credential
  865. completion:(nullable FIRAuthDataResultCallback)completion {
  866. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  867. if (self->_providerData[credential.provider]) {
  868. callInMainThreadWithAuthDataResultAndError(completion,
  869. nil,
  870. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  871. return;
  872. }
  873. FIRAuthDataResult *result =
  874. [[FIRAuthDataResult alloc] initWithUser:self additionalUserInfo:nil];
  875. if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) {
  876. if (self->_hasEmailPasswordCredential) {
  877. callInMainThreadWithAuthDataResultAndError(completion,
  878. nil,
  879. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  880. return;
  881. }
  882. FIREmailPasswordAuthCredential *emailPasswordCredential =
  883. (FIREmailPasswordAuthCredential *)credential;
  884. [self updateEmail:emailPasswordCredential.email
  885. password:emailPasswordCredential.password
  886. callback:^(NSError *error) {
  887. if (error) {
  888. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  889. } else {
  890. callInMainThreadWithAuthDataResultAndError(completion, result, nil);
  891. }
  892. }];
  893. return;
  894. }
  895. #if TARGET_OS_IOS
  896. if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) {
  897. FIRPhoneAuthCredential *phoneAuthCredential = (FIRPhoneAuthCredential *)credential;
  898. [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential
  899. isLinkOperation:YES
  900. completion:^(NSError *_Nullable error) {
  901. if (error){
  902. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  903. } else {
  904. callInMainThreadWithAuthDataResultAndError(completion, result, nil);
  905. }
  906. }];
  907. return;
  908. }
  909. #endif
  910. [self->_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  911. CallbackWithAuthDataResultAndError completeWithError =
  912. ^(FIRAuthDataResult *result, NSError *error) {
  913. complete();
  914. callInMainThreadWithAuthDataResultAndError(completion, result, error);
  915. };
  916. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  917. NSError *_Nullable error) {
  918. if (error) {
  919. completeWithError(nil, error);
  920. return;
  921. }
  922. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  923. FIRVerifyAssertionRequest *request =
  924. [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider
  925. requestConfiguration:requestConfiguration];
  926. [credential prepareVerifyAssertionRequest:request];
  927. request.accessToken = accessToken;
  928. [FIRAuthBackend verifyAssertion:request
  929. callback:^(FIRVerifyAssertionResponse *response, NSError *error) {
  930. if (error) {
  931. [self signOutIfTokenIsInvalidWithError:error];
  932. completeWithError(nil, error);
  933. return;
  934. }
  935. FIRAdditionalUserInfo *additionalUserInfo =
  936. [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response];
  937. FIRAuthDataResult *result =
  938. [[FIRAuthDataResult alloc] initWithUser:self additionalUserInfo:additionalUserInfo];
  939. // Update the new token and refresh user info again.
  940. self->_tokenService = [[FIRSecureTokenService alloc]
  941. initWithRequestConfiguration:requestConfiguration
  942. accessToken:response.IDToken
  943. accessTokenExpirationDate:response.approximateExpirationDate
  944. refreshToken:response.refreshToken];
  945. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  946. NSError *_Nullable error) {
  947. if (error) {
  948. completeWithError(nil, error);
  949. return;
  950. }
  951. FIRGetAccountInfoRequest *getAccountInfoRequest =
  952. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  953. requestConfiguration:requestConfiguration];
  954. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  955. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  956. NSError *_Nullable error) {
  957. if (error) {
  958. [self signOutIfTokenIsInvalidWithError:error];
  959. completeWithError(nil, error);
  960. return;
  961. }
  962. self->_anonymous = NO;
  963. [self updateWithGetAccountInfoResponse:response];
  964. if (![self updateKeychain:&error]) {
  965. completeWithError(nil, error);
  966. return;
  967. }
  968. completeWithError(result, nil);
  969. }];
  970. }];
  971. }];
  972. }];
  973. }];
  974. });
  975. }
  976. - (void)unlinkFromProvider:(NSString *)provider
  977. completion:(nullable FIRAuthResultCallback)completion {
  978. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  979. CallbackWithError completeAndCallbackWithError = ^(NSError *error) {
  980. complete();
  981. callInMainThreadWithUserAndError(completion, self, error);
  982. };
  983. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  984. NSError *_Nullable error) {
  985. if (error) {
  986. completeAndCallbackWithError(error);
  987. return;
  988. }
  989. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  990. FIRSetAccountInfoRequest *setAccountInfoRequest =
  991. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:requestConfiguration];
  992. setAccountInfoRequest.accessToken = accessToken;
  993. BOOL isEmailPasswordProvider = [provider isEqualToString:FIREmailAuthProviderID];
  994. if (isEmailPasswordProvider) {
  995. if (!self->_hasEmailPasswordCredential) {
  996. completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]);
  997. return;
  998. }
  999. setAccountInfoRequest.deleteAttributes = @[ FIRSetAccountInfoUserAttributePassword ];
  1000. } else {
  1001. if (!self->_providerData[provider]) {
  1002. completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]);
  1003. return;
  1004. }
  1005. setAccountInfoRequest.deleteProviders = @[ provider ];
  1006. }
  1007. [FIRAuthBackend setAccountInfo:setAccountInfoRequest
  1008. callback:^(FIRSetAccountInfoResponse *_Nullable response,
  1009. NSError *_Nullable error) {
  1010. if (error) {
  1011. [self signOutIfTokenIsInvalidWithError:error];
  1012. completeAndCallbackWithError(error);
  1013. return;
  1014. }
  1015. if (isEmailPasswordProvider) {
  1016. self->_hasEmailPasswordCredential = NO;
  1017. } else {
  1018. // We can't just use the provider info objects in FIRSetAcccountInfoResponse because they
  1019. // don't have localID and email fields. Remove the specific provider manually.
  1020. NSMutableDictionary *mutableProviderData = [self->_providerData mutableCopy];
  1021. [mutableProviderData removeObjectForKey:provider];
  1022. self->_providerData = [mutableProviderData copy];
  1023. #if TARGET_OS_IOS
  1024. // After successfully unlinking a phone auth provider, remove the phone number from the
  1025. // cached user info.
  1026. if ([provider isEqualToString:FIRPhoneAuthProviderID]) {
  1027. self->_phoneNumber = nil;
  1028. }
  1029. #endif
  1030. }
  1031. if (response.IDToken && response.refreshToken) {
  1032. FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc]
  1033. initWithRequestConfiguration:requestConfiguration
  1034. accessToken:response.IDToken
  1035. accessTokenExpirationDate:response.approximateExpirationDate
  1036. refreshToken:response.refreshToken];
  1037. [self setTokenService:tokenService callback:^(NSError *_Nullable error) {
  1038. completeAndCallbackWithError(error);
  1039. }];
  1040. return;
  1041. }
  1042. if (![self updateKeychain:&error]) {
  1043. completeAndCallbackWithError(error);
  1044. return;
  1045. }
  1046. completeAndCallbackWithError(nil);
  1047. }];
  1048. }];
  1049. }];
  1050. }
  1051. - (void)sendEmailVerificationWithCompletion:(nullable FIRSendEmailVerificationCallback)completion {
  1052. [self sendEmailVerificationWithNullableActionCodeSettings:nil completion:completion];
  1053. }
  1054. - (void)sendEmailVerificationWithActionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings
  1055. completion:(nullable FIRSendEmailVerificationCallback)
  1056. completion {
  1057. [self sendEmailVerificationWithNullableActionCodeSettings:actionCodeSettings
  1058. completion:completion];
  1059. }
  1060. /** @fn sendEmailVerificationWithNullableActionCodeSettings:completion:
  1061. @brief Initiates email verification for the user.
  1062. @param actionCodeSettings Optionally, a @c FIRActionCodeSettings object containing settings
  1063. related to the handling action codes.
  1064. */
  1065. - (void)sendEmailVerificationWithNullableActionCodeSettings:(nullable FIRActionCodeSettings *)
  1066. actionCodeSettings
  1067. completion:
  1068. (nullable FIRSendEmailVerificationCallback)
  1069. completion {
  1070. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1071. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1072. NSError *_Nullable error) {
  1073. if (error) {
  1074. callInMainThreadWithError(completion, error);
  1075. return;
  1076. }
  1077. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  1078. FIRGetOOBConfirmationCodeRequest *request =
  1079. [FIRGetOOBConfirmationCodeRequest verifyEmailRequestWithAccessToken:accessToken
  1080. actionCodeSettings:actionCodeSettings
  1081. requestConfiguration:configuration];
  1082. [FIRAuthBackend getOOBConfirmationCode:request
  1083. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable
  1084. response,
  1085. NSError *_Nullable error) {
  1086. [self signOutIfTokenIsInvalidWithError:error];
  1087. callInMainThreadWithError(completion, error);
  1088. }];
  1089. }];
  1090. });
  1091. }
  1092. - (void)deleteWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1093. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1094. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1095. NSError *_Nullable error) {
  1096. if (error) {
  1097. callInMainThreadWithError(completion, error);
  1098. return;
  1099. }
  1100. FIRDeleteAccountRequest *deleteUserRequest =
  1101. [[FIRDeleteAccountRequest alloc] initWitLocalID:self->_userID
  1102. accessToken:accessToken
  1103. requestConfiguration:self->_auth.requestConfiguration];
  1104. [FIRAuthBackend deleteAccount:deleteUserRequest callback:^(NSError *_Nullable error) {
  1105. if (error) {
  1106. callInMainThreadWithError(completion, error);
  1107. return;
  1108. }
  1109. if (![self->_auth signOutByForceWithUserID:self->_userID error:&error]) {
  1110. callInMainThreadWithError(completion, error);
  1111. return;
  1112. }
  1113. callInMainThreadWithError(completion, error);
  1114. }];
  1115. }];
  1116. });
  1117. }
  1118. /** @fn signOutIfTokenIsInvalidWithError:
  1119. @brief Signs out this user if the user or the token is invalid.
  1120. @param error The error from the server.
  1121. */
  1122. - (void)signOutIfTokenIsInvalidWithError:(nullable NSError *)error {
  1123. NSInteger errorCode = error.code;
  1124. if (errorCode == FIRAuthErrorCodeUserNotFound ||
  1125. errorCode == FIRAuthErrorCodeUserDisabled ||
  1126. errorCode == FIRAuthErrorCodeInvalidUserToken ||
  1127. errorCode == FIRAuthErrorCodeUserTokenExpired) {
  1128. FIRLogNotice(kFIRLoggerAuth, @"I-AUT000016",
  1129. @"Invalid user token detected, user is automatically signed out.");
  1130. [_auth signOutByForceWithUserID:_userID error:NULL];
  1131. }
  1132. }
  1133. @end
  1134. @implementation FIRUserProfileChangeRequest {
  1135. /** @var _user
  1136. @brief The user associated with the change request.
  1137. */
  1138. FIRUser *_user;
  1139. /** @var _displayName
  1140. @brief The display name value to set if @c _displayNameSet is YES.
  1141. */
  1142. NSString *_displayName;
  1143. /** @var _displayNameSet
  1144. @brief Indicates the display name should be part of the change request.
  1145. */
  1146. BOOL _displayNameSet;
  1147. /** @var _photoURL
  1148. @brief The photo URL value to set if @c _displayNameSet is YES.
  1149. */
  1150. NSURL *_photoURL;
  1151. /** @var _photoURLSet
  1152. @brief Indicates the photo URL should be part of the change request.
  1153. */
  1154. BOOL _photoURLSet;
  1155. /** @var _consumed
  1156. @brief Indicates the @c commitChangesWithCallback: method has already been invoked.
  1157. */
  1158. BOOL _consumed;
  1159. }
  1160. - (nullable instancetype)initWithUser:(FIRUser *)user {
  1161. self = [super init];
  1162. if (self) {
  1163. _user = user;
  1164. }
  1165. return self;
  1166. }
  1167. - (nullable NSString *)displayName {
  1168. return _displayName;
  1169. }
  1170. - (void)setDisplayName:(nullable NSString *)displayName {
  1171. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1172. if (self->_consumed) {
  1173. [NSException raise:NSInternalInconsistencyException
  1174. format:@"%@",
  1175. @"Invalid call to setDisplayName: after commitChangesWithCallback:."];
  1176. return;
  1177. }
  1178. self->_displayNameSet = YES;
  1179. self->_displayName = [displayName copy];
  1180. });
  1181. }
  1182. - (nullable NSURL *)photoURL {
  1183. return _photoURL;
  1184. }
  1185. - (void)setPhotoURL:(nullable NSURL *)photoURL {
  1186. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1187. if (self->_consumed) {
  1188. [NSException raise:NSInternalInconsistencyException
  1189. format:@"%@",
  1190. @"Invalid call to setPhotoURL: after commitChangesWithCallback:."];
  1191. return;
  1192. }
  1193. self->_photoURLSet = YES;
  1194. self->_photoURL = [photoURL copy];
  1195. });
  1196. }
  1197. /** @fn hasUpdates
  1198. @brief Indicates at least one field has a value which needs to be committed.
  1199. */
  1200. - (BOOL)hasUpdates {
  1201. return _displayNameSet || _photoURLSet;
  1202. }
  1203. - (void)commitChangesWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1204. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1205. if (self->_consumed) {
  1206. [NSException raise:NSInternalInconsistencyException
  1207. format:@"%@",
  1208. @"commitChangesWithCallback: should only be called once."];
  1209. return;
  1210. }
  1211. self->_consumed = YES;
  1212. // Return fast if there is nothing to update:
  1213. if (![self hasUpdates]) {
  1214. callInMainThreadWithError(completion, nil);
  1215. return;
  1216. }
  1217. NSString *displayName = [self->_displayName copy];
  1218. BOOL displayNameWasSet = self->_displayNameSet;
  1219. NSURL *photoURL = [self->_photoURL copy];
  1220. BOOL photoURLWasSet = self->_photoURLSet;
  1221. [self->_user executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user,
  1222. FIRSetAccountInfoRequest *request) {
  1223. if (photoURLWasSet) {
  1224. request.photoURL = photoURL;
  1225. }
  1226. if (displayNameWasSet) {
  1227. request.displayName = displayName;
  1228. }
  1229. }
  1230. callback:^(NSError *_Nullable error) {
  1231. if (error) {
  1232. callInMainThreadWithError(completion, error);
  1233. return;
  1234. }
  1235. if (displayNameWasSet) {
  1236. [self->_user setDisplayName:displayName];
  1237. }
  1238. if (photoURLWasSet) {
  1239. [self->_user setPhotoURL:photoURL];
  1240. }
  1241. if (![self->_user updateKeychain:&error]) {
  1242. callInMainThreadWithError(completion, error);
  1243. return;
  1244. }
  1245. callInMainThreadWithError(completion, nil);
  1246. }];
  1247. });
  1248. }
  1249. @end
  1250. NS_ASSUME_NONNULL_END