CookieManager.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. export default class CookieManager {
  2. constructor() {
  3. this.expiresDays = 30
  4. }
  5. raw() {
  6. return document.cookie
  7. }
  8. parsed() {
  9. let result = {}
  10. if (this.raw() == "") {
  11. return {}
  12. }
  13. this.raw().split(";").forEach((part) => {
  14. const data = part.trim().split("=")
  15. result[data[0]] = data[1]
  16. })
  17. return result
  18. }
  19. save(data) {
  20. if (!data['expires']) {
  21. const d = new Date();
  22. d.setTime(d.getTime() + (this.expiresDays * 24 * 60 * 60 * 1000));
  23. data['expires'] = d.toUTCString();
  24. }
  25. if (!data['path']) {
  26. data['path'] = "/"
  27. }
  28. let cookieData = []
  29. for (let index in data) {
  30. cookieData.push(`${index}=${data[index]}`)
  31. }
  32. cookieData.push(`SameSite=Strict`)
  33. cookieData.push(`Secure`)
  34. document.cookie = cookieData.join("; ")
  35. }
  36. get(key) {
  37. let cookieData = this.parsed()
  38. if(Object.keys(cookieData).length == 0) {
  39. return null;
  40. }
  41. return cookieData[key]
  42. }
  43. add(key, value) {
  44. let data = this.parsed()
  45. data[key] = value
  46. this.save(data)
  47. }
  48. parseJwt(token) {
  49. if(!token) {
  50. return null
  51. }
  52. return JSON.parse(decodeURIComponent(atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')).split('').map(function(c) {
  53. return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)
  54. }).join('')))
  55. };
  56. }