ParseUser.js 52 KB

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