Commit 2deba187 by User

登录逻辑修改

parent a3d99ee4
<!doctype html>
<html lang="zh-cmn-Hans">
<head>
<meta name="buildTime" content="2025-04-15 09:32:40">
<meta name="buildTime" content="2025-04-25 14:26:56">
<meta charset="UTF-8" />
<link rel="icon" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="color-scheme" content="light dark" />
<title>VueDashboard</title>
<script type="module" crossorigin src="/Content/VueDashboardUi/VueDashboard1/assets/index-DDJd5Man.js"></script>
<script type="module" crossorigin src="/Content/VueDashboardUi/VueDashboard1/assets/index-BNcrQaoq.js"></script>
<link rel="stylesheet" crossorigin href="/Content/VueDashboardUi/VueDashboard1/assets/index-DhhgO4aJ.css">
</head>
<body>
......
......@@ -42,7 +42,6 @@ export function useRouterPush(inSetup = true) {
}
function routerPushByKeyWithMetaQuery(key: RouteKey) {
const allRoutes = router.getRoutes();
// 获取所有路由
......
......@@ -12,35 +12,45 @@ import { setupRouter } from './router';
import { setupI18n } from './locales';
import App from './App.vue';
let timeoutHandle: string | number | NodeJS.Timeout | undefined;
const INACTIVITY_TIMEOUT = 20 * 60 * 1000;
function handleLogout(app: any) {
localStg.remove('token');
localStg.remove('refreshToken');
localStg.remove('userInfo');
app.config.globalProperties.$router.push('/login/pwd-login');
}
// let timeoutHandle: string | number | NodeJS.Timeout | undefined;
// const INACTIVITY_TIMEOUT = 20 * 60 * 1000;
function checkLastActivity(app: any) {
const lastActivity = localStorage.getItem('lastActivityTime');
if (lastActivity) {
const timeDiff = Date.now() - Number.parseInt(lastActivity, 10);
if (timeDiff > INACTIVITY_TIMEOUT) {
handleLogout(app);
}
}
}
// function handleLogout(app: any) {
// localStg.remove('token');
// localStg.remove('refreshToken');
// localStg.remove('userInfo');
// app.config.globalProperties.$router.push('/login/pwd-login');
// }
function startInactivityTimer(app: any) {
clearTimeout(timeoutHandle);
localStorage.setItem('lastActivityTime', Date.now().toString());
timeoutHandle = setTimeout(() => handleLogout(app), INACTIVITY_TIMEOUT);
}
// function checkLastActivity(app: any) {
// const lastActivity = localStorage.getItem('lastActivityTime');
// if (lastActivity) {
// const timeDiff = Date.now() - Number.parseInt(lastActivity, 10);
// if (timeDiff > INACTIVITY_TIMEOUT) {
// handleLogout(app);
// }
// }
// }
function resetInactivityTimer(app: any) {
startInactivityTimer(app);
}
// function startInactivityTimer(app: any) {
// clearTimeout(timeoutHandle);
// localStorage.setItem('lastActivityTime', Date.now().toString());
// timeoutHandle = setTimeout(() => handleLogout(app), INACTIVITY_TIMEOUT);
// }
// function resetInactivityTimer(app: any) {
// startInactivityTimer(app);
// }
// 检查认证状态
// function checkAuthStatus(app: any) {
// if (window.uiGlobalConfig?.IsAuthenticated === false) {
// localStg.remove('token');
// localStg.remove('refreshToken');
// localStg.remove('userInfo');
// app.config.globalProperties.$router.push('/login/pwd-login');
// }
// }
async function setupApp() {
setupLoading();
......@@ -53,17 +63,20 @@ async function setupApp() {
await setupRouter(app);
setupI18n(app);
// 检查认证状态
// checkAuthStatus(app);
// 检查上次活动时间
checkLastActivity(app);
// checkLastActivity(app);
// 监听用户的操作
window.addEventListener('mousemove', () => resetInactivityTimer(app));
window.addEventListener('keydown', () => resetInactivityTimer(app));
window.addEventListener('click', () => resetInactivityTimer(app));
window.addEventListener('scroll', () => resetInactivityTimer(app));
// window.addEventListener('mousemove', () => resetInactivityTimer(app));
// window.addEventListener('keydown', () => resetInactivityTimer(app));
// window.addEventListener('click', () => resetInactivityTimer(app));
// window.addEventListener('scroll', () => resetInactivityTimer(app));
// 启动计时器
startInactivityTimer(app);
// startInactivityTimer(app);
app.use(VueGridLayout);
......@@ -75,9 +88,9 @@ async function setupApp() {
}
// 页面卸载时保存最后活动时间
window.addEventListener('beforeunload', () => {
localStorage.setItem('lastActivityTime', Date.now().toString());
});
// window.addEventListener('beforeunload', () => {
// localStorage.setItem('lastActivityTime', Date.now().toString());
// });
setTimeout(() => {
setupApp();
......
......@@ -31,22 +31,21 @@ export function createRouteGuard(router: Router) {
const loginRoute: RouteKey = 'login';
const noAuthorizationRoute: RouteKey = '403';
const isLogin = Boolean(localStg.get('token'));
const isAuthenticated = window.uiGlobalConfig?.IsAuthenticated !== false;
const needLogin = !to.meta.constant;
const routeRoles = to.meta.roles || [];
const hasRole = authStore.userInfo.roles.some(role => routeRoles.includes(role));
const hasAuth = authStore.isStaticSuper || !routeRoles.length || hasRole;
// 如果未认证,清除token并跳转登录页
if (!isAuthenticated && needLogin) {
localStg.remove('token');
next({ name: loginRoute, query: { redirect: to.fullPath } });
return;
}
const routeSwitches: CommonType.StrategicPattern[] = [
// if it is login route when logged in, then switch to the root page
{
condition: isLogin && to.name === loginRoute,
callback: () => {
next({ name: rootRoute });
}
},
// if it is constant route, then it is allowed to access directly
{
condition: !needLogin,
......@@ -54,23 +53,16 @@ export function createRouteGuard(router: Router) {
handleRouteSwitch(to, from, next);
}
},
// if the route need login but the user is not logged in, then switch to the login page
{
condition: !isLogin && needLogin,
callback: () => {
next({ name: loginRoute, query: { redirect: to.fullPath } });
}
},
// if the user is logged in and has authorization, then it is allowed to access
// if the user has authorization, then it is allowed to access
{
condition: isLogin && needLogin && hasAuth,
condition: needLogin && hasAuth,
callback: () => {
handleRouteSwitch(to, from, next);
}
},
// if the user is logged in but does not have authorization, then switch to the 403 page
// if the user does not have authorization, then switch to the 403 page
{
condition: isLogin && needLogin && !hasAuth,
condition: needLogin && !hasAuth,
callback: () => {
next({ name: noAuthorizationRoute });
}
......@@ -146,20 +138,6 @@ async function initRoute(to: RouteLocationNormalized): Promise<RouteLocationRaw
}
// if the auth route is not initialized, then initialize the auth route
const isLogin = Boolean(localStg.get('token'));
// initialize the auth route requires the user to be logged in, if not, redirect to the login page
if (!isLogin) {
const loginRoute: RouteKey = 'login';
const query = getRouteQueryOfLoginRoute(to, routeStore.routeHome);
const location: RouteLocationRaw = {
name: loginRoute,
query
};
return location;
}
await authStore.initUserInfo();
// initialize the auth route
......
import { json } from 'node:stream/consumers';
import { computed, reactive, ref } from 'vue';
import { useRoute } from 'vue-router';
import { defineStore } from 'pinia';
......@@ -9,8 +10,7 @@ import { localStg } from '@/utils/storage';
import { $t } from '@/locales';
import { useRouteStore } from '../route';
import { useTabStore } from '../tab';
import { clearAuthStorage, getToken, getLocalUserInfo } from './shared';
import { json } from 'node:stream/consumers';
import { clearAuthStorage, getLocalUserInfo, getToken } from './shared';
export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
const route = useRoute();
......@@ -51,6 +51,10 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
clearAuthStorage();
// 重置store
authStore.$reset();
// 设置未认证状态
if (window.uiGlobalConfig) {
window.uiGlobalConfig.IsAuthenticated = false;
}
if (!route.meta.constant) {
await toLogin();
......@@ -63,6 +67,10 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
// 即使退出接口失败,也要清除本地状态
clearAuthStorage();
authStore.$reset();
// 设置未认证状态
if (window.uiGlobalConfig) {
window.uiGlobalConfig.IsAuthenticated = false;
}
if (!route.meta.constant) {
await toLogin();
......@@ -88,20 +96,29 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
const pass = await loginByToken(loginToken);
if (pass) {
await routeStore.initAuthRoute();
if (redirect) {
await redirectFromLogin();
// 设置认证状态为true
if (window.uiGlobalConfig) {
window.uiGlobalConfig.IsAuthenticated = true;
}
// 初始化路由
await routeStore.initAuthRoute();
// 等待路由初始化完成
if (routeStore.isInitAuthRoute) {
// 强制刷新页面
window.location.reload();
window.$notification?.success({
title: $t('page.login.common.loginSuccess'),
content: $t('page.login.common.welcomeBack', { FullName: userInfo.FullName }),
duration: 4500
});
if (redirect) {
// 先执行重定向
await redirectFromLogin();
// 延迟一下再刷新,确保重定向已完成
setTimeout(() => {
window.location.reload();
window.$notification?.success({
title: $t('page.login.common.loginSuccess'),
content: $t('page.login.common.welcomeBack', { FullName: userInfo.FullName }),
duration: 4500
});
}, 500);
}
}
}
} else {
......@@ -144,13 +161,19 @@ export const useAuthStore = defineStore(SetupStoreId.Auth, () => {
async function initUserInfo() {
const hasToken = getToken();
const hasUserInfo = JSON.parse(getLocalUserInfo());
const userInfoStr = getLocalUserInfo();
if (hasToken) {
token.value = hasUserInfo.FullName;
Object.assign(userInfo, hasUserInfo);
if (!hasUserInfo) {
try {
const hasUserInfo = userInfoStr ? JSON.parse(userInfoStr) : null;
if (hasUserInfo) {
token.value = hasUserInfo.FullName;
Object.assign(userInfo, hasUserInfo);
} else {
resetStore();
}
} catch (error) {
console.error('Error parsing user info:', error);
resetStore();
}
}
......
......@@ -10,6 +10,6 @@ export function getLocalUserInfo() {
/** Clear auth storage */
export function clearAuthStorage() {
localStg.remove('token');
localStg.remove('refreshToken');
// localStg.remove('token');
// localStg.remove('refreshToken');
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment