2020-12-06 13:56:14 -08:00
|
|
|
import http from '@/api/http';
|
2026-10-05 18:10:18 -04:00
|
|
|
import type { AxiosError } from 'axios';
|
2026-10-16 14:20:45 +01:00
|
|
|
import { endBootstrapSession, hasBootstrapSession } from '@/bootstrap';
|
2026-10-05 18:10:18 -04:00
|
|
|
import { router } from '@/router/router';
|
2026-10-16 14:20:45 +01:00
|
|
|
import { parseRedirectSearch } from '@/router/redirect';
|
2026-10-05 18:10:18 -04:00
|
|
|
import { isObject } from '@/lib/objects';
|
2020-12-06 13:56:14 -08:00
|
|
|
|
2026-10-05 18:10:18 -04:00
|
|
|
export const setupInterceptors = () => {
|
2022-06-26 15:13:52 -04:00
|
|
|
http.interceptors.response.use(
|
|
|
|
|
(resp) => resp,
|
|
|
|
|
(error: AxiosError) => {
|
2026-11-05 15:10:39 -05:00
|
|
|
// 419 is the CSRF failure a stateful request gets once its session has expired.
|
|
|
|
|
const status = error.response?.status;
|
|
|
|
|
|
|
|
|
|
if ((status === 401 || status === 419) && hasBootstrapSession()) {
|
2026-10-16 14:20:45 +01:00
|
|
|
endBootstrapSession();
|
|
|
|
|
void router.navigate({
|
|
|
|
|
to: '/auth/login',
|
|
|
|
|
search: parseRedirectSearch({ redirect: router.latestLocation.href }),
|
|
|
|
|
replace: true,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2022-06-26 15:13:52 -04:00
|
|
|
if (error.response?.status === 400) {
|
2026-10-05 18:10:18 -04:00
|
|
|
const data = error.response.data;
|
|
|
|
|
const firstError =
|
|
|
|
|
isObject(data) && 'errors' in data && Array.isArray(data.errors) ? data.errors[0] : null;
|
2026-10-08 16:53:20 -04:00
|
|
|
|
2022-06-26 17:31:47 -04:00
|
|
|
if (
|
2026-10-05 18:10:18 -04:00
|
|
|
isObject(firstError) &&
|
|
|
|
|
'code' in firstError &&
|
|
|
|
|
firstError.code === 'TwoFactorAuthRequiredException'
|
2022-06-26 17:31:47 -04:00
|
|
|
) {
|
2022-06-26 15:13:52 -04:00
|
|
|
if (!window.location.pathname.startsWith('/account')) {
|
2026-10-08 16:53:20 -04:00
|
|
|
void router.navigate({ to: '/account', replace: true, state: { twoFactorRedirect: true } });
|
2022-06-26 15:13:52 -04:00
|
|
|
}
|
2020-12-06 13:56:14 -08:00
|
|
|
}
|
|
|
|
|
}
|
2026-10-08 16:53:20 -04:00
|
|
|
|
2022-06-26 15:13:52 -04:00
|
|
|
throw error;
|
2020-12-06 13:56:14 -08:00
|
|
|
}
|
2022-06-26 15:13:52 -04:00
|
|
|
);
|
2020-12-06 13:56:14 -08:00
|
|
|
};
|