cookie.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { DEFAULT_CACHE_TIME } from '../../settings/encryptionSetting';
  2. import { getStorageShortName } from '/@/utils/helper/envHelper';
  3. import { cacheCipher } from '/@/settings/encryptionSetting';
  4. import Encryption from '/@/utils/encryption/aesEncryption';
  5. export default class WebCookie {
  6. private encryption: Encryption;
  7. private hasEncrypt: boolean;
  8. constructor(hasEncrypt = true, key = cacheCipher.key, iv = cacheCipher.iv) {
  9. const encryption = new Encryption({ key, iv });
  10. this.encryption = encryption;
  11. this.hasEncrypt = hasEncrypt;
  12. }
  13. private getKey(key: string) {
  14. return `${getStorageShortName()}${key}`.toUpperCase();
  15. }
  16. /**
  17. * Add cookie
  18. * @param name cookie key
  19. * @param value cookie value
  20. * @param expire
  21. * If the expiration time is not set, the default management browser will automatically delete
  22. * e.g:
  23. * cookieData.set('name','value',)
  24. */
  25. setCookie(key: string, value: any, expire: number | null = DEFAULT_CACHE_TIME) {
  26. value = this.hasEncrypt ? this.encryption.encryptByAES(JSON.stringify(value)) : value;
  27. document.cookie = this.getKey(key) + '=' + value + '; Max-Age=' + expire;
  28. }
  29. /**
  30. * Get the cook value according to the key
  31. * @param key cookie key
  32. */
  33. getCookie(key: string) {
  34. const arr = document.cookie.split('; ');
  35. for (let i = 0; i < arr.length; i++) {
  36. const arr2 = arr[i].split('=');
  37. if (arr2[0] === this.getKey(key)) {
  38. let message: any = null;
  39. const str = arr2[1];
  40. if (this.hasEncrypt && str) {
  41. message = this.encryption.decryptByAES(str);
  42. try {
  43. return JSON.parse(message);
  44. } catch (e) {
  45. return str;
  46. }
  47. }
  48. return str;
  49. }
  50. }
  51. return '';
  52. }
  53. /**
  54. * Delete cookie based on cookie key
  55. * @param key cookie key
  56. */
  57. removeCookie(key: string) {
  58. this.setCookie(key, 1, -1);
  59. }
  60. /**
  61. * clear cookie
  62. */
  63. clearCookie(): void {
  64. const keys = document.cookie.match(/[^ =;]+(?==)/g);
  65. if (keys) {
  66. for (let i = keys.length; i--; ) {
  67. document.cookie = keys[i] + '=0;expires=' + new Date(0).toUTCString();
  68. }
  69. }
  70. }
  71. }