mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 13:09:19 +08:00
feat: SSE 推送权限变更并自动刷新菜单与权限码
This commit is contained in:
@@ -8,6 +8,7 @@ export const RealtimeSseEvent = {
|
||||
CONNECTED: 'message',
|
||||
PING: 'ping',
|
||||
PDD_ORDER_FULL_SYNC_PROGRESS: 'pdd_order_full_sync_progress',
|
||||
ACCESS_CHANGED: 'access_changed',
|
||||
} as const;
|
||||
|
||||
export type RealtimeSseEventName =
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<script lang="ts" setup>
|
||||
import type { NotificationItem } from '@vben/layouts';
|
||||
|
||||
import { computed, onMounted, ref, watch } from 'vue';
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
|
||||
import { AuthenticationLoginExpiredModal } from '@vben/common-ui';
|
||||
@@ -19,6 +19,7 @@ import { useAccessStore, useUserStore } from '@vben/stores';
|
||||
import SwitchAccountModal from '#/components/SwitchAccountModal.vue';
|
||||
import SwitchCompanyModal from '#/components/SwitchCompanyModal.vue';
|
||||
import { usePermission } from '#/composables/use-permission';
|
||||
import { RealtimeSseEvent } from '#/api/notify/sse';
|
||||
import { useAuthStore, useRealtimeStore } from '#/store';
|
||||
import LoginForm from '#/views/_core/authentication/login.vue';
|
||||
|
||||
@@ -69,12 +70,33 @@ const showDot = computed(() =>
|
||||
notifications.value.some((item) => !item.isRead),
|
||||
);
|
||||
|
||||
// 登录布局挂载:已登录才建 SSE
|
||||
// 登录布局挂载:已登录才建 SSE,并订阅权限变更
|
||||
let accessChangedHandler: ((event: MessageEvent) => void) | null = null;
|
||||
|
||||
onMounted(() => {
|
||||
if (!accessStore.accessToken) {
|
||||
return;
|
||||
}
|
||||
realtimeStore.start();
|
||||
|
||||
accessChangedHandler = (event: MessageEvent) => {
|
||||
let ts: number | undefined;
|
||||
try {
|
||||
const data = JSON.parse(event.data as string) as { ts?: number };
|
||||
ts = typeof data?.ts === 'number' ? data.ts : undefined;
|
||||
} catch {
|
||||
// ignore parse error,仍尝试刷新
|
||||
}
|
||||
void authStore.refreshAccess(ts);
|
||||
};
|
||||
realtimeStore.on(RealtimeSseEvent.ACCESS_CHANGED, accessChangedHandler);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
if (accessChangedHandler) {
|
||||
realtimeStore.off(RealtimeSseEvent.ACCESS_CHANGED, accessChangedHandler);
|
||||
accessChangedHandler = null;
|
||||
}
|
||||
});
|
||||
|
||||
// 切换账户模态框引用
|
||||
|
||||
@@ -61,7 +61,10 @@ function filterMissingPageRoutes(
|
||||
return walk(routes);
|
||||
}
|
||||
|
||||
async function generateAccess(options: GenerateMenuAndRoutesOptions) {
|
||||
async function generateAccess(
|
||||
options: GenerateMenuAndRoutesOptions & { silent?: boolean },
|
||||
) {
|
||||
const { silent, ...rest } = options;
|
||||
const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue');
|
||||
|
||||
const layoutMap: ComponentRecordType = {
|
||||
@@ -70,12 +73,14 @@ async function generateAccess(options: GenerateMenuAndRoutesOptions) {
|
||||
};
|
||||
|
||||
return await generateAccessible(preferences.app.accessMode, {
|
||||
...options,
|
||||
...rest,
|
||||
fetchMenuListAsync: async () => {
|
||||
message.loading({
|
||||
content: `${$t('common.loadingMenu')}...`,
|
||||
duration: 1.5,
|
||||
});
|
||||
if (!silent) {
|
||||
message.loading({
|
||||
content: `${$t('common.loadingMenu')}...`,
|
||||
duration: 1.5,
|
||||
});
|
||||
}
|
||||
try {
|
||||
const routes = await getUserMenuApi();
|
||||
return filterMissingPageRoutes(routes || [], pageMap, layoutMap);
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
} from '#/api';
|
||||
import { $t } from '#/locales';
|
||||
import { useAppConfigStore } from '#/store/app-config';
|
||||
import { generateAccess } from '#/router/access';
|
||||
import { accessRoutes, coreRouteNames } from '#/router/routes';
|
||||
|
||||
export const useAuthStore = defineStore('auth', () => {
|
||||
const accessStore = useAccessStore();
|
||||
@@ -28,6 +30,9 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
const router = useRouter();
|
||||
|
||||
const loginLoading = ref(false);
|
||||
/** 防止 SSE 短时间连发导致并发重拉 */
|
||||
let accessRefreshing = false;
|
||||
let lastAccessRefreshTs = 0;
|
||||
|
||||
/**
|
||||
* 异步处理登录操作
|
||||
@@ -228,6 +233,97 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE access_changed 后重拉权限码与菜单路由(不整页刷新)。
|
||||
* @param eventTs 服务端 payload.ts,用于去重
|
||||
*/
|
||||
async function refreshAccess(eventTs?: number) {
|
||||
if (!accessStore.accessToken) {
|
||||
return;
|
||||
}
|
||||
if (typeof eventTs === 'number' && eventTs > 0 && eventTs <= lastAccessRefreshTs) {
|
||||
return;
|
||||
}
|
||||
if (accessRefreshing) {
|
||||
return;
|
||||
}
|
||||
accessRefreshing = true;
|
||||
try {
|
||||
await fetchAccessCodes();
|
||||
|
||||
const prevNames = collectRouteNames(accessStore.accessRoutes);
|
||||
const userInfo = userStore.userInfo;
|
||||
accessStore.setIsAccessChecked(false);
|
||||
const { accessibleMenus, accessibleRoutes } = await generateAccess({
|
||||
roles: userInfo?.roles ?? [],
|
||||
router,
|
||||
routes: accessRoutes,
|
||||
silent: true,
|
||||
});
|
||||
accessStore.setAccessMenus(accessibleMenus);
|
||||
accessStore.setAccessRoutes(accessibleRoutes);
|
||||
accessStore.setIsAccessChecked(true);
|
||||
|
||||
const nextNames = new Set(collectRouteNames(accessibleRoutes));
|
||||
for (const name of prevNames) {
|
||||
if (!nextNames.has(name) && router.hasRoute(name)) {
|
||||
router.removeRoute(name);
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof eventTs === 'number' && eventTs > 0) {
|
||||
lastAccessRefreshTs = eventTs;
|
||||
} else {
|
||||
lastAccessRefreshTs = Date.now();
|
||||
}
|
||||
|
||||
const current = router.currentRoute.value;
|
||||
const currentName = current.name as string | undefined;
|
||||
if (
|
||||
currentName &&
|
||||
!coreRouteNames.includes(currentName) &&
|
||||
currentName !== 'FallbackNotFound'
|
||||
) {
|
||||
const reachable = router.hasRoute(currentName);
|
||||
if (!reachable) {
|
||||
await router.replace(
|
||||
userInfo?.homePath || preferences.app.defaultHomePath,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
notification.info({
|
||||
duration: 3,
|
||||
message: '权限已更新',
|
||||
description: '菜单与权限码已自动刷新',
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn('刷新菜单/权限失败:', error);
|
||||
} finally {
|
||||
accessRefreshing = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 收集路由树中的 name,用于撤销权限后卸掉旧动态路由 */
|
||||
function collectRouteNames(routes: { name?: unknown; children?: any[] }[] | undefined) {
|
||||
const names: string[] = [];
|
||||
const walk = (list: { name?: unknown; children?: any[] }[] | undefined) => {
|
||||
if (!list?.length) {
|
||||
return;
|
||||
}
|
||||
for (const r of list) {
|
||||
if (typeof r.name === 'string' && r.name) {
|
||||
names.push(r.name);
|
||||
}
|
||||
if (r.children?.length) {
|
||||
walk(r.children);
|
||||
}
|
||||
}
|
||||
};
|
||||
walk(routes);
|
||||
return names;
|
||||
}
|
||||
|
||||
function $reset() {
|
||||
loginLoading.value = false;
|
||||
}
|
||||
@@ -240,5 +336,6 @@ export const useAuthStore = defineStore('auth', () => {
|
||||
fetchUserInfo,
|
||||
loginLoading,
|
||||
logout,
|
||||
refreshAccess,
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user