All files / lib/api/core tokenHelpers.ts

91.66% Statements 44/48
47.36% Branches 9/19
100% Functions 7/7
100% Lines 43/43

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 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 7041x 19x 19x 19x 19x 18x   1x 1x       41x 13x 13x 13x     41x 3x 3x 3x 3x 3x 2x 1x     1x       41x 13x 13x 13x 13x 13x 12x           41x 16x 16x   4x 4x 2x 2x 2x   2x         41x   41x 15x     41x 3x 2x    
export function getAuthToken(): string | null {
  Iif (typeof window === 'undefined') return null;
  try {
    const tokenKey = process.env.NEXT_PUBLIC_AUTH_TOKEN_KEY || 'auth_token';
    const token = localStorage.getItem(tokenKey);
    return token;
  } catch (error) {
    console.error('Error getting auth token:', error);
    return null;
  }
}
 
export function getRefreshToken(): string | null {
  Iif (typeof window === 'undefined') return null;
  const refreshKey = process.env.NEXT_PUBLIC_AUTH_REFRESH_TOKEN_KEY || 'auth_refresh_token';
  return localStorage.getItem(refreshKey);
}
 
export function setTokens(accessToken: string, refreshToken?: string): void {
  Iif (typeof window === 'undefined') return;
  try {
    const tokenKey = process.env.NEXT_PUBLIC_AUTH_TOKEN_KEY || 'auth_token';
    const refreshKey = process.env.NEXT_PUBLIC_AUTH_REFRESH_TOKEN_KEY || 'auth_refresh_token';
    localStorage.setItem(tokenKey, accessToken);
    if (refreshToken) {
      localStorage.setItem(refreshKey, refreshToken);
    }
  } catch (error) {
    console.error('Error setting tokens:', error);
  }
}
 
export function clearTokens(): void {
  Iif (typeof window === 'undefined') return;
  const tokenKey = process.env.NEXT_PUBLIC_AUTH_TOKEN_KEY || 'auth_token';
  const refreshKey = process.env.NEXT_PUBLIC_AUTH_REFRESH_TOKEN_KEY || 'auth_refresh_token';
  try {
    localStorage.removeItem(tokenKey);
    localStorage.removeItem(refreshKey);
  } catch {
  }
}
 
 
export function isTokenValid(): boolean {
  const token = getAuthToken();
  if (!token) return false;
  
  try {
    const payload = JSON.parse(atob(token.split('.')[1]));
    const now = Math.floor(Date.now() / 1000);
    const isValid = payload.exp > now;
    return isValid;
  }catch {
    return false;
  }
}
 
export type SessionExpiredCallback = () => void;
let sessionExpiredCallback: SessionExpiredCallback | null = null;
 
export function setSessionExpiredCallback(callback: SessionExpiredCallback): void {
  sessionExpiredCallback = callback;
}
 
export function notifySessionExpired(): void {
  if (sessionExpiredCallback) {
    sessionExpiredCallback();
  }
}