FIRUser.m 54 KB

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