Açıklama Yok

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