All files / src/services tokenStorage.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 3/3
100% Lines 14/14

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                  38x           38x 721x 721x   1x 1x               38x 2x 2x   1x             38x 2x 2x   1x    
// src/services/tokenStorage.ts
 
/**
 * A centralized module for handling authentication token storage.
 * This abstraction layer makes it easy to change the storage mechanism
 * (e.g., from localStorage to sessionStorage or an in-memory store for testing)
 * without altering the application's authentication logic.
 */
 
const TOKEN_KEY = 'authToken';
 
/**
 * Retrieves the authentication token from storage.
 * @returns The token string, or null if not found or if storage is unavailable.
 */
export const getToken = (): string | null => {
  try {
    return window.localStorage.getItem(TOKEN_KEY);
  } catch (error) {
    console.error('SecurityError: Failed to access localStorage to get token.', error);
    return null;
  }
};
 
/**
 * Stores the authentication token.
 * @param token The token string to store.
 */
export const setToken = (token: string): void => {
  try {
    window.localStorage.setItem(TOKEN_KEY, token);
  } catch (error) {
    console.error('SecurityError: Failed to access localStorage to set token.', error);
  }
};
 
/**
 * Removes the authentication token from storage.
 */
export const removeToken = (): void => {
  try {
    window.localStorage.removeItem(TOKEN_KEY);
  } catch (error) {
    console.error('SecurityError: Failed to access localStorage to remove token.', error);
  }
};