FIRUser.m 63 KB

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