FIRUser.m 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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. NSMutableString *tokenPayload = [[NSMutableString alloc] initWithString:tokenStringArray[1]];
  762. // Pad the token payload with "=" signs if the payload's length is not a multple of 4.
  763. int remainder = tokenPayload.length % 4 != 0;
  764. if (remainder) {
  765. while (remainder --) {
  766. [tokenPayload appendString:@"="];
  767. }
  768. }
  769. NSData *decodedTokenPayloadData =
  770. [[NSData alloc] initWithBase64EncodedString:tokenPayload
  771. options:NSDataBase64DecodingIgnoreUnknownCharacters];
  772. NSDictionary *tokenPayloadDictionary =
  773. [NSJSONSerialization JSONObjectWithData:decodedTokenPayloadData
  774. options:kNilOptions
  775. error:error];
  776. if (error) {
  777. return nil;
  778. }
  779. NSDate *expDate =
  780. [NSDate dateWithTimeIntervalSinceNow:[tokenPayloadDictionary[@"exp"] doubleValue]];
  781. NSDate *authDate =
  782. [NSDate dateWithTimeIntervalSinceNow:[tokenPayloadDictionary[@"auth_time"] doubleValue]];
  783. NSDate *issuedDate =
  784. [NSDate dateWithTimeIntervalSinceNow:[tokenPayloadDictionary[@"iat"] doubleValue]];
  785. FIRAuthTokenResult *result =
  786. [[FIRAuthTokenResult alloc] initWithToken:token
  787. expirationDate:expDate
  788. authDate:authDate
  789. issuedAtDate:issuedDate
  790. signInProvider:tokenPayloadDictionary[@"sign_in_provider"]
  791. claims:tokenPayloadDictionary];
  792. return result;
  793. }
  794. - (void)getTokenForcingRefresh:(BOOL)forceRefresh
  795. completion:(nullable FIRAuthTokenCallback)completion {
  796. [self getIDTokenForcingRefresh:forceRefresh completion:completion];
  797. }
  798. /** @fn internalGetTokenForcingRefresh:callback:
  799. @brief Retrieves the Firebase authentication token, possibly refreshing it if it has expired.
  800. @param callback The block to invoke when the token is available. Invoked asynchronously on the
  801. global work thread in the future.
  802. */
  803. - (void)internalGetTokenWithCallback:(nonnull FIRAuthTokenCallback)callback {
  804. [self internalGetTokenForcingRefresh:NO callback:callback];
  805. }
  806. - (void)internalGetTokenForcingRefresh:(BOOL)forceRefresh
  807. callback:(nonnull FIRAuthTokenCallback)callback {
  808. [_tokenService fetchAccessTokenForcingRefresh:forceRefresh
  809. callback:^(NSString *_Nullable token,
  810. NSError *_Nullable error,
  811. BOOL tokenUpdated) {
  812. if (error) {
  813. [self signOutIfTokenIsInvalidWithError:error];
  814. callback(nil, error);
  815. return;
  816. }
  817. if (tokenUpdated) {
  818. if (![self updateKeychain:&error]) {
  819. callback(nil, error);
  820. return;
  821. }
  822. }
  823. callback(token, nil);
  824. }];
  825. }
  826. - (void)linkWithCredential:(FIRAuthCredential *)credential
  827. completion:(nullable FIRAuthResultCallback)completion {
  828. FIRAuthDataResultCallback callback = ^(FIRAuthDataResult *_Nullable authResult,
  829. NSError *_Nullable error) {
  830. completion(authResult.user, error);
  831. };
  832. [self linkAndRetrieveDataWithCredential:credential completion:callback];
  833. }
  834. - (void)linkAndRetrieveDataWithCredential:(FIRAuthCredential *)credential
  835. completion:(nullable FIRAuthDataResultCallback)completion {
  836. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  837. if (self->_providerData[credential.provider]) {
  838. callInMainThreadWithAuthDataResultAndError(completion,
  839. nil,
  840. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  841. return;
  842. }
  843. FIRAuthDataResult *result =
  844. [[FIRAuthDataResult alloc] initWithUser:self additionalUserInfo:nil];
  845. if ([credential isKindOfClass:[FIREmailPasswordAuthCredential class]]) {
  846. if (self->_hasEmailPasswordCredential) {
  847. callInMainThreadWithAuthDataResultAndError(completion,
  848. nil,
  849. [FIRAuthErrorUtils providerAlreadyLinkedError]);
  850. return;
  851. }
  852. FIREmailPasswordAuthCredential *emailPasswordCredential =
  853. (FIREmailPasswordAuthCredential *)credential;
  854. [self updateEmail:emailPasswordCredential.email
  855. password:emailPasswordCredential.password
  856. callback:^(NSError *error) {
  857. if (error) {
  858. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  859. } else {
  860. callInMainThreadWithAuthDataResultAndError(completion, result, nil);
  861. }
  862. }];
  863. return;
  864. }
  865. #if TARGET_OS_IOS
  866. if ([credential isKindOfClass:[FIRPhoneAuthCredential class]]) {
  867. FIRPhoneAuthCredential *phoneAuthCredential = (FIRPhoneAuthCredential *)credential;
  868. [self internalUpdateOrLinkPhoneNumberCredential:phoneAuthCredential
  869. isLinkOperation:YES
  870. completion:^(NSError *_Nullable error) {
  871. if (error){
  872. callInMainThreadWithAuthDataResultAndError(completion, nil, error);
  873. } else {
  874. callInMainThreadWithAuthDataResultAndError(completion, result, nil);
  875. }
  876. }];
  877. return;
  878. }
  879. #endif
  880. [self->_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  881. CallbackWithAuthDataResultAndError completeWithError =
  882. ^(FIRAuthDataResult *result, NSError *error) {
  883. complete();
  884. callInMainThreadWithAuthDataResultAndError(completion, result, error);
  885. };
  886. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  887. NSError *_Nullable error) {
  888. if (error) {
  889. completeWithError(nil, error);
  890. return;
  891. }
  892. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  893. FIRVerifyAssertionRequest *request =
  894. [[FIRVerifyAssertionRequest alloc] initWithProviderID:credential.provider
  895. requestConfiguration:requestConfiguration];
  896. [credential prepareVerifyAssertionRequest:request];
  897. request.accessToken = accessToken;
  898. [FIRAuthBackend verifyAssertion:request
  899. callback:^(FIRVerifyAssertionResponse *response, NSError *error) {
  900. if (error) {
  901. [self signOutIfTokenIsInvalidWithError:error];
  902. completeWithError(nil, error);
  903. return;
  904. }
  905. FIRAdditionalUserInfo *additionalUserInfo =
  906. [FIRAdditionalUserInfo userInfoWithVerifyAssertionResponse:response];
  907. FIRAuthDataResult *result =
  908. [[FIRAuthDataResult alloc] initWithUser:self additionalUserInfo:additionalUserInfo];
  909. // Update the new token and refresh user info again.
  910. self->_tokenService = [[FIRSecureTokenService alloc]
  911. initWithRequestConfiguration:requestConfiguration
  912. accessToken:response.IDToken
  913. accessTokenExpirationDate:response.approximateExpirationDate
  914. refreshToken:response.refreshToken];
  915. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  916. NSError *_Nullable error) {
  917. if (error) {
  918. completeWithError(nil, error);
  919. return;
  920. }
  921. FIRGetAccountInfoRequest *getAccountInfoRequest =
  922. [[FIRGetAccountInfoRequest alloc] initWithAccessToken:accessToken
  923. requestConfiguration:requestConfiguration];
  924. [FIRAuthBackend getAccountInfo:getAccountInfoRequest
  925. callback:^(FIRGetAccountInfoResponse *_Nullable response,
  926. NSError *_Nullable error) {
  927. if (error) {
  928. [self signOutIfTokenIsInvalidWithError:error];
  929. completeWithError(nil, error);
  930. return;
  931. }
  932. self->_anonymous = NO;
  933. [self updateWithGetAccountInfoResponse:response];
  934. if (![self updateKeychain:&error]) {
  935. completeWithError(nil, error);
  936. return;
  937. }
  938. completeWithError(result, nil);
  939. }];
  940. }];
  941. }];
  942. }];
  943. }];
  944. });
  945. }
  946. - (void)unlinkFromProvider:(NSString *)provider
  947. completion:(nullable FIRAuthResultCallback)completion {
  948. [_taskQueue enqueueTask:^(FIRAuthSerialTaskCompletionBlock _Nonnull complete) {
  949. CallbackWithError completeAndCallbackWithError = ^(NSError *error) {
  950. complete();
  951. callInMainThreadWithUserAndError(completion, self, error);
  952. };
  953. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  954. NSError *_Nullable error) {
  955. if (error) {
  956. completeAndCallbackWithError(error);
  957. return;
  958. }
  959. FIRAuthRequestConfiguration *requestConfiguration = self->_auth.requestConfiguration;
  960. FIRSetAccountInfoRequest *setAccountInfoRequest =
  961. [[FIRSetAccountInfoRequest alloc] initWithRequestConfiguration:requestConfiguration];
  962. setAccountInfoRequest.accessToken = accessToken;
  963. BOOL isEmailPasswordProvider = [provider isEqualToString:FIREmailAuthProviderID];
  964. if (isEmailPasswordProvider) {
  965. if (!self->_hasEmailPasswordCredential) {
  966. completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]);
  967. return;
  968. }
  969. setAccountInfoRequest.deleteAttributes = @[ FIRSetAccountInfoUserAttributePassword ];
  970. } else {
  971. if (!self->_providerData[provider]) {
  972. completeAndCallbackWithError([FIRAuthErrorUtils noSuchProviderError]);
  973. return;
  974. }
  975. setAccountInfoRequest.deleteProviders = @[ provider ];
  976. }
  977. [FIRAuthBackend setAccountInfo:setAccountInfoRequest
  978. callback:^(FIRSetAccountInfoResponse *_Nullable response,
  979. NSError *_Nullable error) {
  980. if (error) {
  981. [self signOutIfTokenIsInvalidWithError:error];
  982. completeAndCallbackWithError(error);
  983. return;
  984. }
  985. if (isEmailPasswordProvider) {
  986. self->_hasEmailPasswordCredential = NO;
  987. } else {
  988. // We can't just use the provider info objects in FIRSetAcccountInfoResponse because they
  989. // don't have localID and email fields. Remove the specific provider manually.
  990. NSMutableDictionary *mutableProviderData = [self->_providerData mutableCopy];
  991. [mutableProviderData removeObjectForKey:provider];
  992. self->_providerData = [mutableProviderData copy];
  993. #if TARGET_OS_IOS
  994. // After successfully unlinking a phone auth provider, remove the phone number from the
  995. // cached user info.
  996. if ([provider isEqualToString:FIRPhoneAuthProviderID]) {
  997. self->_phoneNumber = nil;
  998. }
  999. #endif
  1000. }
  1001. if (response.IDToken && response.refreshToken) {
  1002. FIRSecureTokenService *tokenService = [[FIRSecureTokenService alloc]
  1003. initWithRequestConfiguration:requestConfiguration
  1004. accessToken:response.IDToken
  1005. accessTokenExpirationDate:response.approximateExpirationDate
  1006. refreshToken:response.refreshToken];
  1007. [self setTokenService:tokenService callback:^(NSError *_Nullable error) {
  1008. completeAndCallbackWithError(error);
  1009. }];
  1010. return;
  1011. }
  1012. if (![self updateKeychain:&error]) {
  1013. completeAndCallbackWithError(error);
  1014. return;
  1015. }
  1016. completeAndCallbackWithError(nil);
  1017. }];
  1018. }];
  1019. }];
  1020. }
  1021. - (void)sendEmailVerificationWithCompletion:(nullable FIRSendEmailVerificationCallback)completion {
  1022. [self sendEmailVerificationWithNullableActionCodeSettings:nil completion:completion];
  1023. }
  1024. - (void)sendEmailVerificationWithActionCodeSettings:(FIRActionCodeSettings *)actionCodeSettings
  1025. completion:(nullable FIRSendEmailVerificationCallback)
  1026. completion {
  1027. [self sendEmailVerificationWithNullableActionCodeSettings:actionCodeSettings
  1028. completion:completion];
  1029. }
  1030. /** @fn sendEmailVerificationWithNullableActionCodeSettings:completion:
  1031. @brief Initiates email verification for the user.
  1032. @param actionCodeSettings Optionally, a @c FIRActionCodeSettings object containing settings
  1033. related to the handling action codes.
  1034. */
  1035. - (void)sendEmailVerificationWithNullableActionCodeSettings:(nullable FIRActionCodeSettings *)
  1036. actionCodeSettings
  1037. completion:
  1038. (nullable FIRSendEmailVerificationCallback)
  1039. completion {
  1040. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1041. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1042. NSError *_Nullable error) {
  1043. if (error) {
  1044. callInMainThreadWithError(completion, error);
  1045. return;
  1046. }
  1047. FIRAuthRequestConfiguration *configuration = self->_auth.requestConfiguration;
  1048. FIRGetOOBConfirmationCodeRequest *request =
  1049. [FIRGetOOBConfirmationCodeRequest verifyEmailRequestWithAccessToken:accessToken
  1050. actionCodeSettings:actionCodeSettings
  1051. requestConfiguration:configuration];
  1052. [FIRAuthBackend getOOBConfirmationCode:request
  1053. callback:^(FIRGetOOBConfirmationCodeResponse *_Nullable
  1054. response,
  1055. NSError *_Nullable error) {
  1056. [self signOutIfTokenIsInvalidWithError:error];
  1057. callInMainThreadWithError(completion, error);
  1058. }];
  1059. }];
  1060. });
  1061. }
  1062. - (void)deleteWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1063. dispatch_async(FIRAuthGlobalWorkQueue(), ^{
  1064. [self internalGetTokenWithCallback:^(NSString *_Nullable accessToken,
  1065. NSError *_Nullable error) {
  1066. if (error) {
  1067. callInMainThreadWithError(completion, error);
  1068. return;
  1069. }
  1070. FIRDeleteAccountRequest *deleteUserRequest =
  1071. [[FIRDeleteAccountRequest alloc] initWitLocalID:self->_userID
  1072. accessToken:accessToken
  1073. requestConfiguration:self->_auth.requestConfiguration];
  1074. [FIRAuthBackend deleteAccount:deleteUserRequest callback:^(NSError *_Nullable error) {
  1075. if (error) {
  1076. callInMainThreadWithError(completion, error);
  1077. return;
  1078. }
  1079. if (![self->_auth signOutByForceWithUserID:self->_userID error:&error]) {
  1080. callInMainThreadWithError(completion, error);
  1081. return;
  1082. }
  1083. callInMainThreadWithError(completion, error);
  1084. }];
  1085. }];
  1086. });
  1087. }
  1088. /** @fn signOutIfTokenIsInvalidWithError:
  1089. @brief Signs out this user if the user or the token is invalid.
  1090. @param error The error from the server.
  1091. */
  1092. - (void)signOutIfTokenIsInvalidWithError:(nullable NSError *)error {
  1093. NSInteger errorCode = error.code;
  1094. if (errorCode == FIRAuthErrorCodeUserNotFound ||
  1095. errorCode == FIRAuthErrorCodeUserDisabled ||
  1096. errorCode == FIRAuthErrorCodeInvalidUserToken ||
  1097. errorCode == FIRAuthErrorCodeUserTokenExpired) {
  1098. FIRLogNotice(kFIRLoggerAuth, @"I-AUT000016",
  1099. @"Invalid user token detected, user is automatically signed out.");
  1100. [_auth signOutByForceWithUserID:_userID error:NULL];
  1101. }
  1102. }
  1103. @end
  1104. @implementation FIRUserProfileChangeRequest {
  1105. /** @var _user
  1106. @brief The user associated with the change request.
  1107. */
  1108. FIRUser *_user;
  1109. /** @var _displayName
  1110. @brief The display name value to set if @c _displayNameSet is YES.
  1111. */
  1112. NSString *_displayName;
  1113. /** @var _displayNameSet
  1114. @brief Indicates the display name should be part of the change request.
  1115. */
  1116. BOOL _displayNameSet;
  1117. /** @var _photoURL
  1118. @brief The photo URL value to set if @c _displayNameSet is YES.
  1119. */
  1120. NSURL *_photoURL;
  1121. /** @var _photoURLSet
  1122. @brief Indicates the photo URL should be part of the change request.
  1123. */
  1124. BOOL _photoURLSet;
  1125. /** @var _consumed
  1126. @brief Indicates the @c commitChangesWithCallback: method has already been invoked.
  1127. */
  1128. BOOL _consumed;
  1129. }
  1130. - (nullable instancetype)initWithUser:(FIRUser *)user {
  1131. self = [super init];
  1132. if (self) {
  1133. _user = user;
  1134. }
  1135. return self;
  1136. }
  1137. - (nullable NSString *)displayName {
  1138. return _displayName;
  1139. }
  1140. - (void)setDisplayName:(nullable NSString *)displayName {
  1141. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1142. if (self->_consumed) {
  1143. [NSException raise:NSInternalInconsistencyException
  1144. format:@"%@",
  1145. @"Invalid call to setDisplayName: after commitChangesWithCallback:."];
  1146. return;
  1147. }
  1148. self->_displayNameSet = YES;
  1149. self->_displayName = [displayName copy];
  1150. });
  1151. }
  1152. - (nullable NSURL *)photoURL {
  1153. return _photoURL;
  1154. }
  1155. - (void)setPhotoURL:(nullable NSURL *)photoURL {
  1156. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1157. if (self->_consumed) {
  1158. [NSException raise:NSInternalInconsistencyException
  1159. format:@"%@",
  1160. @"Invalid call to setPhotoURL: after commitChangesWithCallback:."];
  1161. return;
  1162. }
  1163. self->_photoURLSet = YES;
  1164. self->_photoURL = [photoURL copy];
  1165. });
  1166. }
  1167. /** @fn hasUpdates
  1168. @brief Indicates at least one field has a value which needs to be committed.
  1169. */
  1170. - (BOOL)hasUpdates {
  1171. return _displayNameSet || _photoURLSet;
  1172. }
  1173. - (void)commitChangesWithCompletion:(nullable FIRUserProfileChangeCallback)completion {
  1174. dispatch_sync(FIRAuthGlobalWorkQueue(), ^{
  1175. if (self->_consumed) {
  1176. [NSException raise:NSInternalInconsistencyException
  1177. format:@"%@",
  1178. @"commitChangesWithCallback: should only be called once."];
  1179. return;
  1180. }
  1181. self->_consumed = YES;
  1182. // Return fast if there is nothing to update:
  1183. if (![self hasUpdates]) {
  1184. callInMainThreadWithError(completion, nil);
  1185. return;
  1186. }
  1187. NSString *displayName = [self->_displayName copy];
  1188. BOOL displayNameWasSet = self->_displayNameSet;
  1189. NSURL *photoURL = [self->_photoURL copy];
  1190. BOOL photoURLWasSet = self->_photoURLSet;
  1191. [self->_user executeUserUpdateWithChanges:^(FIRGetAccountInfoResponseUser *user,
  1192. FIRSetAccountInfoRequest *request) {
  1193. if (photoURLWasSet) {
  1194. request.photoURL = photoURL;
  1195. }
  1196. if (displayNameWasSet) {
  1197. request.displayName = displayName;
  1198. }
  1199. }
  1200. callback:^(NSError *_Nullable error) {
  1201. if (error) {
  1202. callInMainThreadWithError(completion, error);
  1203. return;
  1204. }
  1205. if (displayNameWasSet) {
  1206. [self->_user setDisplayName:displayName];
  1207. }
  1208. if (photoURLWasSet) {
  1209. [self->_user setPhotoURL:photoURL];
  1210. }
  1211. if (![self->_user updateKeychain:&error]) {
  1212. callInMainThreadWithError(completion, error);
  1213. return;
  1214. }
  1215. callInMainThreadWithError(completion, nil);
  1216. }];
  1217. });
  1218. }
  1219. @end
  1220. NS_ASSUME_NONNULL_END