给所有请求都加上jwt,隐藏生成jwt的secret(放到.env中),隐藏app-secret(放在pm2运行配置文件中,后续直接读取环境配置即可)

This commit is contained in:
2025-10-17 15:28:22 +08:00
parent 9ec6d30573
commit 59706b70d0
70 changed files with 2279 additions and 688 deletions
+29 -19
View File
@@ -39,6 +39,7 @@ export interface DocumentSearchParams {
pageSize?: number;
reviewType?: string;
userId?: string; // 添加用户ID筛选
token?: string; // JWT token
}
/**
@@ -88,6 +89,7 @@ export interface DocumentUI {
fileType: string;
path: string;
isTest: boolean;
remark?: string;
updatedAt?: string;
pageCount?: number;
ocrResult?: unknown;
@@ -108,11 +110,12 @@ function getFileExtension(filename: string): string {
* @param id 评查结果ID
* @returns 评查结果
*/
async function getEvaluationResults(id: number) {
async function getEvaluationResults(id: number, frontendJWT?: string) {
const response = await postgrestGet<[]>('evaluation_results', {
filter: {
'document_id': `eq.${id}`
}
},
token: frontendJWT
});
if (response.error) {
return { error: response.error, status: response.status };
@@ -125,12 +128,12 @@ async function getEvaluationResults(id: number) {
/**
* 将API文档转换为UI文档
*/
async function convertToUIDocument(doc: Document): Promise<DocumentUI> {
async function convertToUIDocument(doc: Document, frontendJWT?: string): Promise<DocumentUI> {
// 获取文档类型信息
const typeResponse = await getDocumentTypes();
const typeResponse = await getDocumentTypes(undefined, frontendJWT);
const documentTypes = typeResponse.data?.types || [];
const docType = documentTypes.find(type => type.id.toString() === doc.type_id.toString());
const evaluationResult = await getEvaluationResults(doc.id);
const evaluationResult = await getEvaluationResults(doc.id, frontendJWT);
let issues = 0;
interface EvaluationResultItem {
@@ -164,6 +167,7 @@ async function convertToUIDocument(doc: Document): Promise<DocumentUI> {
fileType: getFileExtension(doc.name),
path: doc.path,
isTest: doc.is_test_document,
remark: doc.remark,
updatedAt: formatDate(doc.updated_at),
pageCount: doc.ocr_result?.__meta?.page_count || 0,
ocrResult: doc.ocr_result
@@ -216,7 +220,8 @@ export async function getDocuments(searchParams: DocumentSearchParams = {}): Pro
dateFrom,
dateTo,
reviewType,
userId
userId,
token
} = searchParams;
let documentTypes: number[] | undefined;
@@ -248,8 +253,8 @@ export async function getDocuments(searchParams: DocumentSearchParams = {}): Pro
// 并行执行获取数据和获取总数的请求
const [documentsResponse, countResponse] = await Promise.all([
postgrestPost<DocumentFromSQL[], unknown>('rpc/get_documents_with_filters', { ...rpcParams, page, page_size: pageSize }),
postgrestPost<number, unknown>('rpc/count_documents_with_filters', rpcParams)
postgrestPost<DocumentFromSQL[], unknown>('rpc/get_documents_with_filters', { ...rpcParams, page, page_size: pageSize }, token),
postgrestPost<number, unknown>('rpc/count_documents_with_filters', rpcParams, token)
]);
// 处理获取文档列表的错误
@@ -305,9 +310,10 @@ export async function getDocuments(searchParams: DocumentSearchParams = {}): Pro
* 删除文档
* @param id 文档ID
* @param userId 用户ID
* @param token JWT token (可选)
* @returns 删除结果
*/
export async function deleteDocument(id: string, userId: string): Promise<{
export async function deleteDocument(id: string, userId: string, token?: string): Promise<{
success?: boolean;
error?: string;
status?: number;
@@ -327,7 +333,8 @@ export async function deleteDocument(id: string, userId: string): Promise<{
filter: {
'id': `eq.${id}`,
'user_id': `eq.${userId}` // 确保只能删除自己的文档
}
},
token
}
);
@@ -350,7 +357,7 @@ export async function deleteDocument(id: string, userId: string): Promise<{
* @param id 文档ID
* @returns 文档详情
*/
export async function getDocument(id: string, userId: string): Promise<{
export async function getDocument(id: string, userId: string, frontendJWT?: string): Promise<{
data?: DocumentUI;
error?: string;
status?: number;
@@ -371,7 +378,8 @@ export async function getDocument(id: string, userId: string): Promise<{
'id': `eq.${id}`,
'user_id': `eq.${userId}`
},
limit: 1
limit: 1,
token: frontendJWT
}
);
@@ -384,7 +392,7 @@ export async function getDocument(id: string, userId: string): Promise<{
return { error: '文档不存在', status: 404 };
}
const documentUI = await convertToUIDocument(extractedData[0]);
const documentUI = await convertToUIDocument(extractedData[0], frontendJWT);
return { data: documentUI };
} catch (error) {
@@ -402,7 +410,7 @@ export async function getDocument(id: string, userId: string): Promise<{
* @param id 文档ID
* @returns 文档详情
*/
export async function getDocumentWithNoUserId(id: string): Promise<{
export async function getDocumentWithNoUserId(id: string, frontendJWT?: string): Promise<{
data?: DocumentUI;
error?: string;
status?: number;
@@ -418,7 +426,8 @@ export async function getDocumentWithNoUserId(id: string): Promise<{
filter: {
'id': `eq.${id}`,
},
limit: 1
limit: 1,
token: frontendJWT
}
);
@@ -432,7 +441,7 @@ export async function getDocumentWithNoUserId(id: string): Promise<{
}
// console.log('extractedData', extractedData);
const documentUI = await convertToUIDocument(extractedData[0]);
const documentUI = await convertToUIDocument(extractedData[0], frontendJWT);
return { data: documentUI };
} catch (error) {
@@ -488,7 +497,7 @@ export async function getFileDownloadUrl(filePath: string): Promise<{
* @param document 部分文档数据
* @returns 更新结果
*/
export async function updateDocument(id: string, document: Partial<DocumentUI> & { remark?: string }, userId: string): Promise<{
export async function updateDocument(id: string, document: Partial<DocumentUI> & { remark?: string }, userId: string, frontendJWT?: string): Promise<{
data?: DocumentUI;
error?: string;
status?: number;
@@ -533,7 +542,8 @@ export async function updateDocument(id: string, document: Partial<DocumentUI> &
{
id: parseInt(id),
user_id: parseInt(userId) // 确保只能更新自己的文档
}
},
frontendJWT
);
if (response.error) {
@@ -542,7 +552,7 @@ export async function updateDocument(id: string, document: Partial<DocumentUI> &
}
// 获取更新后的完整文档数据
const updatedResponse = await getDocument(id, userId);
const updatedResponse = await getDocument(id, userId, frontendJWT);
return updatedResponse;
} catch (error) {
+22 -12
View File
@@ -357,12 +357,19 @@ export async function uploadDocumentToServer(
// const response = await fetch(`${API_BASE_URL}/admin/documents/upload`, {
try {
// console.log('【调试】开始fetch请求...');
// 构建请求头,只在有JWT token时添加Authorization
const headers: HeadersInit = {
'X-File-Name': encodeURIComponent(fileName)
};
if (jwtToken) {
headers['Authorization'] = `Bearer ${jwtToken}`;
}
const response = await fetch(uploadUrl, {
method: 'POST',
headers: {
'X-File-Name': encodeURIComponent(fileName),
'Authorization': `Bearer ${jwtToken || ''}`
},
headers,
body: formData
});
@@ -422,7 +429,7 @@ export async function uploadDocumentToServer(
* @param reviewType 审核类型(可选)
* @returns 文档列表
*/
export async function getTodayDocuments(userInfo?: { user_id?: number; [key: string]: unknown }, reviewType?: string): Promise<{data: Document[]; error?: never} | {data?: never; error: string; status?: number}> {
export async function getTodayDocuments(userInfo?: { user_id?: number; [key: string]: unknown }, reviewType?: string, token?: string): Promise<{data: Document[]; error?: never} | {data?: never; error: string; status?: number}> {
try {
// 检查用户信息是否存在
if (!userInfo?.user_id) {
@@ -492,7 +499,7 @@ export async function getTodayDocuments(userInfo?: { user_id?: number; [key: str
// postgrestGet<ContractStructureComparison[]>('contract_structure_comparison', comparisonParams)
// ]);
const documentsResponse = await postgrestGet<Document[]>('documents', documentsParams);
const documentsResponse = await postgrestGet<Document[]>('documents', { ...documentsParams, token });
// console.log('documents表响应:', documentsResponse);
// console.log('contract_structure_comparison表响应:', comparisonResponse);
@@ -594,7 +601,7 @@ export async function getTodayDocuments(userInfo?: { user_id?: number; [key: str
}
// console.log('发送请求参数:', params);
const response = await postgrestGet<Document[]>('documents', params);
const response = await postgrestGet<Document[]>('documents', { ...params, token });
// console.log('API 响应:', response);
if (response.error) {
@@ -623,9 +630,10 @@ export async function getTodayDocuments(userInfo?: { user_id?: number; [key: str
/**
* 获取文档类型列表
* @param reviewType 审核类型(可选)
* @param token JWT token (可选)
* @returns 文档类型列表
*/
export async function getDocumentTypes(reviewType?: string): Promise<{data: DocumentType[]; error?: never} | {data?: never; error: string; status?: number}> {
export async function getDocumentTypes(reviewType?: string, token?: string): Promise<{data: DocumentType[]; error?: never} | {data?: never; error: string; status?: number}> {
try {
const params: PostgrestParams = {
select: 'id, name',
@@ -649,7 +657,7 @@ export async function getDocumentTypes(reviewType?: string): Promise<{data: Docu
}
}
const response = await postgrestGet<DocumentType[]>('document_types', params);
const response = await postgrestGet<DocumentType[]>('document_types', { ...params, token });
if (response.error) {
return { error: response.error, status: response.status };
@@ -674,11 +682,13 @@ export async function getDocumentTypes(reviewType?: string): Promise<{data: Docu
* 获取指定文档的状态
* @param documentIds 文档ID列表
* @param attachmentIds 合同附件ID列表(可选)
* @param token JWT token (可选)
* @returns 文档状态列表
*/
export async function getDocumentsStatus(
documentIds: number[],
attachmentIds?: number[]
attachmentIds?: number[],
token?: string
): Promise<{data: Document[]; error?: never} | {data?: never; error: string; status?: number}> {
try {
if ((!documentIds || documentIds.length === 0) && (!attachmentIds || attachmentIds.length === 0)) {
@@ -695,7 +705,7 @@ export async function getDocumentsStatus(
'id': `in.(${documentIds.join(',')})`
}
};
documentsResponse = await postgrestGet<Document[]>('documents', documentsParams);
documentsResponse = await postgrestGet<Document[]>('documents', { ...documentsParams, token });
}
// 查询合同附件状态
@@ -708,7 +718,7 @@ export async function getDocumentsStatus(
'id': `in.(${attachmentIds.join(',')})`
}
};
attachmentResponse = await postgrestGet<ContractStructureComparison[]>('contract_structure_comparison', attachmentParams);
attachmentResponse = await postgrestGet<ContractStructureComparison[]>('contract_structure_comparison', { ...attachmentParams, token });
}
if (documentsResponse.error && attachmentResponse.error) {