No Description

FIRUser.m 63KB

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