ParseUser.js 48 KB

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