This commit is contained in:
gr
2026-11-04 10:14:23 +08:00
parent f7f323462c
commit b7c3a962dd
759 changed files with 74649 additions and 4421 deletions
@@ -36,6 +36,7 @@ export namespace AuthApi {
}
}
/** ZYT 与客服本地账号共用密码登录;凭证只放 POST body,由服务端选择验证来源。 */
export async function loginApi(data: AuthApi.LoginParams) {
const resp = await requestClient.post<AuthApi.BackendLoginResult>(
'/auth/login',
+18 -9
View File
@@ -17,6 +17,7 @@ import { message } from 'ant-design-vue';
import { t } from '#/locales/t';
import { useAuthStore } from '#/store';
import { requestBelongsToSession } from '#/utils/authorization-sync';
import { refreshTokenApi } from './core';
import { responseErrorMessage } from './error-message';
@@ -109,15 +110,23 @@ function createRequestClient(baseURL: string, options?: RequestClientOptions) {
);
// token过期的处理
client.addResponseInterceptor(
authenticateResponseInterceptor({
client,
doReAuthenticate,
doRefreshToken,
enableRefreshToken: preferences.app.enableRefreshToken,
formatToken,
}),
);
const authentication = authenticateResponseInterceptor({
client,
doReAuthenticate,
doRefreshToken,
enableRefreshToken: preferences.app.enableRefreshToken,
formatToken,
});
client.addResponseInterceptor({
...authentication,
rejected: (error) => {
// A delayed 401 from a previous account must not log out the new account.
if (!requestBelongsToSession(error?.config?.headers?.Authorization, useAccessStore().accessToken)) {
return Promise.reject(error);
}
return authentication.rejected?.(error);
},
});
// 通用的错误处理,如果没有进入上面的错误处理逻辑,就会进入这里
client.addResponseInterceptor(
+2
View File
@@ -17,6 +17,7 @@ import { initComponentAdapter } from './adapter/component';
import { initSetupVbenForm } from './adapter/form';
import App from './app.vue';
import { router } from './router';
import { installAuthorizationSync } from './router/authorization-sync';
async function bootstrap(namespace: string) {
// 初始化组件适配器
@@ -57,6 +58,7 @@ async function bootstrap(namespace: string) {
// 配置路由及路由守卫
app.use(router);
app.onUnmount(installAuthorizationSync(router));
// 配置Motion插件
const { MotionPlugin } = await import('@vben/plugins/motion');
@@ -0,0 +1,133 @@
import type { UserInfo } from '@vben/types';
import type { RouteRecordRaw, Router } from 'vue-router';
import { watch } from 'vue';
import { createMemoryHistory, createRouter } from 'vue-router';
import { getTabKey, useAccessStore, useTabbarStore, useUserStore } from '@vben/stores';
import { getUserInfoApi } from '#/api/core/user';
import { createAuthorizationSync } from '#/utils/authorization-sync';
import { generateAccess } from './access';
import { accessRoutes, routes } from './routes';
function copyRoutes(input: RouteRecordRaw[]): RouteRecordRaw[] {
return input.map((route) => ({ ...route, meta: { ...route.meta },
children: route.children ? copyRoutes(route.children) : undefined } as RouteRecordRaw));
}
// Vben adds dynamic children into the normalized Root. Keep a clean template,
// including component functions, rather than cloning that mutated tree later.
const staticRoutes = copyRoutes(routes).map((route) => route.path === '/' ? { ...route, children: [] } : route);
const installations = new WeakMap<Router, () => void>();
function routeNames(input: RouteRecordRaw[]): Set<string | symbol> {
return new Set(input.flatMap((route) => [
...(route.name ? [route.name] : []), ...routeNames(route.children ?? []),
]));
}
export function isAuthorizedPath(router: Router, path: string, codes: string[]) {
const target = router.resolve(path);
return target.matched.length > 0 && target.name !== 'FallbackNotFound' && target.matched.every((record) => {
const authority = record.meta.authority;
return !Array.isArray(authority) || authority.length === 0 || authority.some((code) => codes.includes(code));
});
}
/** Reconcile by name/path, retaining authorized matcher/component instances. */
export function reconcileAccessRoutes(router: Router, nextRoutes: RouteRecordRaw[]) {
const staticNames = routeNames(staticRoutes);
const desired = routeNames(nextRoutes);
const root = router.getRoutes().find((route) => route.path === '/');
if (!root?.name) throw new Error('Missing application root route');
for (const record of router.getRoutes()) {
if (record.name && !staticNames.has(record.name) && !desired.has(record.name)) router.removeRoute(record.name);
}
function install(input: RouteRecordRaw[], parent: string | symbol) {
for (const route of input) {
const parentPath = router.getRoutes().find((record) => record.name === parent)?.path ?? '/';
const expectedPath = route.path.startsWith('/') ? route.path : `${parentPath.replace(/\/$/, '')}/${route.path}`;
let existing = route.name ? router.getRoutes().find((record) => record.name === route.name) : undefined;
if (existing && existing.path !== expectedPath) {
router.removeRoute(existing.name!);
existing = undefined;
}
if (existing) {
// Existing authorized pages keep their resolved components and drafts.
// Recurse so a grant adds missing siblings without replacing their parent.
Object.assign(existing.meta, route.meta);
install(route.children ?? [], existing.name!);
} else if (route.meta?.noBasicLayout) {
router.addRoute(route);
} else {
router.addRoute(parent, route);
}
}
}
install(nextRoutes, root.name);
// Keep Vben's source tree exact as well as Vue Router's matcher table.
root.children.splice(0, root.children.length, ...nextRoutes.filter((route) => !route.meta?.noBasicLayout));
}
export function pruneAuthorizationTabs(router: Router, codes: string[], tabbar: ReturnType<typeof useTabbarStore>) {
tabbar.tabs = tabbar.tabs.filter((tab) => isAuthorizedPath(router, tab.fullPath || tab.path, codes));
tabbar.visitHistory.retain(tabbar.tabs.map((tab) => tab.key || getTabKey(tab)));
for (const [key, cached] of tabbar.cachedRoutes) {
if (!isAuthorizedPath(router, cached.route.fullPath || cached.route.path, codes)) tabbar.removeCachedRoute(key);
}
for (const name of tabbar.excludeCachedTabs) {
if (!router.hasRoute(name)) tabbar.excludeCachedTabs.delete(name);
}
void tabbar.updateCacheTabs();
}
/** Install once for this app, after Pinia and Router are available. */
export function installAuthorizationSync(router: Router) {
installations.get(router)?.();
const access = useAccessStore();
const user = useUserStore();
const tabbar = useTabbarStore();
const sync = createAuthorizationSync({
window, document,
fetch: getUserInfoApi,
getCodes: () => access.accessCodes,
getSession: () => access.accessToken && access.isAccessChecked && user.userInfo?.userId
? { token: access.accessToken, userId: String(user.userInfo.userId) } : undefined,
async prepare(info: UserInfo) {
const preparedRouter = createRouter({ history: createMemoryHistory(), routes: copyRoutes(staticRoutes) });
return generateAccess({ roles: info.roles ?? [], router: preparedRouter, routes: accessRoutes });
},
apply(info, snapshot) {
const codes = info.roles ?? [];
user.setUserInfo(info);
access.setAccessCodes(codes);
if (!snapshot) return;
reconcileAccessRoutes(router, snapshot.accessibleRoutes);
access.setAccessMenus(snapshot.accessibleMenus);
access.setAccessRoutes(snapshot.accessibleRoutes);
pruneAuthorizationTabs(router, codes, tabbar);
// Keep an authorized current component mounted; replacing its route would
// discard unsaved forms merely because a different permission changed.
if (!isAuthorizedPath(router, router.currentRoute.value.fullPath, codes)) {
return router.replace('/group/welcome').then(() => {});
}
},
});
const unwatch = watch(() => JSON.stringify([
access.accessToken, user.userInfo?.userId, access.isAccessChecked,
]), () => {
sync.stop();
if (access.accessToken && user.userInfo?.userId && access.isAccessChecked) sync.start();
}, { immediate: true, flush: 'sync' });
const dispose = () => {
unwatch();
sync.stop();
if (installations.get(router) === dispose) installations.delete(router);
};
installations.set(router, dispose);
return dispose;
}
@@ -40,7 +40,6 @@ const routes: RouteRecordRaw[] = [
icon: 'lucide:bot',
order: 0,
title: 'AI 模型',
authority: ['model:read', 'agent:read', 'stats:read'],
},
name: 'ModelCenter',
path: '/model',
@@ -94,7 +93,6 @@ const routes: RouteRecordRaw[] = [
icon: 'lucide:monitor-smartphone',
order: 1,
title: '桌面端',
authority: ['desktop-account:read', 'config:read'],
},
name: 'DesktopCenter',
path: '/desktop',
@@ -138,7 +136,6 @@ const routes: RouteRecordRaw[] = [
icon: 'lucide:messages-square',
order: 2,
title: '聊天归档',
authority: ['im:read', 'im:content:read', 'im:export', 'im:identity:write', 'im:storage:write'],
},
name: 'ArchiveCenter',
path: '/archive',
@@ -200,7 +197,6 @@ const routes: RouteRecordRaw[] = [
icon: 'lucide:shield',
order: 3,
title: '系统管理',
authority: ['user:read', 'audit:read'],
},
name: 'SystemCenter',
path: '/system',
@@ -212,7 +208,7 @@ const routes: RouteRecordRaw[] = [
meta: {
icon: 'lucide:key-round',
title: '角色权限',
authority: ['role:read', 'role:write'],
authority: ['role:read', 'user:read'],
},
},
{
@@ -262,4 +258,12 @@ const routes: RouteRecordRaw[] = [
},
];
// A business directory is visible when at least one of its pages is granted.
// Derive its codes so newly split page permissions cannot be hidden by stale parents.
for (const route of routes) {
if (route.meta && route.children?.length && route.children.every(child => child.meta?.authority?.length)) {
route.meta.authority = [...new Set(route.children.flatMap(child => child.meta?.authority || []))];
}
}
export default routes;
@@ -0,0 +1,91 @@
interface AuthorizationInfo {
roles?: string[];
userId: string;
}
interface Session {
token: string;
userId: string;
}
interface SyncOptions<Info extends AuthorizationInfo, Snapshot> {
apply: (info: Info, snapshot?: Snapshot) => Promise<void> | void;
document: Pick<Document, 'addEventListener' | 'removeEventListener' | 'visibilityState'>;
fetch: () => Promise<Info>;
getCodes: () => string[];
getSession: () => Session | undefined;
interval?: number;
prepare: (info: Info) => Promise<Snapshot>;
window: Pick<Window, 'addEventListener' | 'clearInterval' | 'removeEventListener' | 'setInterval'>;
}
function permissionKey(codes: string[]) {
return JSON.stringify([...new Set(codes)].sort());
}
/** Ignore failures from a request made by a different, already-ended session. */
export function requestBelongsToSession(authorization: unknown, token: null | string) {
return (authorization || null) === (token ? `Bearer ${token}` : null);
}
/** One foreground poller. Preparation never mutates the displayed router/stores. */
export function createAuthorizationSync<Info extends AuthorizationInfo, Snapshot>(options: SyncOptions<Info, Snapshot>) {
let active = false;
let epoch = 0;
let timer: number | undefined;
let pending: Promise<void> | undefined;
let appliedPermissions = permissionKey(options.getCodes());
function refresh(): Promise<void> {
if (!active || options.document.visibilityState !== 'visible') return Promise.resolve();
if (pending) return pending;
const session = options.getSession();
if (!session) return Promise.resolve();
const generation = epoch;
const current = () => {
const now = options.getSession();
return active && epoch === generation && now?.token === session.token && now.userId === session.userId;
};
const task = (async () => {
try {
const info = await options.fetch();
if (!current() || String(info.userId) !== session.userId) return;
const changed = permissionKey(info.roles ?? []) !== appliedPermissions;
const snapshot = changed ? await options.prepare(info) : undefined;
if (!current()) return;
await options.apply(info, snapshot);
if (current()) appliedPermissions = permissionKey(info.roles ?? []);
} catch {
// requestClient owns HTTP/401 handling. A later foreground poll can recover;
// failed background reads must never clear grants or replay a write.
}
})();
pending = task;
void task.finally(() => { if (pending === task) pending = undefined; });
return task;
}
const trigger = () => { void refresh(); };
function stop() {
active = false;
epoch += 1;
pending = undefined;
if (timer !== undefined) options.window.clearInterval(timer);
timer = undefined;
options.window.removeEventListener('focus', trigger);
options.document.removeEventListener('visibilitychange', trigger);
}
function start() {
if (active) return;
active = true;
epoch += 1;
appliedPermissions = permissionKey(options.getCodes());
options.window.addEventListener('focus', trigger);
options.document.addEventListener('visibilitychange', trigger);
timer = options.window.setInterval(trigger, options.interval ?? 3000);
trigger();
}
return { refresh, start, stop };
}
@@ -42,6 +42,15 @@ export function validateGroupConfig(config: GroupConfig, origin: string): GroupC
return config as GroupConfig & Required<Omit<GroupConfig, 'enabled'>>;
}
/** Reach the configured callback origin before storing its tab-bound PKCE proof. */
export function groupLoginEntry(config: GroupConfig, origin: string): string {
const callback = safeUrl(config?.redirect_uri);
validateGroupConfig(config, callback.origin);
const current = safeUrl(origin);
if (current.href !== `${current.origin}/`) throw new Error(t('集团登录地址配置无效'));
return callback.origin === current.origin ? '/auth/group-login' : callback.href;
}
function base64url(value: Uint8Array): string {
return btoa(String.fromCharCode(...value)).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
}
@@ -6,7 +6,7 @@ import { Alert, Button, Spin } from 'ant-design-vue';
import { getGroupConfigApi } from '#/api';
import { useAuthStore } from '#/store';
import { beginGroupLogin, consumeGroupCallback, GROUP_TRANSACTION_KEY } from '#/utils/group-sso';
import { beginGroupLogin, consumeGroupCallback, groupLoginEntry, GROUP_TRANSACTION_KEY } from '#/utils/group-sso';
const error = ref('');
const router = useRouter();
@@ -24,7 +24,13 @@ onMounted(async () => {
await auth.authGroupLogin(transaction);
} else {
sessionStorage.removeItem(GROUP_TRANSACTION_KEY);
const target = await beginGroupLogin(await getGroupConfigApi());
const config = await getGroupConfigApi();
const entry = groupLoginEntry(config, window.location.origin);
if (entry !== '/auth/group-login') {
window.location.replace(entry);
return;
}
const target = await beginGroupLogin(config);
window.location.assign(target);
}
} catch {
@@ -1,14 +1,9 @@
<script lang="ts" setup>
import type { VbenFormSchema } from '@vben/common-ui';
import { computed, onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';
import { computed } from 'vue';
import { AuthenticationLogin, z } from '@vben/common-ui';
import { Button } from 'ant-design-vue';
import { getGroupConfigApi } from '#/api';
import { validateGroupConfig } from '#/utils/group-sso';
import { t } from '#/locales/t';
import { useAuthStore } from '#/store';
@@ -16,14 +11,6 @@ import { useAuthStore } from '#/store';
defineOptions({ name: 'Login' });
const authStore = useAuthStore();
const router = useRouter();
const groupEnabled = ref(false);
onMounted(async () => {
try {
validateGroupConfig(await getGroupConfigApi(), window.location.origin);
groupEnabled.value = true;
} catch { groupEnabled.value = false; }
});
// 模板自带的演示账号下拉、滑块验证码、手机号/扫码/第三方登录、注册和找回密码
// 都删掉了——后端没有对应的接口,留着只会让人点进死路。滑块验证码尤其要注意:
@@ -31,14 +18,14 @@ onMounted(async () => {
const formSchema = computed((): VbenFormSchema[] => [
{
component: 'VbenInput',
componentProps: { placeholder: t('用户名') },
componentProps: { placeholder: t('ZYT 账号或客服本地账号') },
fieldName: 'username',
label: t('用户名'),
rules: z.string().min(1, { message: t('请输入用户名') }),
label: t('账号'),
rules: z.string().min(1, { message: t('请输入账号') }),
},
{
component: 'VbenInputPassword',
componentProps: { placeholder: t('密码') },
componentProps: { placeholder: t('ZYT 密码或客服本地密码') },
fieldName: 'password',
label: t('密码'),
rules: z.string().min(1, { message: t('请输入密码') }),
@@ -54,15 +41,10 @@ const formSchema = computed((): VbenFormSchema[] => [
:show-forget-password="false"
:show-qrcode-login="false"
:show-register="false"
:show-remember-me="false"
:show-third-party-login="false"
:sub-title="t('请使用管理员分配的账号登录')"
:sub-title="t('ZYT 首次登录为基础用户,业务权限由客服管理员分配。')"
:title="t('真羊 AI 客服 · 管理后台')"
@submit="authStore.authLogin"
>
<template #third-party-login>
<Button v-if="groupEnabled" block class="mt-4" @click="router.push('/auth/group-login')">
{{ t('使用集团账号登录') }}
</Button>
</template>
</AuthenticationLogin>
/>
</template>
@@ -27,8 +27,9 @@ const open = ref(false);
const isNew = ref(false);
const form = reactive({ code: '', name: '', permissions: [] as string[] });
const protectedRole = (code: string) => code === 'admin' || code === 'zyt_basic';
// 新增和修改是两个按钮:只能新增的人打开已有角色只能看
const readonly = computed(() => !(isNew.value ? canCreate.value : canWrite.value) || form.code === 'admin');
const readonly = computed(() => !(isNew.value ? canCreate.value : canWrite.value) || protectedRole(form.code));
/** 一级菜单 → 页面 → 权限码,和左侧菜单一一对应。 */
const grouped = computed(() => groupPermissions(permissions.value));
@@ -49,6 +50,7 @@ function expandAll() {
}
function onCheck(keys: unknown) {
if (readonly.value) return;
// 不是严格模式时 antd 给的是数组;兜底处理 { checked } 形状
const list = Array.isArray(keys) ? keys : ((keys as { checked?: (number | string)[] }).checked ?? []);
form.permissions = applyTreeCheck(form.permissions, list, visibleCodes.value, permissions.value);
@@ -98,10 +100,11 @@ async function submit() {
const known = new Set(permissions.value.map((item) => item.code));
roles.value = (await saveRole({ ...form, permissions: form.permissions.filter((code) => known.has(code)) })).roles;
open.value = false;
message.success(t('已保存,权限立即生效(无需重启,也无需重新登录)'));
message.success(t('已保存,后端权限立即生效;在线用户的菜单和按钮将在数秒内自动更新。'));
}
async function remove(row: RoleItem) {
if (!canDelete.value || protectedRole(row.code) || row.builtin || row.user_count > 0) return;
roles.value = (await deleteRole(row.code)).roles;
message.success(t('已删除'));
}
@@ -125,7 +128,7 @@ onMounted(load);
type="info"
show-icon
:message="t('权限按左侧菜单组织:菜单 → 页面 → 页面里的每个按钮')"
:description="t('改完立刻生效——不用重启服务,用户也不用重新登录。管理员角色不可削权(削了就没人能加回来),内置角色和仍有人在用的角色不可删除。要新增权限点或左侧菜单链接,去「系统管理 → 权限菜单」。')"
:description="t('后端权限修改后立即生效,无需重启或重新登录;在线用户的菜单和按钮将在数秒内自动更新,切回窗口时立即同步。管理员和集团基础用户角色只读,内置角色和仍有人在用的角色不可删除。要新增权限点或左侧菜单链接,去「系统管理 → 权限菜单」。')"
/>
<Card :title="t('角色与权限')">
<template #extra>
@@ -158,12 +161,12 @@ onMounted(load);
</template>
<template v-else-if="column.key === 'action'">
<Button type="link" size="small" @click="openEdit(record as RoleItem)">
{{ canWrite && record.code !== 'admin' ? t('编辑') : t('查看') }}
{{ canWrite && !protectedRole(record.code) ? t('编辑') : t('查看') }}
</Button>
<Popconfirm :title="t('确定删除这个角色?')" @confirm="remove(record as RoleItem)">
<Button
type="link" size="small" danger
:disabled="!canDelete || record.builtin || record.user_count > 0"
:disabled="!canDelete || protectedRole(record.code) || record.builtin || record.user_count > 0"
>
{{ t('删除') }}
</Button>
@@ -190,6 +193,9 @@ onMounted(load);
<p v-if="form.code === 'admin'" class="mb-2 text-xs text-gray-500">
{{ t('管理员始终拥有全部权限(包括以后新增的),不能修改。') }}
</p>
<p v-else-if="form.code === 'zyt_basic'" class="mb-2 text-xs text-gray-500">
{{ t('集团基础用户固定无业务权限,不能修改。请到「系统管理 → 用户管理」为账号分配其他业务角色。') }}
</p>
<div class="mb-2 flex flex-wrap items-center gap-2">
<Input v-model:value="keyword" allow-clear size="small" class="w-60" :placeholder="t('搜索按钮名称或权限码')"
@change="expandAll" />