重构
This commit is contained in:
@@ -6,7 +6,7 @@ import { ADMIN_LOCALE_STORAGE_KEY } from './i18n';
|
||||
|
||||
const api = axios.create({ baseURL: '/api' });
|
||||
|
||||
let handling401 = false;
|
||||
let handlingAuthInvalid = false;
|
||||
let handling403Portal = false;
|
||||
|
||||
const PORTAL_MISMATCH_CODES = new Set(['ADMIN_ACCESS_ONLY', 'AGENT_ACCESS_ONLY']);
|
||||
@@ -17,6 +17,33 @@ function requestPath(config: { url?: string; baseURL?: string } | undefined): st
|
||||
return `${base}${config.url}`;
|
||||
}
|
||||
|
||||
function isLoginRequest(config: { url?: string; baseURL?: string } | undefined): boolean {
|
||||
return requestPath(config).includes('/auth/login');
|
||||
}
|
||||
|
||||
function isInvalidCredentialsResponse(data: unknown): boolean {
|
||||
return (
|
||||
typeof data === 'object' &&
|
||||
data !== null &&
|
||||
'code' in data &&
|
||||
(data as { code?: unknown }).code === 'INVALID_CREDENTIALS'
|
||||
);
|
||||
}
|
||||
|
||||
async function redirectToLoginForInvalidSession() {
|
||||
if (handlingAuthInvalid) return;
|
||||
handlingAuthInvalid = true;
|
||||
try {
|
||||
clearStaffSession();
|
||||
resetStaffSessionHydration();
|
||||
if (router.currentRoute.value.path !== '/login') {
|
||||
await router.replace('/login');
|
||||
}
|
||||
} finally {
|
||||
handlingAuthInvalid = false;
|
||||
}
|
||||
}
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const t = localStorage.getItem('manage_token');
|
||||
if (t) config.headers.Authorization = `Bearer ${t}`;
|
||||
@@ -49,7 +76,18 @@ api.interceptors.request.use((config) => {
|
||||
});
|
||||
|
||||
api.interceptors.response.use(
|
||||
(res) => res,
|
||||
async (res) => {
|
||||
if (!isLoginRequest(res.config) && isInvalidCredentialsResponse(res.data)) {
|
||||
await redirectToLoginForInvalidSession();
|
||||
return Promise.reject(
|
||||
Object.assign(new Error((res.data as { error?: string }).error || 'Invalid credentials'), {
|
||||
response: res,
|
||||
config: res.config,
|
||||
}),
|
||||
);
|
||||
}
|
||||
return res;
|
||||
},
|
||||
async (err) => {
|
||||
if (err.isPortalMismatch) {
|
||||
await ensureStaffSession();
|
||||
@@ -59,14 +97,11 @@ api.interceptors.response.use(
|
||||
return Promise.reject(err);
|
||||
}
|
||||
|
||||
if (err.response?.status === 401 && !handling401) {
|
||||
handling401 = true;
|
||||
clearStaffSession();
|
||||
resetStaffSessionHydration();
|
||||
if (router.currentRoute.value.path !== '/login') {
|
||||
await router.replace('/login');
|
||||
}
|
||||
handling401 = false;
|
||||
if (
|
||||
!isLoginRequest(err.config) &&
|
||||
(err.response?.status === 401 || isInvalidCredentialsResponse(err.response?.data))
|
||||
) {
|
||||
await redirectToLoginForInvalidSession();
|
||||
}
|
||||
|
||||
if (
|
||||
|
||||
Reference in New Issue
Block a user