fix: align login and home routing with leaudit backend

This commit is contained in:
wren
2026-04-29 18:02:31 +08:00
parent 7dbeaac5f8
commit 3d3d8d6e6b
7 changed files with 636 additions and 724 deletions
+31 -1
View File
@@ -664,7 +664,7 @@ export async function getUserRoutesByRole(
// 注意:Authorization 头会由 axios 拦截器自动添加(从 localStorage 读取)
// 但为了确保使用正确的 token,这里仍然显式传递
const response = await apiRequest<BackendRoutesResponse>(
'/rbac/user/routes', // endpoint (第一个参数)
'/api/rbac/user/routes', // endpoint (第一个参数)
{
method: 'GET',
headers: {
@@ -678,6 +678,12 @@ export async function getUserRoutesByRole(
// 检查响应是否成功
if (response.error) {
console.error('❌ [User Routes] API 请求失败:', response.error);
if (response.status === 404) {
console.warn('⚠️ [User Routes] 后端路由权限接口未落地,回退到静态菜单');
return buildFallbackRoutes(roleKey);
}
// 🔑 如果是令牌过期错误,标记需要重定向到登录页
const isTokenExpired = response.error.includes('令牌已过期') ||
response.error.includes('令牌') ||
@@ -702,6 +708,10 @@ export async function getUserRoutesByRole(
// 检查响应数据
if (!response.data) {
console.error('❌ [User Routes] 后端未返回数据');
if (response.status === 404) {
console.warn('⚠️ [User Routes] 后端路由权限接口未落地,回退到静态菜单');
return buildFallbackRoutes(roleKey);
}
if (typeof window !== 'undefined') {
toastService.error("获取路由数据失败");
}
@@ -998,6 +1008,7 @@ export function mapUserRoleToRoleKey(userRole: string): string {
const roleMapping: Record<string, string> = {
'common': 'common',
'admin': 'admin',
'provincial_admin': 'admin',
'deptLeader': 'deptLeader',
'groupLeader': 'groupLeader',
// 添加常见的后端角色映射
@@ -1010,3 +1021,22 @@ export function mapUserRoleToRoleKey(userRole: string): string {
// 如果找不到映射,返回 userRole 本身(假设后端已经返回了正确的 role_key)
return roleMapping[userRole] || userRole || 'common';
}
/**
* 基于静态菜单数据构造后备结果。
*/
function buildFallbackRoutes(roleKey: string): {
success: boolean;
data: MenuItem[];
permissionMap: Record<string, string[]>;
} {
const mappedRoleKey = mapUserRoleToRoleKey(roleKey);
const fallbackMenus = FALLBACK_MENU_DATA[mappedRoleKey] || FALLBACK_MENU_DATA.common;
const permissionMap: Record<string, string[]> = {};
return {
success: true,
data: fallbackMenus,
permissionMap,
};
}
+23 -104
View File
@@ -1,4 +1,3 @@
import { postgrestGet, type PostgrestParams } from "../postgrest-client";
import { apiRequest } from "../axios-client";
// import dayjs from 'dayjs';
@@ -202,7 +201,7 @@ export async function getHomeData(reviewType?: string | null, userId?: string |
export interface AreaConfig {
area: string; // 地区名称
enabled: boolean; // 是否启用
sort_order: number; // 排序顺序
sortOrder: number; // 排序顺序
}
/**
@@ -212,11 +211,13 @@ export interface EntryModule {
id: number;
name: string;
description: string | null;
path: string | null;
areas: AreaConfig[]; // 修改为对象数组
created_at: string;
updated_at: string;
document_types?: Array<{
targetPath: string | null;
routePath: string | null;
iconPath: string | null;
sortOrder: number;
requiresDocumentTypes: boolean;
areas: AreaConfig[];
documentTypes: Array<{
id: number;
name: string;
code: string | null;
@@ -225,119 +226,38 @@ export interface EntryModule {
/**
* 获取用户可访问的入口模块
* @param userArea 用户所属地区
* @param token JWT token
* @returns 入口模块列表
*/
export async function getEntryModules(userRole: string | null | undefined, userArea: string | null | undefined, token?: string): Promise<EntryModule[]> {
export async function getEntryModules(token?: string): Promise<EntryModule[]> {
try {
if (!userRole || !userArea) {
console.warn('⚠️ [getEntryModules] 用户角色或地区为空,返回空模块列表');
if (!token) {
console.warn('⚠️ [getEntryModules] JWT 为空,返回空模块列表');
return [];
}
// console.log('🔍 [getEntryModules] 查询地区:', userArea);
// 查询 entry_modules 表,获取所有模块(在客户端进行过滤)
const params: PostgrestParams = {
select: 'id,name,description,path,areas,created_at,updated_at',
filter: {}
};
const modulesResponse = await postgrestGet('/api/postgrest/proxy/entry_modules', { ...params, token });
const modulesResponse = await apiRequest<EntryModule[]>(
'/api/home/entry-modules',
{
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
}
);
if (modulesResponse.error) {
console.error('❌ [getEntryModules] 查询入口模块失败:', modulesResponse.error);
return [];
}
const allModules = extractApiData<EntryModule[]>(modulesResponse.data);
if (!allModules || allModules.length === 0) {
const modules = extractApiData<EntryModule[]>(modulesResponse.data);
if (!modules || modules.length === 0) {
console.warn('⚠️ [getEntryModules] 未找到任何入口模块');
return [];
}
// 🔑 在客户端过滤:只保留包含用户地区且已启用的模块
const modules = allModules.filter(module => {
// 省级管理员可以看到所有模块
if (userRole === 'provincial_admin') {
return true;
}
// 检查 areas 数组中是否存在匹配的地区配置
if (!module.areas || !Array.isArray(module.areas)) {
return false;
}
// 查找用户地区的配置
const areaConfig = module.areas.find(config =>
config.area === userArea && config.enabled === true
);
return !!areaConfig; // 找到且启用才返回 true
});
if (modules.length === 0) {
console.warn('⚠️ [getEntryModules] 未找到已启用的入口模块');
return [];
}
// console.log(`✅ [getEntryModules] 找到 ${modules.length} 个已启用的入口模块`);
// 为每个模块查询关联的 document_types
const modulesWithTypes = await Promise.all(
modules.map(async (module) => {
try {
const typesParams: PostgrestParams = {
select: 'id,name,code',
filter: {
entry_module_id: `eq.${module.id}`
}
};
const typesResponse = await postgrestGet('/api/postgrest/proxy/document_types', { ...typesParams, token });
if (typesResponse.error) {
console.error(`❌ [getEntryModules] 查询模块 ${module.id} 的文档类型失败:`, typesResponse.error);
return { ...module, document_types: [] };
}
const documentTypes = extractApiData<Array<{ id: number; name: string; code: string | null }>>(typesResponse.data);
return {
...module,
document_types: documentTypes || []
};
} catch (error) {
console.error(`❌ [getEntryModules] 处理模块 ${module.id} 时出错:`, error);
return { ...module, document_types: [] };
}
})
);
// console.log('✅ [getEntryModules] 入口模块数据(含文档类型):', JSON.stringify(modulesWithTypes));
// 默认会多加一个 智慧法务助手 入口 默认所有人都可以用,看到
modulesWithTypes.push({
"id": 0,
"name": "智慧法务助手",
"description": "智慧法务助手",
"path": "entryModule/assistant",
"areas": [],
"created_at": "2025-11-18T21:33:33.857417+08:00",
"updated_at": "2025-11-18T22:28:51.819722+08:00",
"document_types": [
{
"id": 0,
"name": "空",
"code": "空"
}
]
}
)
return modulesWithTypes;
return modules;
} catch (error) {
console.error('❌ [getEntryModules] 获取入口模块失败:', error instanceof Error ? error.message : String(error));
return [];
@@ -525,4 +445,3 @@ export async function getTopRiskUsers(
return { available: false, total: 0, items: [] };
}
}
+2 -2
View File
@@ -64,7 +64,7 @@ export interface LoginResponse {
* @returns 登录响应(包含 JWT token
*/
export async function loginWithOAuth(loginData: LoginRequest): Promise<LoginResponse> {
const loginUrl = `${API_BASE_URL}/auth/login`;
const loginUrl = `${API_BASE_URL}/api/auth/login`;
console.log("📝 [Login Client] 调用后端 OAuth 登录接口:", loginUrl);
@@ -116,7 +116,7 @@ export async function loginWithPassword(
username: string,
password: string
): Promise<LoginResponse> {
const loginUrl = `${API_BASE_URL}/auth/login`;
const loginUrl = `${API_BASE_URL}/api/auth/login`;
console.log("📝 [Login Client] 调用后端密码登录接口:", loginUrl);
+6 -6
View File
@@ -54,9 +54,9 @@ export const portConfigs: Record<string, Partial<ApiConfig>> = {
// documentUrl: 'http://nas.7bm.co:8096/docauditai/',
// uploadUrl: 'http://nas.7bm.co:8096/api/v2/documents',
// leaudit-platform 联调地址
baseUrl: 'http://172.15.0.59:8096',
documentUrl: 'http://172.15.0.59:8096/docauditai/',
uploadUrl: 'http://172.15.0.59:8096/api/upload',
baseUrl: 'http://172.16.0.59:8096',
documentUrl: 'http://172.16.0.59:8096/docauditai/',
uploadUrl: 'http://172.16.0.59:8096/api/upload',
collaboraUrl: 'http://172.16.0.58:9980',
appUrl: 'http://172.16.0.34:51703',
@@ -173,9 +173,9 @@ const configs: Record<string, ApiConfig> = {
// documentUrl: 'http://172.16.0.59:8096/docauditai/',
// uploadUrl: 'http://172.16.0.59:8096/api/v2/documents',
// leaudit-platform 联调地址
baseUrl: 'http://172.15.0.59:8096',
documentUrl: 'http://172.15.0.59:8096/docauditai/',
uploadUrl: 'http://172.15.0.59:8096/api/upload',
baseUrl: 'http://172.16.0.59:8096',
documentUrl: 'http://172.16.0.59:8096/docauditai/',
uploadUrl: 'http://172.16.0.59:8096/api/upload',
// baseUrl: 'http://172.16.0.84:8073', // FastAPI后端(包含/dify代理)
// documentUrl: 'http://172.16.0.84:8073/docauditai/',
// uploadUrl: 'http://172.16.0.84:8073/api/v2/documents',
+28 -44
View File
@@ -3,6 +3,7 @@ import { useNavigate, Form, useLoaderData } from '@remix-run/react';
import { type MetaFunction, type ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
import styles from "~/styles/pages/home.css?url";
import dayjs from 'dayjs';
import type { EntryModule } from '~/api/home/home';
import { getUserSession, logout } from "~/api/login/auth.server";
import { toastService } from '~/components/ui';
import { DOCUMENT_URL, CROSS_CHECKING_ONLY_MODE, CROSS_CHECKING_ONLY_PORT, getCurrentPort } from '~/config/api-config';
@@ -37,17 +38,13 @@ export async function loader({ request }: LoaderFunctionArgs) {
const { userRole, userInfo, frontendJWT } = await getUserSession(request);
// 🔑 获取用户地区并查询入口模块
const userArea = userInfo?.area || null;
// console.log('🔍 [Index Loader] 用户地区:', userArea);
// console.log('🔍 [Index Loader] 用户角色:', userRole);
let entryModules = [];
if (userRole && frontendJWT) {
let entryModules: EntryModule[] = [];
if (frontendJWT) {
const { getEntryModules } = await import('~/api/home/home');
entryModules = await getEntryModules(userRole,userArea, frontendJWT);
entryModules = await getEntryModules(frontendJWT);
console.log(`📦 [Index Loader] 获取到 ${entryModules.length} 个入口模块`);
} else {
console.warn('⚠️ [Index Loader] 用户角色为空,返回空模块列表');
console.warn('⚠️ [Index Loader] 缺少 JWT,返回空模块列表');
}
// 🔑 检查用户是否有系统设置权限
@@ -200,15 +197,14 @@ export default function Index() {
}, []);
// 处理模块点击
const handleModuleClick = (module: typeof loaderData.entryModules[0]) => {
const handleModuleClick = (module: EntryModule) => {
// 提取文档类型 IDs
const typeIds = module.document_types?.map(dt => dt.id) || [];
const typeIds = module.documentTypes.map((dt) => dt.id) || [];
// 🔑 验证文档类型(智慧法务助手除外)
if (module.name !== '智慧法务助手' && typeIds.length === 0) {
if (module.requiresDocumentTypes && typeIds.length === 0) {
toastService.error('该入口尚未关联文档类型,无法进入');
console.warn('⚠️ [Index] 模块未关联文档类型:', module.name);
return; // 阻止进入
return;
}
if (typeof window !== 'undefined') {
@@ -228,48 +224,30 @@ export default function Index() {
// 存储模块信息
sessionStorage.setItem('selectedModuleId', String(module.id));
sessionStorage.setItem('selectedModuleName', module.name);
sessionStorage.setItem('selectedModulePicPath', module.path)
sessionStorage.setItem('selectedModulePicPath', module.iconPath || '')
}
// 🔑 根据模块名称决定跳转路径
let targetPath = '/home'; // 默认跳转到首页
if (module.name.includes('合同')) {
// 合同相关模块 → 跳转到合同模板搜索
targetPath = '/contract-template/search';
// console.log('📌 [Index] 合同模块,跳转到:', targetPath);
} else if (module.name === '智慧法务助手') {
// 智慧法务助手 → 跳转到 AI 对话
targetPath = '/chat-with-llm/chat';
sessionStorage.setItem('selectedModulePicPath', '/images/icon_assistant.png')
// console.log('📌 [Index] 智慧法务助手,跳转到:', targetPath);
} else {
// console.log('📌 [Index] 其他模块,跳转到:', targetPath);
const targetPath = module.targetPath || '/home';
if (targetPath === '/chat-with-llm/chat' && typeof window !== 'undefined') {
sessionStorage.setItem('selectedModulePicPath', module.iconPath || '/images/icon_assistant.png');
}
navigate(targetPath);
};
// 处理键盘事件
const handleKeyDown = (module: typeof loaderData.entryModules[0], e: React.KeyboardEvent<HTMLDivElement>) => {
const handleKeyDown = (module: EntryModule, e: React.KeyboardEvent<HTMLDivElement>) => {
if (e.key === 'Enter' || e.key === ' ') {
handleModuleClick(module);
}
};
// 获取模块图标(根据模块 path 或 id)
const getModuleIcon = (module: typeof loaderData.entryModules[0]) => {
// 根据 path 判断图标
// if (module.path?.includes('ht')) {
// return '/images/icon_hetong.png';
// } else if (module.path?.includes('aj')) {
// return '/images/icon_anjuan.png';
// } else if (module.path?.includes('nw')) {
// return '/images/icon_assistant.png';
// }
// 默认图标
if (module.path){
return `${DOCUMENT_URL}${module.path}`
const getModuleIcon = (module: EntryModule) => {
if (module.iconPath){
if (module.iconPath.startsWith('/images/')) {
return module.iconPath;
}
return `${DOCUMENT_URL}${module.iconPath}`;
}
return '/images/icon_assistant.png';
};
@@ -439,14 +417,20 @@ export default function Index() {
/* 正常模式:显示所有入口模块 */
loaderData.entryModules && loaderData.entryModules.length > 0 ? (
<>
{loaderData.entryModules.map((module) => {
const isLLMModule = module.name === '智慧法务助手';
{loaderData.entryModules.map((module: EntryModule) => {
const isLLMModule = module.targetPath === '/chat-with-llm/chat';
const isCrossCheckingModule = module.targetPath === '/cross-checking';
// 🔑 如果是智慧法务助手且用户没有访问权限,则不渲染该模块
if (isLLMModule && !loaderData.hasChatLLMAccess) {
return null;
}
// 交叉评查已在下面独立渲染,避免首页重复出现两张卡片
if (isCrossCheckingModule) {
return null;
}
return (
<div
key={module.id}
+2 -13
View File
@@ -212,19 +212,8 @@ export async function loader({ request }: LoaderFunctionArgs) {
const frontendJWT = loginResponse.data.access_token;
const savedUserInfo = loginResponse.data.user_info;
const backExpiresIn = loginResponse.data.expires_in || (60 * 60 * 8)
// 🔑 提取后端返回的签发时间并转换为时间戳
let tokenIssuedAt = Date.now(); // 默认使用当前时间
if (loginResponse.data.issued_time) {
try {
// 后端返回格式:"2025-11-18 17:41:06"
// 转换为时间戳(毫秒)
tokenIssuedAt = new Date(loginResponse.data.issued_time.replace(' ', 'T')).getTime();
console.log("📅 [Callback] 使用后端返回的签发时间:", loginResponse.data.issued_time, "→", tokenIssuedAt);
} catch (error) {
console.warn("⚠️ [Callback] 无法解析 issued_time,使用当前时间:", error);
}
}
// 直接使用当前服务端时间作为 session 签发时间,避免后端返回的本地时间字符串被 Node 以不同时区解析
const tokenIssuedAt = Date.now();
// 更新userInfo以包含数据库ID、JWTuser_role 从后端返回)
const enhancedUserInfo = {
+6 -16
View File
@@ -103,10 +103,11 @@ export async function action({ request }: ActionFunctionArgs) {
const response = await loginWithPassword(username.trim(), password.trim());
if (!response.success || !response.data) {
console.error("❌ [Login Action] 登录失败:", response.error);
const loginError = response.error || response.message || "登录失败,请检查用户名和密码";
console.error("❌ [Login Action] 登录失败:", loginError);
return Response.json({
success: false,
error: response.error || "登录失败,请检查用户名和密码"
error: loginError
}, { status: 401 });
}
@@ -133,25 +134,14 @@ export async function action({ request }: ActionFunctionArgs) {
// if(!user_info.area){
// user_info.area = '梅州'
// }
// 🔑 将后端返回的 issued_time 转换为时间戳(毫秒)
let tokenIssuedAt = Date.now(); // 默认使用当前时间
if (issued_time) {
try {
// 后端返回格式:"2025-11-18 17:41:06"
// 转换为时间戳(毫秒)
tokenIssuedAt = new Date(issued_time.replace(' ', 'T')).getTime();
console.log("📅 [Login Action] 使用后端返回的签发时间:", issued_time, "→", tokenIssuedAt);
} catch (error) {
console.warn("⚠️ [Login Action] 无法解析 issued_time,使用当前时间:", error);
}
}
// 直接使用当前服务端时间作为 session 签发时间,避免后端返回的本地时间字符串被 Node 以不同时区解析
const tokenIssuedAt = Date.now();
console.log("✅ [Login Action] 登录成功,准备创建 session");
// console.log("📦 [Login Action] 后端返回完整数据:", response.data);
console.log("👤 [Login Action] 用户角色:", user_info.user_role); // 应该是 "admin"
console.log("⏰ [Login Action] Token 有效期:", expires_in, "秒 (", expires_in / 3600, "小时)");
// ✅ 账密登录直接写入 Cookie Session 并跳首页
// localStorage 由 root 中的客户端会话引导逻辑补写,避免 callback 跳转链路卡住
return createUserSession({