ParseUser.js 41 KB

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