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

82 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 });
2025-06-29 00:57:57 +08:00
const { getToken, logoutFun ,getRefreshToken} = useAuths();
2023-12-14 10:15:23 +08:00
const whiteList = ["/login", "/auth-redirect", "/bind", "/register"];
2025-07-15 00:54:34 +08:00
router.beforeEach(async (to, from, next) => {
2023-12-14 10:15:23 +08:00
NProgress.start();
const hasToken = getToken();
2025-06-29 00:57:57 +08:00
const refreshToken = getRefreshToken();
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');
2025-07-15 00:54:34 +08:00
// ➤ 如果是弹窗+LoginAgain执行登出再跳转回 login 页面
if (clientId === 'LoginAgain' && isPopup && hasToken) {
await logoutFun()
next({ path: '/login', query: { client_id: 'YiXinAi-Login', redirect_uri: redirectUri } });
return;
} else if (isPopup && clientId === 'YiXinAi-Login' && redirectUri) {
2025-06-21 21:52:44 +08:00
if (hasToken) {
// 发送消息给父窗口
const targetOrigin = new URL(decodeURIComponent(redirectUri)).origin;
2025-06-21 21:52:44 +08:00
window.opener.postMessage({
type: 'SSO_LOGIN_SUCCESS',
2025-06-29 00:57:57 +08:00
token: hasToken,
refreshToken: refreshToken,
}, targetOrigin);
// 立即关闭窗口
2025-06-21 21:52:44 +08:00
setTimeout(() => window.close(), 100);
2025-07-15 00:54:34 +08:00
return;
2025-06-21 21:52:44 +08:00
}
}
}
2023-12-14 10:15:23 +08:00
if (hasToken) {
if (to.path === "/login") {
// 已经登陆跳转到首页
2025-07-15 00:54:34 +08:00
next({path: "/"});
2023-12-14 10:15:23 +08:00
NProgress.done();
} else {
if (useUserStore().roles.length === 0) {
// 判断当前用户是否已拉取完user_info信息
useUserStore()
2025-07-15 00:54:34 +08:00
.getInfo()
.then(() => {
next({...to, replace: true});
})
.catch((err) => {
logoutFun.then(() => {
ElMessage.error(err);
next({path: "/"});
});
2023-12-14 10:15:23 +08:00
});
} 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();
});