138 lines
4.4 KiB
TypeScript
138 lines
4.4 KiB
TypeScript
/**
|
||
* 该文件可自行根据业务逻辑进行调整
|
||
*/
|
||
import type { RequestClientOptions } from '@vben/request';
|
||
|
||
import { useAppConfig } from '@vben/hooks';
|
||
import { preferences } from '@vben/preferences';
|
||
import {
|
||
authenticateResponseInterceptor,
|
||
defaultResponseInterceptor,
|
||
errorMessageResponseInterceptor,
|
||
RequestClient,
|
||
} from '@vben/request';
|
||
import { useAccessStore } from '@vben/stores';
|
||
|
||
import { message } from 'ant-design-vue';
|
||
|
||
import { t } from '#/locales/t';
|
||
import { useAuthStore } from '#/store';
|
||
|
||
import { refreshTokenApi } from './core';
|
||
import { responseErrorMessage } from './error-message';
|
||
|
||
const { apiURL } = useAppConfig(import.meta.env, import.meta.env.PROD);
|
||
|
||
function createRequestClient(baseURL: string, options?: RequestClientOptions) {
|
||
const client = new RequestClient({
|
||
...options,
|
||
baseURL,
|
||
});
|
||
|
||
/**
|
||
* 重新认证逻辑。
|
||
*
|
||
* 这里必须防重入:登出本身也是一个带鉴权头的请求,令牌已经无效时它同样会
|
||
* 拿到 401,于是又走进这个函数、又去登出……递归下去,表现是浏览器疯狂
|
||
* 发 POST /auth/logout 直到页面卡死。authStore.logout() 里的 try/catch 挡不住,
|
||
* 它catch 的是自己那一层,下一层照样新起一轮。
|
||
*/
|
||
let reAuthenticating = false;
|
||
async function doReAuthenticate() {
|
||
if (reAuthenticating) {
|
||
return;
|
||
}
|
||
reAuthenticating = true;
|
||
console.warn('Access token or refresh token is invalid or expired. ');
|
||
const accessStore = useAccessStore();
|
||
const authStore = useAuthStore();
|
||
accessStore.setAccessToken(null);
|
||
if (
|
||
preferences.app.loginExpiredMode === 'modal' &&
|
||
accessStore.isAccessChecked
|
||
) {
|
||
accessStore.setLoginExpired(true);
|
||
} else {
|
||
try {
|
||
await authStore.logout();
|
||
} finally {
|
||
reAuthenticating = false;
|
||
}
|
||
return;
|
||
}
|
||
reAuthenticating = false;
|
||
}
|
||
|
||
/**
|
||
* 刷新 token 逻辑。
|
||
*
|
||
* 后端发的是 30 天有效的长令牌,没有 refresh token。配套地
|
||
* `enableRefreshToken` 关掉了,拦截器不会走到这里;万一哪天有人打开开关,
|
||
* 这里立刻抛错,比默默续期一个假令牌然后无限重试要好得多。
|
||
*/
|
||
async function doRefreshToken(): Promise<string> {
|
||
await refreshTokenApi();
|
||
throw new Error(t('后端未启用令牌续期'));
|
||
}
|
||
|
||
function formatToken(token: null | string) {
|
||
return token ? `Bearer ${token}` : null;
|
||
}
|
||
|
||
// 请求头处理
|
||
client.addRequestInterceptor({
|
||
fulfilled: async (config) => {
|
||
const accessStore = useAccessStore();
|
||
|
||
config.headers.Authorization = formatToken(accessStore.accessToken);
|
||
config.headers['Accept-Language'] = preferences.app.locale;
|
||
return config;
|
||
},
|
||
});
|
||
|
||
// 处理返回的响应数据格式。
|
||
//
|
||
// 模板默认配的是 `{codeField:'code', dataField:'data', successCode:0}`,也就是
|
||
// 假定后端返回 `{code:0, data:{...}}` 这种信封。admin_api.py 返回的是扁平
|
||
// JSON(`{"access_token":...}`),没有 code 字段,按默认配置每一个 200 都会被
|
||
// 判成失败并抛出——症状是点登录毫无反应,控制台还一句错都不报。
|
||
//
|
||
// 所以改成透传:成败由 HTTP 状态码表达(这本来就是它该干的事),
|
||
// 整个响应体就是数据。这个拦截器不能直接删掉——删了之后没人拆包,
|
||
// 拿到的是整个 axios response,`resp.access_token` 一样是 undefined。
|
||
client.addResponseInterceptor(
|
||
defaultResponseInterceptor({
|
||
codeField: '',
|
||
dataField: (response) => response,
|
||
successCode: () => true,
|
||
}),
|
||
);
|
||
|
||
// token过期的处理
|
||
client.addResponseInterceptor(
|
||
authenticateResponseInterceptor({
|
||
client,
|
||
doReAuthenticate,
|
||
doRefreshToken,
|
||
enableRefreshToken: preferences.app.enableRefreshToken,
|
||
formatToken,
|
||
}),
|
||
);
|
||
|
||
// 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里
|
||
client.addResponseInterceptor(
|
||
errorMessageResponseInterceptor((msg: string, error) => {
|
||
// FastAPI detail may be a validation array or object, never pass it directly to a toast.
|
||
message.error(responseErrorMessage(error?.response?.data, msg));
|
||
}),
|
||
);
|
||
|
||
return client;
|
||
}
|
||
|
||
export const requestClient = createRequestClient(apiURL, {
|
||
responseReturn: 'data',
|
||
});
|
||
|
||
export const baseRequestClient = new RequestClient({ baseURL: apiURL });
|