ParseUser.js 32 KB

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