2025-08-05 07:08:07 +00:00
|
|
|
|
// src/utils/request.js
|
|
|
|
|
|
import axios from "axios";
|
2026-06-04 07:53:29 +00:00
|
|
|
|
import { generateRandomString, MAX_FILE_SIZE_MB } from "./index";
|
2026-03-05 14:42:36 +00:00
|
|
|
|
import i18n from '@/i18n'
|
2026-04-10 21:48:53 +00:00
|
|
|
|
import { getApiBaseUrl } from './api-base';
|
2026-03-05 14:42:36 +00:00
|
|
|
|
|
|
|
|
|
|
const t = (key: string) => i18n.global.t(key)
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
2025-09-15 18:47:39 +00:00
|
|
|
|
// API基础URL
|
2026-04-10 21:48:53 +00:00
|
|
|
|
const BASE_URL = getApiBaseUrl();
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 创建Axios实例
|
|
|
|
|
|
const instance = axios.create({
|
|
|
|
|
|
baseURL: BASE_URL, // 使用配置的API基础URL
|
|
|
|
|
|
timeout: 30000, // 请求超时时间
|
|
|
|
|
|
headers: {
|
|
|
|
|
|
"Content-Type": "application/json",
|
|
|
|
|
|
"X-Request-ID": `${generateRandomString(12)}`,
|
|
|
|
|
|
},
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-03-17 07:33:19 +00:00
|
|
|
|
// 获取当前用户语言(用于 Accept-Language header)
|
|
|
|
|
|
function getCurrentLanguage(): string {
|
|
|
|
|
|
return i18n.global.locale?.value || localStorage.getItem('locale') || 'zh-CN'
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
|
|
|
|
|
|
instance.interceptors.request.use(
|
|
|
|
|
|
(config) => {
|
2026-06-12 14:40:18 +00:00
|
|
|
|
const existingAuth = config.headers?.Authorization ?? config.headers?.authorization;
|
|
|
|
|
|
const isEmbedAuth = typeof existingAuth === 'string' && existingAuth.startsWith('Embed ');
|
|
|
|
|
|
const isEmbedPath = typeof config.url === 'string' && config.url.includes('/api/v1/embed/');
|
|
|
|
|
|
|
|
|
|
|
|
// 嵌入渠道使用 Embed token;勿用本地 JWT 覆盖(否则调试页会 401)
|
|
|
|
|
|
if (!isEmbedAuth) {
|
|
|
|
|
|
const token = localStorage.getItem('weknora_token');
|
|
|
|
|
|
if (token) {
|
|
|
|
|
|
config.headers["Authorization"] = `Bearer ${token}`;
|
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-03-17 07:33:19 +00:00
|
|
|
|
// 添加用户语言偏好
|
|
|
|
|
|
config.headers["Accept-Language"] = getCurrentLanguage();
|
|
|
|
|
|
|
2026-07-14 08:13:49 +00:00
|
|
|
|
// 添加跨空间访问请求头:只要 setSelectedTenant 写过激活空间,
|
fix(rbac): role-aware UI gates leaked write affordances after tenant switch
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.
Five distinct root causes, all on the client / server boundary:
1. `currentTenantRole` (frontend/src/stores/auth.ts) read
`tenant.value.id` — the user's *home* tenant — instead of the active
tenant id. After switching to A, the helper still returned B's home
role (Owner), so every `hasRole(...)` gate in the codebase silently
short-circuited. Fix: read `selectedTenantId` first, fall back to
`tenant.id`.
2. `setMemberships` was only called once, on /auth/login. Hard reloads
(which the tenant switcher triggers) re-ran `getCurrentUser()` via
`App.vue` and `router/index.ts`, but those callers discarded the
`memberships` field of the response, so the auth store kept the
login-time snapshot forever. Role changes between sessions stayed
invisible. Fix: extract memberships in both /auth/me consumers and
feed them into `setMemberships`.
3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
active tenant id, so any KB inside the current tenant was treated
as "owned by the caller" — bypassing every role gate below. Fix:
compare against `kb.creator_id` (the field PR 5 introduced) and
require an actual creator match. `canEdit` / `canManage` now layer
`hasRole('admin')` on top so a non-creator with sufficient role can
still manage.
4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
more-menu (Settings, Delete, Edit) unconditionally. With the
ownership column from PR 5 this is straightforward to gate on the
client: Settings/Delete now require creator-match or `hasRole('admin')`
per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.
5. The axios interceptor (frontend/src/utils/request.ts) had a
"selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
short-circuit. Any code that wrote the active tenant into
`weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
hydrate) made the two values equal, after which the header silently
stopped attaching and subsequent navigation requests landed on the
home tenant. Fix: drop the short-circuit; always attach when
selectedTenantId is set.
Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.
The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.
2026-05-14 13:55:22 +00:00
|
|
|
|
// 每个请求都要附 X-Tenant-ID。早期版本会 short-circuit
|
|
|
|
|
|
// "selectedTenantId === defaultTenantId 时不附"以减少 header 体积,
|
2026-07-14 08:13:49 +00:00
|
|
|
|
// 但这条优化会被任何把 weknora_tenant 写成激活空间的代码(OIDC
|
fix(rbac): role-aware UI gates leaked write affordances after tenant switch
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.
Five distinct root causes, all on the client / server boundary:
1. `currentTenantRole` (frontend/src/stores/auth.ts) read
`tenant.value.id` — the user's *home* tenant — instead of the active
tenant id. After switching to A, the helper still returned B's home
role (Owner), so every `hasRole(...)` gate in the codebase silently
short-circuited. Fix: read `selectedTenantId` first, fall back to
`tenant.id`.
2. `setMemberships` was only called once, on /auth/login. Hard reloads
(which the tenant switcher triggers) re-ran `getCurrentUser()` via
`App.vue` and `router/index.ts`, but those callers discarded the
`memberships` field of the response, so the auth store kept the
login-time snapshot forever. Role changes between sessions stayed
invisible. Fix: extract memberships in both /auth/me consumers and
feed them into `setMemberships`.
3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
active tenant id, so any KB inside the current tenant was treated
as "owned by the caller" — bypassing every role gate below. Fix:
compare against `kb.creator_id` (the field PR 5 introduced) and
require an actual creator match. `canEdit` / `canManage` now layer
`hasRole('admin')` on top so a non-creator with sufficient role can
still manage.
4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
more-menu (Settings, Delete, Edit) unconditionally. With the
ownership column from PR 5 this is straightforward to gate on the
client: Settings/Delete now require creator-match or `hasRole('admin')`
per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.
5. The axios interceptor (frontend/src/utils/request.ts) had a
"selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
short-circuit. Any code that wrote the active tenant into
`weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
hydrate) made the two values equal, after which the header silently
stopped attaching and subsequent navigation requests landed on the
home tenant. Fix: drop the short-circuit; always attach when
selectedTenantId is set.
Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.
The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.
2026-05-14 13:55:22 +00:00
|
|
|
|
// 回调、UserMenu loadUserInfo、router hydrate)触发,导致后续请求
|
2026-07-14 08:13:49 +00:00
|
|
|
|
// 静默丢失 header,前端"切换了"但实际仍跑在 home 空间里——把"切
|
fix(rbac): role-aware UI gates leaked write affordances after tenant switch
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.
Five distinct root causes, all on the client / server boundary:
1. `currentTenantRole` (frontend/src/stores/auth.ts) read
`tenant.value.id` — the user's *home* tenant — instead of the active
tenant id. After switching to A, the helper still returned B's home
role (Owner), so every `hasRole(...)` gate in the codebase silently
short-circuited. Fix: read `selectedTenantId` first, fall back to
`tenant.id`.
2. `setMemberships` was only called once, on /auth/login. Hard reloads
(which the tenant switcher triggers) re-ran `getCurrentUser()` via
`App.vue` and `router/index.ts`, but those callers discarded the
`memberships` field of the response, so the auth store kept the
login-time snapshot forever. Role changes between sessions stayed
invisible. Fix: extract memberships in both /auth/me consumers and
feed them into `setMemberships`.
3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
active tenant id, so any KB inside the current tenant was treated
as "owned by the caller" — bypassing every role gate below. Fix:
compare against `kb.creator_id` (the field PR 5 introduced) and
require an actual creator match. `canEdit` / `canManage` now layer
`hasRole('admin')` on top so a non-creator with sufficient role can
still manage.
4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
more-menu (Settings, Delete, Edit) unconditionally. With the
ownership column from PR 5 this is straightforward to gate on the
client: Settings/Delete now require creator-match or `hasRole('admin')`
per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.
5. The axios interceptor (frontend/src/utils/request.ts) had a
"selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
short-circuit. Any code that wrote the active tenant into
`weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
hydrate) made the two values equal, after which the header silently
stopped attaching and subsequent navigation requests landed on the
home tenant. Fix: drop the short-circuit; always attach when
selectedTenantId is set.
Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.
The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.
2026-05-14 13:55:22 +00:00
|
|
|
|
// 换之后只有第一批请求带 X-Tenant-ID"调成永久状态。
|
2026-07-14 08:13:49 +00:00
|
|
|
|
// 后端 IsTenantAccessible 已经允许 header 指向 home 空间(自家),
|
fix(rbac): role-aware UI gates leaked write affordances after tenant switch
When an Owner of tenant A invited user B as a Viewer, B could log in,
switch the active tenant from B's home to A via the user menu, and
still see every write button — Create KB, Upload Document, Edit/Delete
agent — because the role-gate plumbing on the client was wired to the
wrong tenant. The server's RBAC enforcement (PR 2 / PR 5) still blocked
the actual mutations with 403, so no data leaked, but the UI presented
authority the user did not have, which is a confusing and embarrassing
defect.
Five distinct root causes, all on the client / server boundary:
1. `currentTenantRole` (frontend/src/stores/auth.ts) read
`tenant.value.id` — the user's *home* tenant — instead of the active
tenant id. After switching to A, the helper still returned B's home
role (Owner), so every `hasRole(...)` gate in the codebase silently
short-circuited. Fix: read `selectedTenantId` first, fall back to
`tenant.id`.
2. `setMemberships` was only called once, on /auth/login. Hard reloads
(which the tenant switcher triggers) re-ran `getCurrentUser()` via
`App.vue` and `router/index.ts`, but those callers discarded the
`memberships` field of the response, so the auth store kept the
login-time snapshot forever. Role changes between sessions stayed
invisible. Fix: extract memberships in both /auth/me consumers and
feed them into `setMemberships`.
3. `KnowledgeBase.vue`'s `isOwner` compared `kb.tenant_id` to the
active tenant id, so any KB inside the current tenant was treated
as "owned by the caller" — bypassing every role gate below. Fix:
compare against `kb.creator_id` (the field PR 5 introduced) and
require an actual creator match. `canEdit` / `canManage` now layer
`hasRole('admin')` on top so a non-creator with sufficient role can
still manage.
4. `KnowledgeBaseList.vue` and `AgentList.vue` rendered the per-card
more-menu (Settings, Delete, Edit) unconditionally. With the
ownership column from PR 5 this is straightforward to gate on the
client: Settings/Delete now require creator-match or `hasRole('admin')`
per the server's `OwnedKBOrAdmin` / `OwnedAgentOrAdmin` matrix.
5. The axios interceptor (frontend/src/utils/request.ts) had a
"selectedTenantId === defaultTenantId → don't attach X-Tenant-ID"
short-circuit. Any code that wrote the active tenant into
`weknora_tenant` (UserMenu's loadUserInfo, OIDC sync, router
hydrate) made the two values equal, after which the header silently
stopped attaching and subsequent navigation requests landed on the
home tenant. Fix: drop the short-circuit; always attach when
selectedTenantId is set.
Server-side, /auth/me read `user.TenantID` (the immutable home tenant
id stamped at signup) when fetching the tenant for the response, so
the `tenant` field always pointed at home even after the auth
middleware had already resolved an active tenant from X-Tenant-ID.
The frontend then re-keyed `authStore.tenant` to the home tenant on
every refresh, undoing the switch. Fix: read the active tenant id from
context (`types.TenantIDFromContext(ctx)`) and only fall back to
user.TenantID when context is unset.
The server-side enforcement was correct throughout — every fix here is
purely about not lying to the user with the rendered UI.
2026-05-14 13:55:22 +00:00
|
|
|
|
// 所以无脑附不会引入新风险。
|
2026-06-12 14:40:18 +00:00
|
|
|
|
if (!isEmbedAuth && !isEmbedPath) {
|
|
|
|
|
|
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
|
|
|
|
|
|
if (selectedTenantId) {
|
|
|
|
|
|
config.headers["X-Tenant-ID"] = selectedTenantId;
|
|
|
|
|
|
}
|
2025-12-02 04:17:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
config.headers["X-Request-ID"] = `${generateRandomString(12)}`;
|
|
|
|
|
|
return config;
|
|
|
|
|
|
},
|
2025-09-15 18:47:39 +00:00
|
|
|
|
(error) => {
|
|
|
|
|
|
return Promise.reject(error);
|
|
|
|
|
|
}
|
2025-08-05 07:08:07 +00:00
|
|
|
|
);
|
|
|
|
|
|
|
2025-09-15 18:47:39 +00:00
|
|
|
|
// Token刷新标志,防止多个请求同时刷新token
|
|
|
|
|
|
let isRefreshing = false;
|
|
|
|
|
|
let failedQueue: Array<{ resolve: Function; reject: Function }> = [];
|
2026-04-15 07:43:56 +00:00
|
|
|
|
|
2026-06-05 10:44:05 +00:00
|
|
|
|
// Share-link endpoints (/auth/invitations/lookup, /auth/register-by-invite)
|
|
|
|
|
|
// are reachable by anonymous users opening an invite link. A 401 from these
|
|
|
|
|
|
// must surface to the page (e.g. expired token), not trigger the
|
|
|
|
|
|
// refresh-then-redirect-to-login flow (issue #1617). '/auth/register' already
|
|
|
|
|
|
// covers '/auth/register-by-invite' via substring match.
|
2026-06-12 14:40:18 +00:00
|
|
|
|
const PUBLIC_AUTH_PATHS = ['/auth/auto-setup', '/auth/login', '/auth/register', '/auth/oidc/', '/auth/invitations/lookup', '/api/v1/embed/'];
|
2026-04-15 07:43:56 +00:00
|
|
|
|
|
|
|
|
|
|
function isPublicAuthRequest(url?: string): boolean {
|
|
|
|
|
|
if (!url) return false;
|
|
|
|
|
|
return PUBLIC_AUTH_PATHS.some(p => url.includes(p));
|
|
|
|
|
|
}
|
2025-09-15 18:47:39 +00:00
|
|
|
|
|
|
|
|
|
|
// 处理队列中的请求
|
|
|
|
|
|
const processQueue = (error: any, token: string | null = null) => {
|
|
|
|
|
|
failedQueue.forEach(({ resolve, reject }) => {
|
|
|
|
|
|
if (error) {
|
|
|
|
|
|
reject(error);
|
|
|
|
|
|
} else {
|
|
|
|
|
|
resolve(token);
|
|
|
|
|
|
}
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
failedQueue = [];
|
|
|
|
|
|
};
|
|
|
|
|
|
|
2026-06-12 14:40:18 +00:00
|
|
|
|
function isEmbedPage(): boolean {
|
|
|
|
|
|
if (typeof window === 'undefined') return false;
|
|
|
|
|
|
return window.location.pathname.startsWith('/embed/');
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-04-15 07:43:56 +00:00
|
|
|
|
function redirectToLogin() {
|
|
|
|
|
|
if (typeof window === 'undefined') return;
|
|
|
|
|
|
if (window.location.pathname === '/login') return;
|
2026-06-12 14:40:18 +00:00
|
|
|
|
// Embed 渠道用 Embed token 鉴权,匿名访问不应被踢到登录页
|
|
|
|
|
|
if (isEmbedPage()) return;
|
2026-04-15 07:43:56 +00:00
|
|
|
|
window.location.href = '/login';
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
instance.interceptors.response.use(
|
|
|
|
|
|
(response) => {
|
|
|
|
|
|
// 根据业务状态码处理逻辑
|
|
|
|
|
|
const { status, data } = response;
|
2026-03-30 07:08:57 +00:00
|
|
|
|
if (status >= 200 && status < 300) {
|
2025-08-05 07:08:07 +00:00
|
|
|
|
return data;
|
|
|
|
|
|
} else {
|
|
|
|
|
|
return Promise.reject(data);
|
|
|
|
|
|
}
|
|
|
|
|
|
},
|
2025-09-15 18:47:39 +00:00
|
|
|
|
async (error: any) => {
|
|
|
|
|
|
const originalRequest = error.config;
|
|
|
|
|
|
|
2025-08-05 07:08:07 +00:00
|
|
|
|
if (!error.response) {
|
2026-03-05 14:42:36 +00:00
|
|
|
|
return Promise.reject({ message: t('error.networkError') });
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
2025-09-15 18:47:39 +00:00
|
|
|
|
|
2026-04-15 07:43:56 +00:00
|
|
|
|
// 公开接口(auto-setup / login / register / oidc)的 401 不走 refresh 逻辑,直接返回错误
|
2026-06-12 14:40:18 +00:00
|
|
|
|
if ((error.response.status === 401 || error.response.status === 403) && isPublicAuthRequest(originalRequest?.url)) {
|
|
|
|
|
|
const { status, data } = error.response;
|
|
|
|
|
|
const msg = typeof data === 'object'
|
|
|
|
|
|
? (typeof data?.error === 'string' ? data.error : (data?.error?.message || data?.message))
|
|
|
|
|
|
: data;
|
|
|
|
|
|
return Promise.reject({ status, message: msg || t('error.invalidCredentials') });
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// Embed 调试页/挂件:无 JWT 时直接拒绝,勿走 refresh → /login
|
|
|
|
|
|
if (error.response.status === 401 && isEmbedPage()) {
|
2025-09-15 18:47:39 +00:00
|
|
|
|
const { status, data } = error.response;
|
2026-06-12 14:40:18 +00:00
|
|
|
|
const msg = typeof data === 'object'
|
|
|
|
|
|
? (typeof data?.error === 'string' ? data.error : (data?.error?.message || data?.message))
|
|
|
|
|
|
: data;
|
|
|
|
|
|
return Promise.reject({ status, message: msg || t('error.invalidCredentials') });
|
2025-09-15 18:47:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 如果是401错误且不是刷新token的请求,尝试刷新token
|
|
|
|
|
|
if (error.response.status === 401 && !originalRequest._retry && !originalRequest.url?.includes('/auth/refresh')) {
|
|
|
|
|
|
if (isRefreshing) {
|
|
|
|
|
|
// 如果正在刷新token,将请求加入队列
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
|
|
failedQueue.push({ resolve, reject });
|
|
|
|
|
|
}).then(token => {
|
|
|
|
|
|
originalRequest.headers['Authorization'] = 'Bearer ' + token;
|
|
|
|
|
|
return instance(originalRequest);
|
|
|
|
|
|
}).catch(err => {
|
|
|
|
|
|
return Promise.reject(err);
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
originalRequest._retry = true;
|
|
|
|
|
|
isRefreshing = true;
|
|
|
|
|
|
|
|
|
|
|
|
const refreshToken = localStorage.getItem('weknora_refresh_token');
|
|
|
|
|
|
|
|
|
|
|
|
if (refreshToken) {
|
|
|
|
|
|
try {
|
|
|
|
|
|
// 动态导入refresh token API
|
|
|
|
|
|
const { refreshToken: refreshTokenAPI } = await import('../api/auth/index');
|
|
|
|
|
|
const response = await refreshTokenAPI(refreshToken);
|
|
|
|
|
|
|
|
|
|
|
|
if (response.success && response.data) {
|
|
|
|
|
|
const { token, refreshToken: newRefreshToken } = response.data;
|
|
|
|
|
|
|
|
|
|
|
|
// 更新localStorage中的token
|
|
|
|
|
|
localStorage.setItem('weknora_token', token);
|
|
|
|
|
|
localStorage.setItem('weknora_refresh_token', newRefreshToken);
|
|
|
|
|
|
|
|
|
|
|
|
// 更新请求头
|
|
|
|
|
|
originalRequest.headers['Authorization'] = 'Bearer ' + token;
|
|
|
|
|
|
|
|
|
|
|
|
// 处理队列中的请求
|
|
|
|
|
|
processQueue(null, token);
|
|
|
|
|
|
|
|
|
|
|
|
return instance(originalRequest);
|
|
|
|
|
|
} else {
|
2026-03-05 14:42:36 +00:00
|
|
|
|
throw new Error(response.message || t('error.tokenRefreshFailed'));
|
2025-09-15 18:47:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
} catch (refreshError) {
|
|
|
|
|
|
// 刷新失败,清除所有token并跳转到登录页
|
|
|
|
|
|
localStorage.removeItem('weknora_token');
|
|
|
|
|
|
localStorage.removeItem('weknora_refresh_token');
|
|
|
|
|
|
localStorage.removeItem('weknora_user');
|
|
|
|
|
|
localStorage.removeItem('weknora_tenant');
|
|
|
|
|
|
|
|
|
|
|
|
processQueue(refreshError, null);
|
|
|
|
|
|
|
2026-04-15 07:43:56 +00:00
|
|
|
|
redirectToLogin();
|
2025-09-15 18:47:39 +00:00
|
|
|
|
|
|
|
|
|
|
return Promise.reject(refreshError);
|
|
|
|
|
|
} finally {
|
|
|
|
|
|
isRefreshing = false;
|
|
|
|
|
|
}
|
|
|
|
|
|
} else {
|
|
|
|
|
|
// 没有refresh token,直接跳转到登录页
|
|
|
|
|
|
localStorage.removeItem('weknora_token');
|
|
|
|
|
|
localStorage.removeItem('weknora_user');
|
|
|
|
|
|
localStorage.removeItem('weknora_tenant');
|
|
|
|
|
|
|
2026-04-15 07:43:56 +00:00
|
|
|
|
redirectToLogin();
|
2025-09-15 18:47:39 +00:00
|
|
|
|
|
2026-03-05 14:42:36 +00:00
|
|
|
|
return Promise.reject({ message: t('error.pleaseRelogin') });
|
2025-09-15 18:47:39 +00:00
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-12-30 03:29:16 +00:00
|
|
|
|
// 处理 Nginx 413 Request Entity Too Large
|
|
|
|
|
|
if (error.response.status === 413) {
|
|
|
|
|
|
return Promise.reject({
|
|
|
|
|
|
status: 413,
|
2026-06-04 07:53:29 +00:00
|
|
|
|
message: i18n.global.t('error.fileSizeExceeded', { size: MAX_FILE_SIZE_MB }),
|
2025-12-30 03:29:16 +00:00
|
|
|
|
success: false
|
|
|
|
|
|
});
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2025-09-15 18:47:39 +00:00
|
|
|
|
const { status, data } = error.response;
|
|
|
|
|
|
// 将HTTP状态码一并抛出,方便上层判断401等场景
|
2025-12-02 13:14:24 +00:00
|
|
|
|
// 后端返回格式: { success: false, error: { code, message, details } }
|
|
|
|
|
|
// 提取 error.message 作为顶层 message,方便前端使用 error?.message 获取
|
2026-03-30 07:08:57 +00:00
|
|
|
|
let errorMessage: string | undefined;
|
|
|
|
|
|
if (typeof data === 'object') {
|
|
|
|
|
|
if (typeof data?.error === 'string') {
|
|
|
|
|
|
errorMessage = data.error;
|
|
|
|
|
|
} else if (data?.error?.message) {
|
|
|
|
|
|
errorMessage = data.error.message;
|
|
|
|
|
|
} else {
|
|
|
|
|
|
errorMessage = data?.message;
|
|
|
|
|
|
}
|
|
|
|
|
|
} else if (typeof data === 'string') {
|
|
|
|
|
|
errorMessage = data;
|
|
|
|
|
|
}
|
2025-12-02 13:14:24 +00:00
|
|
|
|
return Promise.reject({
|
|
|
|
|
|
status,
|
|
|
|
|
|
message: errorMessage,
|
|
|
|
|
|
...(typeof data === 'object' ? data : {})
|
|
|
|
|
|
});
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
);
|
|
|
|
|
|
|
2026-07-01 08:55:30 +00:00
|
|
|
|
export function get<T = any>(url: string, config?: any): Promise<T> {
|
|
|
|
|
|
return instance.get<T>(url, config) as unknown as Promise<T>;
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-01 08:55:30 +00:00
|
|
|
|
export async function getDown(url: string): Promise<Blob> {
|
|
|
|
|
|
const res = await instance.get<Blob>(url, {
|
2025-08-05 07:08:07 +00:00
|
|
|
|
responseType: "blob",
|
2026-07-01 08:55:30 +00:00
|
|
|
|
}) as unknown as Blob;
|
2025-08-05 07:08:07 +00:00
|
|
|
|
return res
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-06-25 08:55:17 +00:00
|
|
|
|
export function postUpload(
|
|
|
|
|
|
url: string,
|
|
|
|
|
|
data = {},
|
|
|
|
|
|
onUploadProgress?: (progressEvent: any) => void,
|
|
|
|
|
|
config: any = {},
|
2026-07-01 08:55:30 +00:00
|
|
|
|
): Promise<any> {
|
2025-08-05 07:08:07 +00:00
|
|
|
|
return instance.post(url, data, {
|
2026-06-25 08:55:17 +00:00
|
|
|
|
...config,
|
2025-08-05 07:08:07 +00:00
|
|
|
|
headers: {
|
|
|
|
|
|
"Content-Type": "multipart/form-data",
|
|
|
|
|
|
"X-Request-ID": `${generateRandomString(12)}`,
|
2026-06-25 08:55:17 +00:00
|
|
|
|
...(config.headers || {}),
|
2025-08-05 07:08:07 +00:00
|
|
|
|
},
|
2026-06-25 08:55:17 +00:00
|
|
|
|
onUploadProgress: onUploadProgress || config.onUploadProgress,
|
2026-07-01 08:55:30 +00:00
|
|
|
|
}) as unknown as Promise<any>;
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-01 08:55:30 +00:00
|
|
|
|
export function postChat<T = any>(url: string, data = {}): Promise<T> {
|
2025-08-05 07:08:07 +00:00
|
|
|
|
return instance.post(url, data, {
|
|
|
|
|
|
headers: {
|
|
|
|
|
|
"Content-Type": "text/event-stream;charset=utf-8",
|
|
|
|
|
|
"X-Request-ID": `${generateRandomString(12)}`,
|
|
|
|
|
|
},
|
2026-07-01 08:55:30 +00:00
|
|
|
|
}) as unknown as Promise<T>;
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-01 08:55:30 +00:00
|
|
|
|
export function post<T = any>(url: string, data = {}, config?: any): Promise<T> {
|
|
|
|
|
|
return instance.post<T>(url, data, config) as unknown as Promise<T>;
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-01 08:55:30 +00:00
|
|
|
|
export function put<T = any>(url: string, data = {}, config?: any): Promise<T> {
|
|
|
|
|
|
return instance.put<T>(url, data, config) as unknown as Promise<T>;
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|
|
|
|
|
|
|
2026-08-25 03:28:12 +00:00
|
|
|
|
export function patch<T = any>(url: string, data = {}, config?: any): Promise<T> {
|
|
|
|
|
|
return instance.patch<T>(url, data, config) as unknown as Promise<T>;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2026-07-01 08:55:30 +00:00
|
|
|
|
export function del<T = any>(url: string, data?: any): Promise<T> {
|
|
|
|
|
|
return instance.delete<T>(url, { data }) as unknown as Promise<T>;
|
2025-08-05 07:08:07 +00:00
|
|
|
|
}
|