FIRUser.m 73 KB

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