ParseUser.js 38 KB

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