All files / src/lib/auth token.ts

61.36% Statements 27/44
40% Branches 2/5
66.66% Functions 2/3
61.36% Lines 27/44

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 451x 1x 1x 1x                             1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 32x 32x       32x 32x 32x 32x 32x  
const ACCESS_TOKEN_KEY = 'accessToken';
const COOKIE_DOMAIN = '.wego.monster';
 
export const setAccessToken = (token: string, maxAgeSeconds?: number) => {
  if (typeof document === 'undefined') return;

  const parts = [
    `${ACCESS_TOKEN_KEY}=${encodeURIComponent(token)}`,
    'path=/',
    `domain=${COOKIE_DOMAIN}`,
  ];

  if (typeof maxAgeSeconds === 'number' && maxAgeSeconds > 0) {
    parts.push(`Max-Age=${maxAgeSeconds}`);
  }

  document.cookie = parts.join('; ');
};
 
export const clearAccessToken = () => {
  if (typeof document === 'undefined') return;
 
  document.cookie = [
    `${ACCESS_TOKEN_KEY}=`,
    'Max-Age=0',
    'Expires=Thu, 01 Jan 1970 00:00:00 GMT',
    'path=/',
    `domain=${COOKIE_DOMAIN}`,
  ].join('; ');
 
  document.cookie = `${ACCESS_TOKEN_KEY}=; Max-Age=0; path=/`;
};
 
export const getAccessToken = async () => {
  const isServer = typeof window === 'undefined';
  if (isServer) {
    const { cookies } = await import('next/headers');
    const cookieStore = await cookies();
    return cookieStore.get(ACCESS_TOKEN_KEY)?.value;
  } else {
    const match = document.cookie.match(new RegExp(`(^| )${ACCESS_TOKEN_KEY}=([^;]+)`));
    return match ? decodeURIComponent(match[2]) : undefined;
  }
};