Commit 2deba187 by User

登录逻辑修改

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