Source: util/session.es.js

  1. /**
  2. * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
  3. *
  4. * This library is free software; you can redistribute it and/or modify it under
  5. * the terms of the GNU Lesser General Public License as published by the Free
  6. * Software Foundation; either version 2.1 of the License, or (at your option)
  7. * any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful, but WITHOUT
  10. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  11. * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
  12. * details.
  13. */
  14. import fetch from './fetch.es';
  15. const TOKEN_SERIALIZE = 'serialize://';
  16. function getSessionClickFormData(cmd) {
  17. const doAsUserIdEncoded = Liferay.ThemeDisplay.getDoAsUserIdEncoded();
  18. const formData = new FormData();
  19. formData.append('cmd', cmd);
  20. formData.append('p_auth', Liferay.authToken);
  21. if (doAsUserIdEncoded) {
  22. formData.append('doAsUserId', doAsUserIdEncoded);
  23. }
  24. return formData;
  25. }
  26. function getSessionClickURL() {
  27. return `${Liferay.ThemeDisplay.getPortalURL()}${Liferay.ThemeDisplay.getPathMain()}/portal/session_click`;
  28. }
  29. /**
  30. * Gets the Store utility fetch value for given key
  31. * @param {String} key string for fetch request
  32. * @param {Object} options (currently only useHttpSession, defaulting to false)
  33. * @return {Promise}
  34. * @review
  35. */
  36. export function getSessionValue(key, options = {}) {
  37. const formData = getSessionClickFormData('get');
  38. formData.append('key', key);
  39. if (options.useHttpSession) {
  40. formData.append('useHttpSession', true);
  41. }
  42. return fetch(getSessionClickURL(), {
  43. body: formData,
  44. method: 'POST',
  45. })
  46. .then((response) => response.text())
  47. .then((responseText) => {
  48. if (responseText.startsWith(TOKEN_SERIALIZE)) {
  49. const value = responseText.substring(TOKEN_SERIALIZE.length);
  50. responseText = JSON.parse(value);
  51. }
  52. return responseText;
  53. });
  54. }
  55. /**
  56. * Sets the Store utility fetch value
  57. * @param {String} key of the formData
  58. * @param {Object|String} value of the key for the formData
  59. * @param {Object} options (currently only useHttpSession, defaulting to false)
  60. * @return {Promise}
  61. * @review
  62. */
  63. export function setSessionValue(key, value, options = {}) {
  64. const formData = getSessionClickFormData('set');
  65. if (value && typeof value === 'object') {
  66. value = TOKEN_SERIALIZE + JSON.stringify(value);
  67. }
  68. formData.append(key, value);
  69. if (options.useHttpSession) {
  70. formData.append('useHttpSession', true);
  71. }
  72. return fetch(getSessionClickURL(), {
  73. body: formData,
  74. method: 'POST',
  75. });
  76. }