Files
Yi.Admin/Yi.Bbs.Vue3/src/permission.js

88 lines
2.5 KiB
JavaScript
Raw Normal View History

2023-12-14 10:15:23 +08:00
import router from "./router";
import useAuths from "@/hooks/useAuths";
import { ElMessage } from "element-plus";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import useUserStore from "@/stores/user";
NProgress.configure({ showSpinner: false });
const { getToken, logoutFun } = useAuths();
const whiteList = ["/login", "/auth-redirect", "/bind", "/register"];
router.beforeEach((to, from, next) => {
NProgress.start();
const hasToken = getToken();
2025-06-21 21:52:44 +08:00
if (to.path === "/login" || to.path === "/index") {
const urlParams = new URLSearchParams(window.location.search);
const isPopup = window.opener && window.opener !== window;
const clientId = urlParams.get('client_id');
const redirectUri = urlParams.get('redirect_uri');
// 检查是否已经处理过SSO登录防重复
const hasHandledSSO = sessionStorage.getItem('sso_handled');
if (isPopup && clientId && redirectUri && !hasHandledSSO) {
if (hasToken) {
// 标记已处理,避免重复发送
sessionStorage.setItem('sso_handled', 'true');
// 发送消息给父窗口
window.opener.postMessage({
type: 'SSO_LOGIN_SUCCESS',
token: hasToken
}, redirectUri);
// 关闭弹出窗口
setTimeout(() => window.close(), 100);
} else {
// 存储SSO参数但改用sessionStorage避免持久化
sessionStorage.setItem('sso_params', JSON.stringify({
isPopup,
clientId,
redirectUri
}));
}
}
}
2023-12-14 10:15:23 +08:00
if (hasToken) {
if (to.path === "/login") {
// 已经登陆跳转到首页
next({ path: "/" });
NProgress.done();
} else {
if (useUserStore().roles.length === 0) {
// 判断当前用户是否已拉取完user_info信息
useUserStore()
.getInfo()
.then(() => {
next({ ...to, replace: true });
})
.catch((err) => {
logoutFun.then(() => {
ElMessage.error(err);
next({ path: "/" });
});
});
} else {
next();
}
}
} else {
// 没有token
if (whiteList.indexOf(to.path) !== -1) {
// 在免登录白名单,直接进入
next();
} else {
2023-12-14 23:29:36 +08:00
next();
useUserStore().resetInfo();
2023-12-14 23:29:36 +08:00
// next(`/login?redirect=${to.path}&unTourist=true`); // 否则全部重定向到登录页
2023-12-14 10:15:23 +08:00
NProgress.done();
}
}
});
router.afterEach(() => {
NProgress.done();
});