FIRUser.m 57 KB

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