ParseUser.js 39 KB

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