All files / src/services axiosConfig.ts

100% Statements 30/30
100% Branches 16/16
100% Functions 6/6
100% Lines 29/29

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      4x                 22x 22x 22x   22x 3x 19x 3x   16x   5x   1x         7x 7x   7x 6x         3x 2x       4x 2x   14x 14x 14x   14x   37x 9x 7x     5x   3x   14x        
import axios from 'axios';
import { useAuthStore } from '../stores/useAuthStore';
 
const PUBLIC_PATHS = [
  '/api/auth/login',
  '/api/auth/register',
  '/api/auth/email/resend',
  '/api/auth/password/forgot',
  '/api/auth/password/reset',
];
 
export function getPathnameFromConfig(config: any): string {
  const url = config.url ?? '';
  const base = config.baseURL;
  try {
    let fullUrl: URL;
    if (/^https?:\/\//i.test(url)) {
      fullUrl = new URL(url);
    } else if (base) {
      fullUrl = new URL(url, base);
    } else {
      return url.split('?')[0];
    }
    return fullUrl.pathname;
  } catch {
    return url.split('?')[0];
  }
}
 
function handle401() {
  const authStore = useAuthStore.getState();
  authStore.clearToken();
  // Si vous gérez un flag sessionExpired, vous pouvez l’activer ici
  if (window.location.pathname !== '/login') {
    window.location.href = '/login';
  }
}
 
function handle403() {
  if (window.location.pathname !== '/unauthorized') {
    window.location.href = '/unauthorized';
  }
}
 
axios.interceptors.response.use(
  response => response,
  error => {
    const status = error.response?.status;
    const config = error.config;
    const path = getPathnameFromConfig(config);
 
    if (status === 401) {
      // Si path est un endpoint public, ne pas rediriger automatiquement
      const isPublic = PUBLIC_PATHS.some(prefix => path.startsWith(prefix));
      if (!isPublic) {
        handle401();
      }
      // Sinon, on laisse le code appelant gérer l’erreur (ex.: afficher "identifiants incorrects")
    } else if (status === 403) {
      // Redirige vers /unauthorized
      handle403();
    }
    return Promise.reject(error);
  }
);