WeKnora/frontend/src/utils/request.ts

263 lines
8.6 KiB
TypeScript
Raw Normal View History

2025-08-05 07:08:07 +00:00
// src/utils/request.js
import axios from "axios";
import { generateRandomString, MAX_FILE_SIZE_MB } from "./index";
import i18n from '@/i18n'
import { getApiBaseUrl } from './api-base';
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
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)}`,
},
});
// 获取当前用户语言(用于 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) => {
2025-09-15 18:47:39 +00:00
// 添加JWT token认证
const token = localStorage.getItem('weknora_token');
if (token) {
config.headers["Authorization"] = `Bearer ${token}`;
2025-08-05 07:08:07 +00:00
}
// 添加用户语言偏好
config.headers["Accept-Language"] = getCurrentLanguage();
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
// 添加跨租户访问请求头:只要 setSelectedTenant 写过激活租户,
// 每个请求都要附 X-Tenant-ID。早期版本会 short-circuit
// "selectedTenantId === defaultTenantId 时不附"以减少 header 体积,
// 但这条优化会被任何把 weknora_tenant 写成激活租户的代码(OIDC
// 回调、UserMenu loadUserInfo、router hydrate)触发,导致后续请求
// 静默丢失 header,前端"切换了"但实际仍跑在 home 租户里——把"切
// 换之后只有第一批请求带 X-Tenant-ID"调成永久状态。
// 后端 IsTenantAccessible 已经允许 header 指向 home 租户(自家),
// 所以无脑附不会引入新风险。
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
if (selectedTenantId) {
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
config.headers["X-Tenant-ID"] = selectedTenantId;
}
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 }> = [];
// 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.
const PUBLIC_AUTH_PATHS = ['/auth/auto-setup', '/auth/login', '/auth/register', '/auth/oidc/', '/auth/invitations/lookup'];
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 = [];
};
function redirectToLogin() {
if (typeof window === 'undefined') return;
if (window.location.pathname === '/login') return;
window.location.href = '/login';
}
2025-08-05 07:08:07 +00:00
instance.interceptors.response.use(
(response) => {
// 根据业务状态码处理逻辑
const { status, data } = response;
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) {
return Promise.reject({ message: t('error.networkError') });
2025-08-05 07:08:07 +00:00
}
2025-09-15 18:47:39 +00:00
// 公开接口(auto-setup / login / register / oidc)的 401 不走 refresh 逻辑,直接返回错误
if (error.response.status === 401 && isPublicAuthRequest(originalRequest?.url)) {
2025-09-15 18:47:39 +00:00
const { status, data } = error.response;
return Promise.reject({ status, message: (typeof data === 'object' ? (data?.error?.message || data?.message) : data) || 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 {
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);
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');
redirectToLogin();
2025-09-15 18:47:39 +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,
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等场景
// 后端返回格式: { success: false, error: { code, message, details } }
// 提取 error.message 作为顶层 message,方便前端使用 error?.message 获取
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;
}
return Promise.reject({
status,
message: errorMessage,
...(typeof data === 'object' ? data : {})
});
2025-08-05 07:08:07 +00:00
}
);
export function get(url: string, config?: any) {
return instance.get(url, config);
2025-08-05 07:08:07 +00:00
}
export async function getDown(url: string) {
let res = await instance.get(url, {
responseType: "blob",
});
return res
}
export function postUpload(url: string, data = {}, onUploadProgress?: (progressEvent: any) => void) {
2025-08-05 07:08:07 +00:00
return instance.post(url, data, {
headers: {
"Content-Type": "multipart/form-data",
"X-Request-ID": `${generateRandomString(12)}`,
},
onUploadProgress,
2025-08-05 07:08:07 +00:00
});
}
export function postChat(url: string, data = {}) {
return instance.post(url, data, {
headers: {
"Content-Type": "text/event-stream;charset=utf-8",
"X-Request-ID": `${generateRandomString(12)}`,
},
});
}
export function post(url: string, data = {}, config?: any) {
return instance.post(url, data, config);
2025-08-05 07:08:07 +00:00
}
export function put(url: string, data = {}) {
return instance.put(url, data);
}
export function del(url: string, data?: any) {
return instance.delete(url, { data });
2025-08-05 07:08:07 +00:00
}