token.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import { tokenValidation } from '../store';
  2. export function setTokenCookie(token) {
  3. document.cookie = `token=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`;
  4. const expiration = new Date(Date.now() + 30 * 60 * 1000);
  5. document.cookie = `token=${token}-time=${expiration.toUTCString()}; path=/; expires=${expiration.toUTCString()}`;
  6. }
  7. export function getToken() {
  8. const tokenCookie = document.cookie.split('; ').find((row) => row.startsWith('token='));
  9. if (tokenCookie == null) return null;
  10. const [tokenPart] = tokenCookie.split('-time=');
  11. return tokenPart.replace('token=', '');
  12. }
  13. export function checkTokenExpiry() {
  14. const tokenCookie = document.cookie.split('; ').find((row) => row.startsWith('token='));
  15. if (tokenCookie == null) {
  16. tokenValidation.set(true);
  17. return;
  18. }
  19. const [tokenPart, timePart] = tokenCookie.split('-time=');
  20. if (timePart == null) {
  21. tokenValidation.set(true);
  22. return;
  23. }
  24. const expirationTime = new Date(timePart);
  25. const now = new Date();
  26. const timeDiff = expirationTime - now;
  27. if (timeDiff <= 0) {
  28. tokenValidation.set(true);
  29. } else if (timeDiff <= 5 * 60 * 1000) {
  30. const myHeaders = new Headers();
  31. myHeaders.append('Content-Type', 'application/json');
  32. const raw = JSON.stringify({
  33. email: localStorage.getItem('email')
  34. });
  35. const requestOptions = {
  36. method: 'POST',
  37. headers: myHeaders,
  38. body: raw,
  39. redirect: 'follow'
  40. };
  41. fetch('http://localhost:3005/api/refresh-token', requestOptions)
  42. .then((response) => response.json())
  43. .then((result) => setTokenCookie(result.data.token));
  44. }
  45. tokenValidation.set(false);
  46. }