auth.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /**
  2. * 设置带过期时间的数据
  3. * @param {string} key - 存储的键
  4. * @param {array} value - 存储的值
  5. * @param {number} expiryDays - 过期天数
  6. * @returns {void}
  7. */
  8. function setItemWithExpiry(key, value, expiryDays) {
  9. const _val = typeof value === 'object' ? JSON.stringify(value) : value;
  10. const now = new Date();
  11. // 计算过期时间的时间戳(毫秒)
  12. const expiryTime = now.getTime() + expiryDays * 24 * 60 * 60 * 1000;
  13. const item = {
  14. value: _val,
  15. expiry: expiryTime,
  16. };
  17. localStorage.setItem(key, JSON.stringify(item));
  18. }
  19. /**
  20. * 获取数据时判断是否过期
  21. * @param {string} key - 存储的键
  22. * @returns {Object|null}
  23. */
  24. function getItemWithExpiry(key) {
  25. const itemStr = localStorage.getItem(key);
  26. if (!itemStr) {
  27. return null;
  28. }
  29. try {
  30. const item = JSON.parse(itemStr);
  31. const now = new Date();
  32. if (now.getTime() > item.expiry) {
  33. console.log('ss');
  34. localStorage.removeItem(key);
  35. return null;
  36. }
  37. return JSON.parse(item.value);
  38. } catch (e) {
  39. // 解析失败,直接返回null
  40. return null;
  41. }
  42. }
  43. const TokenKey = 'GCLS_Token';
  44. export function getSessionID() {
  45. const token = getItemWithExpiry(TokenKey);
  46. return token ? token.session_id ?? '' : '';
  47. }
  48. export function getToken() {
  49. const token = getItemWithExpiry(TokenKey);
  50. return token;
  51. }
  52. export function setToken(token) {
  53. setItemWithExpiry(TokenKey, token, 10);
  54. }
  55. export function removeToken() {
  56. localStorage.removeItem(TokenKey);
  57. }
  58. const ConfigKey = 'GCLS_Config';
  59. export function getConfig() {
  60. const config = getItemWithExpiry(ConfigKey);
  61. return config;
  62. }
  63. export function setConfig(value) {
  64. setItemWithExpiry(ConfigKey, value, 10);
  65. }
  66. export function removeConfig() {
  67. localStorage.removeItem(ConfigKey);
  68. }