u
This commit is contained in:
1 parent
68e0785ec6
commit
57c0d98f11
189 files changed
+34329
No files matched your search
@@ -0,0 +1,63 @@
|
||||
import { useUserStore } from "@/store/user";
|
||||
import { useWebSocketStore } from "@/store/webSocketStore";
|
||||
import { Message } from "@arco-design/web-vue";
|
||||
import type { App } from "vue";
|
||||
import { createRouter, createWebHashHistory } from "vue-router";
|
||||
import routes from "./routes";
|
||||
|
||||
const router = createRouter({
|
||||
history: createWebHashHistory(),
|
||||
strict: true,
|
||||
routes: routes,
|
||||
scrollBehavior: () => ({ left: 0, top: 0 })
|
||||
});
|
||||
|
||||
// 提取路径检查的逻辑
|
||||
function shouldCheckLogin(path: string, protectedPaths: string[]): boolean {
|
||||
// 将路径模式转化为正则表达式并检查路径是否匹配
|
||||
const regexPatterns = protectedPaths.map((pattern) => {
|
||||
// 将路径模式转换为正则表达式
|
||||
const regexString = pattern.replace(/\*\*/g, ".*").replace(/\//g, "\\/");
|
||||
return new RegExp(`^${regexString}$`);
|
||||
});
|
||||
|
||||
return regexPatterns.some((pattern) => pattern.test(path));
|
||||
}
|
||||
|
||||
const protectedPaths = ["/im/**", "/settings/**"];
|
||||
|
||||
router.beforeEach((to, from, next) => {
|
||||
window.NProgress?.start?.();
|
||||
|
||||
const userStore = useUserStore();
|
||||
const webSocketStore = useWebSocketStore();
|
||||
|
||||
if (shouldCheckLogin(to.path, protectedPaths)) {
|
||||
if (!userStore.isLogined) {
|
||||
Message.warning("尚未登录,请先登录!");
|
||||
setTimeout(() => {
|
||||
next("/login");
|
||||
}, 500);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (to.path === "/login") {
|
||||
webSocketStore.disconnect();
|
||||
}
|
||||
|
||||
if (userStore.isLogined) {
|
||||
const WebSocketUrl = import.meta.env.VITE_WEBSOCKET_BASEURL;
|
||||
|
||||
webSocketStore.connect(`${WebSocketUrl}/${userStore.userInfo.token}`);
|
||||
}
|
||||
next();
|
||||
});
|
||||
|
||||
router.afterEach(() => {
|
||||
window.NProgress?.done?.();
|
||||
});
|
||||
|
||||
export function setupRouter(app: App) {
|
||||
app.use(router);
|
||||
}
|
||||
Reference in new issue
Block a user