ParseUser.js 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = void 0;
  6. var _CoreManager = _interopRequireDefault(require("./CoreManager"));
  7. var _isRevocableSession = _interopRequireDefault(require("./isRevocableSession"));
  8. var _ParseError = _interopRequireDefault(require("./ParseError"));
  9. var _ParseObject = _interopRequireDefault(require("./ParseObject"));
  10. var _Storage = _interopRequireDefault(require("./Storage"));
  11. function _interopRequireDefault(e) {
  12. return e && e.__esModule ? e : {
  13. default: e
  14. };
  15. }
  16. const CURRENT_USER_KEY = 'currentUser';
  17. let canUseCurrentUser = !_CoreManager.default.get('IS_NODE');
  18. let currentUserCacheMatchesDisk = false;
  19. let currentUserCache = null;
  20. const authProviders = {};
  21. /**
  22. * <p>A Parse.User object is a local representation of a user persisted to the
  23. * Parse cloud. This class is a subclass of a Parse.Object, and retains the
  24. * same functionality of a Parse.Object, but also extends it with various
  25. * user specific methods, like authentication, signing up, and validation of
  26. * uniqueness.</p>
  27. *
  28. * @alias Parse.User
  29. * @augments Parse.Object
  30. */
  31. class ParseUser extends _ParseObject.default {
  32. /**
  33. * @param {object} attributes The initial set of data to store in the user.
  34. */
  35. constructor(attributes) {
  36. super('_User');
  37. if (attributes && typeof attributes === 'object') {
  38. if (!this.set(attributes || {})) {
  39. throw new Error("Can't create an invalid Parse User");
  40. }
  41. }
  42. }
  43. /**
  44. * Request a revocable session token to replace the older style of token.
  45. *
  46. * @param {object} options
  47. * @returns {Promise} A promise that is resolved when the replacement
  48. * token has been fetched.
  49. */
  50. _upgradeToRevocableSession(options) {
  51. options = options || {};
  52. const upgradeOptions = {};
  53. if (options.hasOwnProperty('useMasterKey')) {
  54. upgradeOptions.useMasterKey = options.useMasterKey;
  55. }
  56. const controller = _CoreManager.default.getUserController();
  57. return controller.upgradeToRevocableSession(this, upgradeOptions);
  58. }
  59. /**
  60. * Parse allows you to link your users with {@link https://docs.parseplatform.org/parse-server/guide/#oauth-and-3rd-party-authentication 3rd party authentication}, enabling
  61. * your users to sign up or log into your application using their existing identities.
  62. * Since 2.9.0
  63. *
  64. * @see {@link https://docs.parseplatform.org/js/guide/#linking-users Linking Users}
  65. * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider}
  66. * @param {object} options
  67. * @param {object} [options.authData] AuthData to link with
  68. * <ul>
  69. * <li>If provider is string, options is {@link http://docs.parseplatform.org/parse-server/guide/#supported-3rd-party-authentications authData}
  70. * <li>If provider is AuthProvider, options is saveOpts
  71. * </ul>
  72. * @param {object} saveOpts useMasterKey / sessionToken
  73. * @returns {Promise} A promise that is fulfilled with the user is linked
  74. */
  75. linkWith(provider, options, saveOpts = {}) {
  76. saveOpts.sessionToken = saveOpts.sessionToken || this.getSessionToken() || '';
  77. let authType;
  78. if (typeof provider === 'string') {
  79. authType = provider;
  80. if (authProviders[provider]) {
  81. provider = authProviders[provider];
  82. } else {
  83. const authProvider = {
  84. restoreAuthentication() {
  85. return true;
  86. },
  87. getAuthType() {
  88. return authType;
  89. }
  90. };
  91. authProviders[authProvider.getAuthType()] = authProvider;
  92. provider = authProvider;
  93. }
  94. } else {
  95. authType = provider.getAuthType();
  96. }
  97. if (options && options.hasOwnProperty('authData')) {
  98. const authData = this.get('authData') || {};
  99. if (typeof authData !== 'object') {
  100. throw new Error('Invalid type: authData field should be an object');
  101. }
  102. authData[authType] = options.authData;
  103. const oldAnonymousData = authData.anonymous;
  104. this.stripAnonymity();
  105. const controller = _CoreManager.default.getUserController();
  106. return controller.linkWith(this, authData, saveOpts).catch(e => {
  107. delete authData[authType];
  108. this.restoreAnonimity(oldAnonymousData);
  109. throw e;
  110. });
  111. } else {
  112. return new Promise((resolve, reject) => {
  113. provider.authenticate({
  114. success: (provider, result) => {
  115. const opts = {};
  116. opts.authData = result;
  117. this.linkWith(provider, opts, saveOpts).then(() => {
  118. resolve(this);
  119. }, error => {
  120. reject(error);
  121. });
  122. },
  123. error: (provider, error) => {
  124. reject(error);
  125. }
  126. });
  127. });
  128. }
  129. }
  130. /**
  131. * @param provider
  132. * @param options
  133. * @param {object} [options.authData]
  134. * @param saveOpts
  135. * @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith}
  136. * @returns {Promise}
  137. */
  138. _linkWith(provider, options, saveOpts = {}) {
  139. return this.linkWith(provider, options, saveOpts);
  140. }
  141. /**
  142. * Synchronizes auth data for a provider (e.g. puts the access token in the
  143. * right place to be used by the Facebook SDK).
  144. *
  145. * @param provider
  146. */
  147. _synchronizeAuthData(provider) {
  148. if (!this.isCurrent() || !provider) {
  149. return;
  150. }
  151. let authType;
  152. if (typeof provider === 'string') {
  153. authType = provider;
  154. provider = authProviders[authType];
  155. } else {
  156. authType = provider.getAuthType();
  157. }
  158. const authData = this.get('authData');
  159. if (!provider || !authData || typeof authData !== 'object') {
  160. return;
  161. }
  162. const success = provider.restoreAuthentication(authData[authType]);
  163. if (!success) {
  164. this._unlinkFrom(provider);
  165. }
  166. }
  167. /**
  168. * Synchronizes authData for all providers.
  169. */
  170. _synchronizeAllAuthData() {
  171. const authData = this.get('authData');
  172. if (typeof authData !== 'object') {
  173. return;
  174. }
  175. for (const key in authData) {
  176. this._synchronizeAuthData(key);
  177. }
  178. }
  179. /**
  180. * Removes null values from authData (which exist temporarily for unlinking)
  181. */
  182. _cleanupAuthData() {
  183. if (!this.isCurrent()) {
  184. return;
  185. }
  186. const authData = this.get('authData');
  187. if (typeof authData !== 'object') {
  188. return;
  189. }
  190. for (const key in authData) {
  191. if (!authData[key]) {
  192. delete authData[key];
  193. }
  194. }
  195. }
  196. /**
  197. * Unlinks a user from a service.
  198. *
  199. * @param {string | AuthProvider} provider Name of auth provider or {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider}
  200. * @param {object} options MasterKey / SessionToken
  201. * @returns {Promise} A promise that is fulfilled when the unlinking
  202. * finishes.
  203. */
  204. _unlinkFrom(provider, options) {
  205. return this.linkWith(provider, {
  206. authData: null
  207. }, options).then(() => {
  208. this._synchronizeAuthData(provider);
  209. return Promise.resolve(this);
  210. });
  211. }
  212. /**
  213. * Checks whether a user is linked to a service.
  214. *
  215. * @param {object} provider service to link to
  216. * @returns {boolean} true if link was successful
  217. */
  218. _isLinked(provider) {
  219. let authType;
  220. if (typeof provider === 'string') {
  221. authType = provider;
  222. } else {
  223. authType = provider.getAuthType();
  224. }
  225. const authData = this.get('authData') || {};
  226. if (typeof authData !== 'object') {
  227. return false;
  228. }
  229. return !!authData[authType];
  230. }
  231. /**
  232. * Deauthenticates all providers.
  233. */
  234. _logOutWithAll() {
  235. const authData = this.get('authData');
  236. if (typeof authData !== 'object') {
  237. return;
  238. }
  239. for (const key in authData) {
  240. this._logOutWith(key);
  241. }
  242. }
  243. /**
  244. * Deauthenticates a single provider (e.g. removing access tokens from the
  245. * Facebook SDK).
  246. *
  247. * @param {object} provider service to logout of
  248. */
  249. _logOutWith(provider) {
  250. if (!this.isCurrent()) {
  251. return;
  252. }
  253. if (typeof provider === 'string') {
  254. provider = authProviders[provider];
  255. }
  256. if (provider && provider.deauthenticate) {
  257. provider.deauthenticate();
  258. }
  259. }
  260. /**
  261. * Class instance method used to maintain specific keys when a fetch occurs.
  262. * Used to ensure that the session token is not lost.
  263. *
  264. * @returns {object} sessionToken
  265. */
  266. _preserveFieldsOnFetch() {
  267. return {
  268. sessionToken: this.get('sessionToken')
  269. };
  270. }
  271. /**
  272. * Returns true if <code>current</code> would return this user.
  273. *
  274. * @returns {boolean} true if user is cached on disk
  275. */
  276. isCurrent() {
  277. const current = ParseUser.current();
  278. return !!current && current.id === this.id;
  279. }
  280. /**
  281. * Returns true if <code>current</code> would return this user.
  282. *
  283. * @returns {Promise<boolean>} true if user is cached on disk
  284. */
  285. async isCurrentAsync() {
  286. const current = await ParseUser.currentAsync();
  287. return !!current && current.id === this.id;
  288. }
  289. stripAnonymity() {
  290. const authData = this.get('authData');
  291. if (authData && typeof authData === 'object' && authData.hasOwnProperty('anonymous')) {
  292. // We need to set anonymous to null instead of deleting it in order to remove it from Parse.
  293. authData.anonymous = null;
  294. }
  295. }
  296. restoreAnonimity(anonymousData) {
  297. if (anonymousData) {
  298. const authData = this.get('authData');
  299. authData.anonymous = anonymousData;
  300. }
  301. }
  302. /**
  303. * Returns get("username").
  304. *
  305. * @returns {string}
  306. */
  307. getUsername() {
  308. const username = this.get('username');
  309. if (username == null || typeof username === 'string') {
  310. return username;
  311. }
  312. return '';
  313. }
  314. /**
  315. * Calls set("username", username, options) and returns the result.
  316. *
  317. * @param {string} username
  318. */
  319. setUsername(username) {
  320. this.stripAnonymity();
  321. this.set('username', username);
  322. }
  323. /**
  324. * Calls set("password", password, options) and returns the result.
  325. *
  326. * @param {string} password User's Password
  327. */
  328. setPassword(password) {
  329. this.set('password', password);
  330. }
  331. /**
  332. * Returns get("email").
  333. *
  334. * @returns {string} User's Email
  335. */
  336. getEmail() {
  337. const email = this.get('email');
  338. if (email == null || typeof email === 'string') {
  339. return email;
  340. }
  341. return '';
  342. }
  343. /**
  344. * Calls set("email", email) and returns the result.
  345. *
  346. * @param {string} email
  347. * @returns {boolean}
  348. */
  349. setEmail(email) {
  350. return this.set('email', email);
  351. }
  352. /**
  353. * Returns the session token for this user, if the user has been logged in,
  354. * or if it is the result of a query with the master key. Otherwise, returns
  355. * undefined.
  356. *
  357. * @returns {string} the session token, or undefined
  358. */
  359. getSessionToken() {
  360. const token = this.get('sessionToken');
  361. if (token == null || typeof token === 'string') {
  362. return token;
  363. }
  364. return '';
  365. }
  366. /**
  367. * Checks whether this user is the current user and has been authenticated.
  368. *
  369. * @returns {boolean} whether this user is the current user and is logged in.
  370. */
  371. authenticated() {
  372. const current = ParseUser.current();
  373. return !!this.get('sessionToken') && !!current && current.id === this.id;
  374. }
  375. /**
  376. * Signs up a new user. You should call this instead of save for
  377. * new Parse.Users. This will create a new Parse.User on the server, and
  378. * also persist the session on disk so that you can access the user using
  379. * <code>current</code>.
  380. *
  381. * <p>A username and password must be set before calling signUp.</p>
  382. *
  383. * @param {object} attrs Extra fields to set on the new user, or null.
  384. * @param {object} options
  385. * @returns {Promise} A promise that is fulfilled when the signup
  386. * finishes.
  387. */
  388. signUp(attrs, options) {
  389. options = options || {};
  390. const signupOptions = {};
  391. if (options.hasOwnProperty('useMasterKey')) {
  392. signupOptions.useMasterKey = options.useMasterKey;
  393. }
  394. if (options.hasOwnProperty('installationId')) {
  395. signupOptions.installationId = options.installationId;
  396. }
  397. if (options.hasOwnProperty('context') && Object.prototype.toString.call(options.context) === '[object Object]') {
  398. signupOptions.context = options.context;
  399. }
  400. const controller = _CoreManager.default.getUserController();
  401. return controller.signUp(this, attrs, signupOptions);
  402. }
  403. /**
  404. * Logs in a Parse.User. On success, this saves the session to disk,
  405. * so you can retrieve the currently logged in user using
  406. * <code>current</code>.
  407. *
  408. * <p>A username and password must be set before calling logIn.</p>
  409. *
  410. * @param {object} options
  411. * @returns {Promise} A promise that is fulfilled with the user when
  412. * the login is complete.
  413. */
  414. logIn(options = {}) {
  415. options = options || {};
  416. const loginOptions = {
  417. usePost: true
  418. };
  419. if (options.hasOwnProperty('useMasterKey')) {
  420. loginOptions.useMasterKey = options.useMasterKey;
  421. }
  422. if (options.hasOwnProperty('installationId')) {
  423. loginOptions.installationId = options.installationId;
  424. }
  425. if (options.hasOwnProperty('usePost')) {
  426. loginOptions.usePost = options.usePost;
  427. }
  428. if (options.hasOwnProperty('context') && Object.prototype.toString.call(options.context) === '[object Object]') {
  429. loginOptions.context = options.context;
  430. }
  431. const controller = _CoreManager.default.getUserController();
  432. return controller.logIn(this, loginOptions);
  433. }
  434. /**
  435. * Wrap the default save behavior with functionality to save to local
  436. * storage if this is current user.
  437. *
  438. * @param {...any} args
  439. * @returns {Promise}
  440. */
  441. async save(...args) {
  442. await super.save.apply(this, args);
  443. const current = await this.isCurrentAsync();
  444. if (current) {
  445. return _CoreManager.default.getUserController().updateUserOnDisk(this);
  446. }
  447. return this;
  448. }
  449. /**
  450. * Wrap the default destroy behavior with functionality that logs out
  451. * the current user when it is destroyed
  452. *
  453. * @param {...any} args
  454. * @returns {Parse.User}
  455. */
  456. async destroy(...args) {
  457. await super.destroy.apply(this, args);
  458. const current = await this.isCurrentAsync();
  459. if (current) {
  460. return _CoreManager.default.getUserController().removeUserFromDisk();
  461. }
  462. return this;
  463. }
  464. /**
  465. * Wrap the default fetch behavior with functionality to save to local
  466. * storage if this is current user.
  467. *
  468. * @param {...any} args
  469. * @returns {Parse.User}
  470. */
  471. async fetch(...args) {
  472. await super.fetch.apply(this, args);
  473. const current = await this.isCurrentAsync();
  474. if (current) {
  475. return _CoreManager.default.getUserController().updateUserOnDisk(this);
  476. }
  477. return this;
  478. }
  479. /**
  480. * Wrap the default fetchWithInclude behavior with functionality to save to local
  481. * storage if this is current user.
  482. *
  483. * @param {...any} args
  484. * @returns {Parse.User}
  485. */
  486. async fetchWithInclude(...args) {
  487. await super.fetchWithInclude.apply(this, args);
  488. const current = await this.isCurrentAsync();
  489. if (current) {
  490. return _CoreManager.default.getUserController().updateUserOnDisk(this);
  491. }
  492. return this;
  493. }
  494. /**
  495. * Verify whether a given password is the password of the current user.
  496. *
  497. * @param {string} password The password to be verified.
  498. * @param {object} options The options.
  499. * @param {boolean} [options.ignoreEmailVerification] Set to `true` to bypass email verification and verify
  500. * the password regardless of whether the email has been verified. This requires the master key.
  501. * @returns {Promise} A promise that is fulfilled with a user when the password is correct.
  502. */
  503. verifyPassword(password, options) {
  504. const username = this.getUsername() || '';
  505. return ParseUser.verifyPassword(username, password, options);
  506. }
  507. static readOnlyAttributes() {
  508. return ['sessionToken'];
  509. }
  510. /**
  511. * Adds functionality to the existing Parse.User class.
  512. *
  513. * @param {object} protoProps A set of properties to add to the prototype
  514. * @param {object} classProps A set of static properties to add to the class
  515. * @static
  516. * @returns {Parse.User} The newly extended Parse.User class
  517. */
  518. static extend(protoProps, classProps) {
  519. if (protoProps) {
  520. for (const prop in protoProps) {
  521. if (prop !== 'className') {
  522. Object.defineProperty(ParseUser.prototype, prop, {
  523. value: protoProps[prop],
  524. enumerable: false,
  525. writable: true,
  526. configurable: true
  527. });
  528. }
  529. }
  530. }
  531. if (classProps) {
  532. for (const prop in classProps) {
  533. if (prop !== 'className') {
  534. Object.defineProperty(ParseUser, prop, {
  535. value: classProps[prop],
  536. enumerable: false,
  537. writable: true,
  538. configurable: true
  539. });
  540. }
  541. }
  542. }
  543. return ParseUser;
  544. }
  545. /**
  546. * Retrieves the currently logged in ParseUser with a valid session,
  547. * either from memory or localStorage, if necessary.
  548. *
  549. * @static
  550. * @returns {Parse.Object} The currently logged in Parse.User.
  551. */
  552. static current() {
  553. if (!canUseCurrentUser) {
  554. return null;
  555. }
  556. const controller = _CoreManager.default.getUserController();
  557. return controller.currentUser();
  558. }
  559. /**
  560. * Retrieves the currently logged in ParseUser from asynchronous Storage.
  561. *
  562. * @static
  563. * @returns {Promise} A Promise that is resolved with the currently
  564. * logged in Parse User
  565. */
  566. static currentAsync() {
  567. if (!canUseCurrentUser) {
  568. return Promise.resolve(null);
  569. }
  570. const controller = _CoreManager.default.getUserController();
  571. return controller.currentUserAsync();
  572. }
  573. /**
  574. * Signs up a new user with a username (or email) and password.
  575. * This will create a new Parse.User on the server, and also persist the
  576. * session in localStorage so that you can access the user using
  577. * {@link #current}.
  578. *
  579. * @param {string} username The username (or email) to sign up with.
  580. * @param {string} password The password to sign up with.
  581. * @param {object} attrs Extra fields to set on the new user.
  582. * @param {object} options
  583. * @static
  584. * @returns {Promise} A promise that is fulfilled with the user when
  585. * the signup completes.
  586. */
  587. static signUp(username, password, attrs, options) {
  588. attrs = attrs || {};
  589. attrs.username = username;
  590. attrs.password = password;
  591. const user = new this(attrs);
  592. return user.signUp({}, options);
  593. }
  594. /**
  595. * Logs in a user with a username (or email) and password. On success, this
  596. * saves the session to disk, so you can retrieve the currently logged in
  597. * user using <code>current</code>.
  598. *
  599. * @param {string} username The username (or email) to log in with.
  600. * @param {string} password The password to log in with.
  601. * @param {object} options
  602. * @static
  603. * @returns {Promise} A promise that is fulfilled with the user when
  604. * the login completes.
  605. */
  606. static logIn(username, password, options) {
  607. if (typeof username !== 'string') {
  608. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Username must be a string.'));
  609. } else if (typeof password !== 'string') {
  610. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Password must be a string.'));
  611. }
  612. const user = new this();
  613. user._finishFetch({
  614. username: username,
  615. password: password
  616. });
  617. return user.logIn(options);
  618. }
  619. /**
  620. * Logs in a user with a username (or email) and password, and authData. On success, this
  621. * saves the session to disk, so you can retrieve the currently logged in
  622. * user using <code>current</code>.
  623. *
  624. * @param {string} username The username (or email) to log in with.
  625. * @param {string} password The password to log in with.
  626. * @param {object} authData The authData to log in with.
  627. * @param {object} options
  628. * @static
  629. * @returns {Promise} A promise that is fulfilled with the user when
  630. * the login completes.
  631. */
  632. static logInWithAdditionalAuth(username, password, authData, options) {
  633. if (typeof username !== 'string') {
  634. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Username must be a string.'));
  635. }
  636. if (typeof password !== 'string') {
  637. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Password must be a string.'));
  638. }
  639. if (Object.prototype.toString.call(authData) !== '[object Object]') {
  640. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Auth must be an object.'));
  641. }
  642. const user = new this();
  643. user._finishFetch({
  644. username: username,
  645. password: password,
  646. authData
  647. });
  648. return user.logIn(options);
  649. }
  650. /**
  651. * Logs in a user with an objectId. On success, this saves the session
  652. * to disk, so you can retrieve the currently logged in user using
  653. * <code>current</code>.
  654. *
  655. * @param {string} userId The objectId for the user.
  656. * @static
  657. * @returns {Promise} A promise that is fulfilled with the user when
  658. * the login completes.
  659. */
  660. static loginAs(userId) {
  661. if (!userId) {
  662. throw new _ParseError.default(_ParseError.default.USERNAME_MISSING, 'Cannot log in as user with an empty user id');
  663. }
  664. const controller = _CoreManager.default.getUserController();
  665. const user = new this();
  666. return controller.loginAs(user, userId);
  667. }
  668. /**
  669. * Logs in a user with a session token. On success, this saves the session
  670. * to disk, so you can retrieve the currently logged in user using
  671. * <code>current</code>.
  672. *
  673. * @param {string} sessionToken The sessionToken to log in with.
  674. * @param {object} options
  675. * @static
  676. * @returns {Promise} A promise that is fulfilled with the user when
  677. * the login completes.
  678. */
  679. static become(sessionToken, options) {
  680. if (!canUseCurrentUser) {
  681. throw new Error('It is not memory-safe to become a user in a server environment');
  682. }
  683. options = options || {};
  684. const becomeOptions = {
  685. sessionToken: sessionToken
  686. };
  687. if (options.hasOwnProperty('useMasterKey')) {
  688. becomeOptions.useMasterKey = options.useMasterKey;
  689. }
  690. const controller = _CoreManager.default.getUserController();
  691. const user = new this();
  692. return controller.become(user, becomeOptions);
  693. }
  694. /**
  695. * Retrieves a user with a session token.
  696. *
  697. * @param {string} sessionToken The sessionToken to get user with.
  698. * @param {object} options
  699. * @static
  700. * @returns {Promise} A promise that is fulfilled with the user is fetched.
  701. */
  702. static me(sessionToken, options = {}) {
  703. const controller = _CoreManager.default.getUserController();
  704. const meOptions = {
  705. sessionToken: sessionToken
  706. };
  707. if (options.useMasterKey) {
  708. meOptions.useMasterKey = options.useMasterKey;
  709. }
  710. const user = new this();
  711. return controller.me(user, meOptions);
  712. }
  713. /**
  714. * Logs in a user with a session token. On success, this saves the session
  715. * to disk, so you can retrieve the currently logged in user using
  716. * <code>current</code>. If there is no session token the user will not logged in.
  717. *
  718. * @param {object} userJSON The JSON map of the User's data
  719. * @static
  720. * @returns {Promise} A promise that is fulfilled with the user when
  721. * the login completes.
  722. */
  723. static hydrate(userJSON) {
  724. const controller = _CoreManager.default.getUserController();
  725. const user = new this();
  726. return controller.hydrate(user, userJSON);
  727. }
  728. /**
  729. * Static version of {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith}
  730. *
  731. * @param provider
  732. * @param options
  733. * @param {object} [options.authData]
  734. * @param saveOpts
  735. * @static
  736. * @returns {Promise}
  737. */
  738. static logInWith(provider, options, saveOpts) {
  739. const user = new this();
  740. return user.linkWith(provider, options, saveOpts);
  741. }
  742. /**
  743. * Logs out the currently logged in user session. This will remove the
  744. * session from disk, log out of linked services, and future calls to
  745. * <code>current</code> will return <code>null</code>.
  746. *
  747. * @param {object} options
  748. * @static
  749. * @returns {Promise} A promise that is resolved when the session is
  750. * destroyed on the server.
  751. */
  752. static logOut(options = {}) {
  753. const controller = _CoreManager.default.getUserController();
  754. return controller.logOut(options);
  755. }
  756. /**
  757. * Requests a password reset email to be sent to the specified email address
  758. * associated with the user account. This email allows the user to securely
  759. * reset their password on the Parse site.
  760. *
  761. * @param {string} email The email address associated with the user that
  762. * forgot their password.
  763. * @param {object} options
  764. * @static
  765. * @returns {Promise}
  766. */
  767. static requestPasswordReset(email, options) {
  768. options = options || {};
  769. const requestOptions = {};
  770. if (options.hasOwnProperty('useMasterKey')) {
  771. requestOptions.useMasterKey = options.useMasterKey;
  772. }
  773. const controller = _CoreManager.default.getUserController();
  774. return controller.requestPasswordReset(email, requestOptions);
  775. }
  776. /**
  777. * Request an email verification.
  778. *
  779. * @param {string} email The email address associated with the user that
  780. * needs to verify their email.
  781. * @param {object} options
  782. * @static
  783. * @returns {Promise}
  784. */
  785. static requestEmailVerification(email, options) {
  786. options = options || {};
  787. const requestOptions = {};
  788. if (options.hasOwnProperty('useMasterKey')) {
  789. requestOptions.useMasterKey = options.useMasterKey;
  790. }
  791. const controller = _CoreManager.default.getUserController();
  792. return controller.requestEmailVerification(email, requestOptions);
  793. }
  794. /**
  795. * Verify whether a given password is the password of the current user.
  796. * @static
  797. *
  798. * @param {string} username The username of the user whose password should be verified.
  799. * @param {string} password The password to be verified.
  800. * @param {object} options The options.
  801. * @param {boolean} [options.ignoreEmailVerification] Set to `true` to bypass email verification and verify
  802. * the password regardless of whether the email has been verified. This requires the master key.
  803. * @returns {Promise} A promise that is fulfilled with a user when the password is correct.
  804. */
  805. static verifyPassword(username, password, options) {
  806. if (typeof username !== 'string') {
  807. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Username must be a string.'));
  808. }
  809. if (typeof password !== 'string') {
  810. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Password must be a string.'));
  811. }
  812. const controller = _CoreManager.default.getUserController();
  813. return controller.verifyPassword(username, password, options || {});
  814. }
  815. /**
  816. * Allow someone to define a custom User class without className
  817. * being rewritten to _User. The default behavior is to rewrite
  818. * User to _User for legacy reasons. This allows developers to
  819. * override that behavior.
  820. *
  821. * @param {boolean} isAllowed Whether or not to allow custom User class
  822. * @static
  823. */
  824. static allowCustomUserClass(isAllowed) {
  825. _CoreManager.default.set('PERFORM_USER_REWRITE', !isAllowed);
  826. }
  827. /**
  828. * Allows a legacy application to start using revocable sessions. If the
  829. * current session token is not revocable, a request will be made for a new,
  830. * revocable session.
  831. * It is not necessary to call this method from cloud code unless you are
  832. * handling user signup or login from the server side. In a cloud code call,
  833. * this function will not attempt to upgrade the current token.
  834. *
  835. * @param {object} options
  836. * @static
  837. * @returns {Promise} A promise that is resolved when the process has
  838. * completed. If a replacement session token is requested, the promise
  839. * will be resolved after a new token has been fetched.
  840. */
  841. static enableRevocableSession(options) {
  842. options = options || {};
  843. _CoreManager.default.set('FORCE_REVOCABLE_SESSION', true);
  844. if (canUseCurrentUser) {
  845. const current = ParseUser.current();
  846. if (current) {
  847. return current._upgradeToRevocableSession(options);
  848. }
  849. }
  850. return Promise.resolve();
  851. }
  852. /**
  853. * Enables the use of become or the current user in a server
  854. * environment. These features are disabled by default, since they depend on
  855. * global objects that are not memory-safe for most servers.
  856. *
  857. * @static
  858. */
  859. static enableUnsafeCurrentUser() {
  860. canUseCurrentUser = true;
  861. }
  862. /**
  863. * Disables the use of become or the current user in any environment.
  864. * These features are disabled on servers by default, since they depend on
  865. * global objects that are not memory-safe for most servers.
  866. *
  867. * @static
  868. */
  869. static disableUnsafeCurrentUser() {
  870. canUseCurrentUser = false;
  871. }
  872. /**
  873. * When registering users with {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#linkWith linkWith} a basic auth provider
  874. * is automatically created for you.
  875. *
  876. * For advanced authentication, you can register an Auth provider to
  877. * implement custom authentication, deauthentication.
  878. *
  879. * @param provider
  880. * @see {@link https://parseplatform.org/Parse-SDK-JS/api/master/AuthProvider.html AuthProvider}
  881. * @see {@link https://docs.parseplatform.org/js/guide/#custom-authentication-module Custom Authentication Module}
  882. * @static
  883. */
  884. static _registerAuthenticationProvider(provider) {
  885. authProviders[provider.getAuthType()] = provider;
  886. // Synchronize the current user with the auth provider.
  887. ParseUser.currentAsync().then(current => {
  888. if (current) {
  889. current._synchronizeAuthData(provider.getAuthType());
  890. }
  891. });
  892. }
  893. /**
  894. * @param provider
  895. * @param options
  896. * @param {object} [options.authData]
  897. * @param saveOpts
  898. * @deprecated since 2.9.0 see {@link https://parseplatform.org/Parse-SDK-JS/api/master/Parse.User.html#logInWith logInWith}
  899. * @static
  900. * @returns {Promise}
  901. */
  902. static _logInWith(provider, options, saveOpts) {
  903. const user = new this();
  904. return user.linkWith(provider, options, saveOpts);
  905. }
  906. static _clearCache() {
  907. currentUserCache = null;
  908. currentUserCacheMatchesDisk = false;
  909. }
  910. static _setCurrentUserCache(user) {
  911. currentUserCache = user;
  912. }
  913. }
  914. _ParseObject.default.registerSubclass('_User', ParseUser);
  915. const DefaultController = {
  916. updateUserOnDisk(user) {
  917. const path = _Storage.default.generatePath(CURRENT_USER_KEY);
  918. const json = user.toJSON();
  919. delete json.password;
  920. json.className = '_User';
  921. let userData = JSON.stringify(json);
  922. if (_CoreManager.default.get('ENCRYPTED_USER')) {
  923. const crypto = _CoreManager.default.getCryptoController();
  924. userData = crypto.encrypt(json, _CoreManager.default.get('ENCRYPTED_KEY'));
  925. }
  926. return _Storage.default.setItemAsync(path, userData).then(() => {
  927. return user;
  928. });
  929. },
  930. removeUserFromDisk() {
  931. const path = _Storage.default.generatePath(CURRENT_USER_KEY);
  932. currentUserCacheMatchesDisk = true;
  933. currentUserCache = null;
  934. return _Storage.default.removeItemAsync(path);
  935. },
  936. setCurrentUser(user) {
  937. currentUserCache = user;
  938. user._cleanupAuthData();
  939. user._synchronizeAllAuthData();
  940. return DefaultController.updateUserOnDisk(user);
  941. },
  942. currentUser() {
  943. if (currentUserCache) {
  944. return currentUserCache;
  945. }
  946. if (currentUserCacheMatchesDisk) {
  947. return null;
  948. }
  949. if (_Storage.default.async()) {
  950. throw new Error('Cannot call currentUser() when using a platform with an async ' + 'storage system. Call currentUserAsync() instead.');
  951. }
  952. const path = _Storage.default.generatePath(CURRENT_USER_KEY);
  953. let userData = _Storage.default.getItem(path);
  954. currentUserCacheMatchesDisk = true;
  955. if (!userData) {
  956. currentUserCache = null;
  957. return null;
  958. }
  959. if (_CoreManager.default.get('ENCRYPTED_USER')) {
  960. const crypto = _CoreManager.default.getCryptoController();
  961. userData = crypto.decrypt(userData, _CoreManager.default.get('ENCRYPTED_KEY'));
  962. }
  963. userData = JSON.parse(userData);
  964. if (!userData.className) {
  965. userData.className = '_User';
  966. }
  967. if (userData._id) {
  968. if (userData.objectId !== userData._id) {
  969. userData.objectId = userData._id;
  970. }
  971. delete userData._id;
  972. }
  973. if (userData._sessionToken) {
  974. userData.sessionToken = userData._sessionToken;
  975. delete userData._sessionToken;
  976. }
  977. const current = _ParseObject.default.fromJSON(userData);
  978. currentUserCache = current;
  979. current._synchronizeAllAuthData();
  980. return current;
  981. },
  982. currentUserAsync() {
  983. if (currentUserCache) {
  984. return Promise.resolve(currentUserCache);
  985. }
  986. if (currentUserCacheMatchesDisk) {
  987. return Promise.resolve(null);
  988. }
  989. const path = _Storage.default.generatePath(CURRENT_USER_KEY);
  990. return _Storage.default.getItemAsync(path).then(userData => {
  991. currentUserCacheMatchesDisk = true;
  992. if (!userData) {
  993. currentUserCache = null;
  994. return Promise.resolve(null);
  995. }
  996. if (_CoreManager.default.get('ENCRYPTED_USER')) {
  997. const crypto = _CoreManager.default.getCryptoController();
  998. userData = crypto.decrypt(userData.toString(), _CoreManager.default.get('ENCRYPTED_KEY'));
  999. }
  1000. userData = JSON.parse(userData);
  1001. if (!userData.className) {
  1002. userData.className = '_User';
  1003. }
  1004. if (userData._id) {
  1005. if (userData.objectId !== userData._id) {
  1006. userData.objectId = userData._id;
  1007. }
  1008. delete userData._id;
  1009. }
  1010. if (userData._sessionToken) {
  1011. userData.sessionToken = userData._sessionToken;
  1012. delete userData._sessionToken;
  1013. }
  1014. const current = _ParseObject.default.fromJSON(userData);
  1015. currentUserCache = current;
  1016. current._synchronizeAllAuthData();
  1017. return Promise.resolve(current);
  1018. });
  1019. },
  1020. signUp(user, attrs, options) {
  1021. const username = attrs && attrs.username || user.get('username');
  1022. const password = attrs && attrs.password || user.get('password');
  1023. if (!username || !username.length) {
  1024. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Cannot sign up user with an empty username.'));
  1025. }
  1026. if (!password || !password.length) {
  1027. return Promise.reject(new _ParseError.default(_ParseError.default.OTHER_CAUSE, 'Cannot sign up user with an empty password.'));
  1028. }
  1029. return user.save(attrs, options).then(() => {
  1030. // Clear the password field
  1031. user._finishFetch({
  1032. password: undefined
  1033. });
  1034. if (canUseCurrentUser) {
  1035. return DefaultController.setCurrentUser(user);
  1036. }
  1037. return user;
  1038. });
  1039. },
  1040. logIn(user, options) {
  1041. const RESTController = _CoreManager.default.getRESTController();
  1042. const stateController = _CoreManager.default.getObjectStateController();
  1043. const auth = {
  1044. username: user.get('username'),
  1045. password: user.get('password'),
  1046. authData: user.get('authData')
  1047. };
  1048. return RESTController.request(options.usePost ? 'POST' : 'GET', 'login', auth, options).then(response => {
  1049. user._migrateId(response.objectId);
  1050. user._setExisted(true);
  1051. stateController.setPendingOp(user._getStateIdentifier(), 'username', undefined);
  1052. stateController.setPendingOp(user._getStateIdentifier(), 'password', undefined);
  1053. response.password = undefined;
  1054. user._finishFetch(response);
  1055. if (!canUseCurrentUser) {
  1056. // We can't set the current user, so just return the one we logged in
  1057. return Promise.resolve(user);
  1058. }
  1059. return DefaultController.setCurrentUser(user);
  1060. });
  1061. },
  1062. loginAs(user, userId) {
  1063. const RESTController = _CoreManager.default.getRESTController();
  1064. return RESTController.request('POST', 'loginAs', {
  1065. userId
  1066. }, {
  1067. useMasterKey: true
  1068. }).then(response => {
  1069. user._finishFetch(response);
  1070. user._setExisted(true);
  1071. if (!canUseCurrentUser) {
  1072. return Promise.resolve(user);
  1073. }
  1074. return DefaultController.setCurrentUser(user);
  1075. });
  1076. },
  1077. become(user, options) {
  1078. const RESTController = _CoreManager.default.getRESTController();
  1079. return RESTController.request('GET', 'users/me', {}, options).then(response => {
  1080. user._finishFetch(response);
  1081. user._setExisted(true);
  1082. return DefaultController.setCurrentUser(user);
  1083. });
  1084. },
  1085. hydrate(user, userJSON) {
  1086. user._finishFetch(userJSON);
  1087. user._setExisted(true);
  1088. if (userJSON.sessionToken && canUseCurrentUser) {
  1089. return DefaultController.setCurrentUser(user);
  1090. } else {
  1091. return Promise.resolve(user);
  1092. }
  1093. },
  1094. me(user, options) {
  1095. const RESTController = _CoreManager.default.getRESTController();
  1096. return RESTController.request('GET', 'users/me', {}, options).then(response => {
  1097. user._finishFetch(response);
  1098. user._setExisted(true);
  1099. return user;
  1100. });
  1101. },
  1102. logOut(options) {
  1103. const RESTController = _CoreManager.default.getRESTController();
  1104. if (options.sessionToken) {
  1105. return RESTController.request('POST', 'logout', {}, options);
  1106. }
  1107. return DefaultController.currentUserAsync().then(currentUser => {
  1108. const path = _Storage.default.generatePath(CURRENT_USER_KEY);
  1109. let promise = _Storage.default.removeItemAsync(path);
  1110. if (currentUser !== null) {
  1111. const currentSession = currentUser.getSessionToken();
  1112. if (currentSession && (0, _isRevocableSession.default)(currentSession)) {
  1113. promise = promise.then(() => {
  1114. return RESTController.request('POST', 'logout', {}, {
  1115. sessionToken: currentSession
  1116. });
  1117. });
  1118. }
  1119. currentUser._logOutWithAll();
  1120. currentUser._finishFetch({
  1121. sessionToken: undefined
  1122. });
  1123. }
  1124. currentUserCacheMatchesDisk = true;
  1125. currentUserCache = null;
  1126. return promise;
  1127. });
  1128. },
  1129. requestPasswordReset(email, options) {
  1130. const RESTController = _CoreManager.default.getRESTController();
  1131. return RESTController.request('POST', 'requestPasswordReset', {
  1132. email: email
  1133. }, options);
  1134. },
  1135. async upgradeToRevocableSession(user, options) {
  1136. const token = user.getSessionToken();
  1137. if (!token) {
  1138. return Promise.reject(new _ParseError.default(_ParseError.default.SESSION_MISSING, 'Cannot upgrade a user with no session token'));
  1139. }
  1140. options.sessionToken = token;
  1141. const RESTController = _CoreManager.default.getRESTController();
  1142. const result = await RESTController.request('POST', 'upgradeToRevocableSession', {}, options);
  1143. user._finishFetch({
  1144. sessionToken: (result === null || result === void 0 ? void 0 : result.sessionToken) || ''
  1145. });
  1146. const current = await user.isCurrentAsync();
  1147. if (current) {
  1148. return DefaultController.setCurrentUser(user);
  1149. }
  1150. return Promise.resolve(user);
  1151. },
  1152. linkWith(user, authData, options) {
  1153. return user.save({
  1154. authData
  1155. }, options).then(() => {
  1156. if (canUseCurrentUser) {
  1157. return DefaultController.setCurrentUser(user);
  1158. }
  1159. return user;
  1160. });
  1161. },
  1162. verifyPassword(username, password, options) {
  1163. const RESTController = _CoreManager.default.getRESTController();
  1164. const data = {
  1165. username,
  1166. password,
  1167. ...(options.ignoreEmailVerification !== undefined && {
  1168. ignoreEmailVerification: options.ignoreEmailVerification
  1169. })
  1170. };
  1171. return RESTController.request('GET', 'verifyPassword', data, options);
  1172. },
  1173. requestEmailVerification(email, options) {
  1174. const RESTController = _CoreManager.default.getRESTController();
  1175. return RESTController.request('POST', 'verificationEmailRequest', {
  1176. email: email
  1177. }, options);
  1178. }
  1179. };
  1180. _CoreManager.default.setParseUser(ParseUser);
  1181. _CoreManager.default.setUserController(DefaultController);
  1182. var _default = exports.default = ParseUser;