refactor: 路由跳转优化

This commit is contained in:
shiziyuan9527 2022-10-28 18:09:16 +08:00 committed by 刘瑞斌
parent 5e35184d32
commit b1df71c717
7 changed files with 53 additions and 84 deletions

View File

@ -61,9 +61,14 @@ public class LoginController {
.map(r -> { .map(r -> {
if (r instanceof RsaKey) { if (r instanceof RsaKey) {
return ResultHolder.error(rsaKey.getPublicKey()); return ResultHolder.error(rsaKey.getPublicKey());
} else {
return ResultHolder.success(r);
} }
if (r instanceof User) {
// 用户只有工作空间权限
if (StringUtils.isBlank(((User) r).getLastProjectId())) {
((User) r).setLastProjectId("no_such_project");
}
}
return ResultHolder.success(r);
}); });
} else { } else {
return Mono.just(ResultHolder.error(rsaKey.getPublicKey())); return Mono.just(ResultHolder.error(rsaKey.getPublicKey()));

View File

@ -101,7 +101,7 @@ export default {
ready: false, ready: false,
openLdap: false, openLdap: false,
authSources: [], authSources: [],
lastUser: null, lastUser: sessionStorage.getItem('lastUser'),
loginTitle: this.$t('commons.welcome') loginTitle: this.$t('commons.welcome')
} }
}, },
@ -238,6 +238,7 @@ export default {
}, },
checkRedirectUrl() { checkRedirectUrl() {
if (this.lastUser === getCurrentUserId()) { if (this.lastUser === getCurrentUserId()) {
this.$router.push({path: sessionStorage.getItem('redirectUrl') || '/'});
return; return;
} }
let redirectUrl = '/'; let redirectUrl = '/';
@ -252,7 +253,8 @@ export default {
} }
sessionStorage.setItem('redirectUrl', redirectUrl); sessionStorage.setItem('redirectUrl', redirectUrl);
this.$router.push({path: redirectUrl || '/', query: this.otherQuery}) sessionStorage.setItem('lastUser', getCurrentUserId());
this.$router.push({ name: "login_redirect", path: redirectUrl || '/', query: this.otherQuery});
}, },
doLogin() { doLogin() {
const userStore = useUserStore() const userStore = useUserStore()
@ -282,10 +284,7 @@ export default {
.then(response => { .then(response => {
language = response.data; language = response.data;
localStorage.setItem(DEFAULT_LANGUAGE, language); localStorage.setItem(DEFAULT_LANGUAGE, language);
window.location.href = "/";
}); });
} else {
window.location.href = "/";
} }
}, },
redirectAuth(authId) { redirectAuth(authId) {

View File

@ -116,12 +116,22 @@ export default {
this.handleSelect(this.activeIndex); this.handleSelect(this.activeIndex);
} }
}, },
created() {
this.$EventBus.$on('projectChange', () => {
this.$nextTick(() => {
this.menuKey++;
})
})
},
mounted() { mounted() {
if (this.$route.matched.length > 0) { if (this.$route.matched.length > 0) {
this.activeIndex = this.$route.matched[0].path; this.activeIndex = this.$route.matched[0].path;
} }
this.registerEvents(); this.registerEvents();
}, },
beforeDestroy() {
this.$EventBus.$off('projectChange');
},
methods: { methods: {
hasLicense, hasLicense,
handleSelect(index) { handleSelect(index) {

View File

@ -1,7 +1,6 @@
import Vue from "vue" import Vue from "vue"
import Router from "vue-router" import Router from "vue-router"
import Layout from "../business/app-layout" import Layout from "../business/app-layout"
import {getCurrentUserId} from "../utils/token";
import {hasPermissions} from "../utils/permission"; import {hasPermissions} from "../utils/permission";
import {SECOND_LEVEL_ROUTE_PERMISSION_MAP} from "../utils/constants"; import {SECOND_LEVEL_ROUTE_PERMISSION_MAP} from "../utils/constants";
@ -64,84 +63,35 @@ let store = null;
router.beforeEach(async (to, from, next) => { router.beforeEach(async (to, from, next) => {
if (store === null) { if (store === null) {
const {useUserStore} = await import('@/store'); const {useUserStore} = await import('@/store');
store = useUserStore() store = useUserStore();
} }
let user = store.currentUser let formModule = from.path.split('/')[1];
if (to.path.split('/')[1] !== from.path.split('/')[1]) { let toModule = to.path.split('/')[1];
if (to.path !== '/login' && formModule && toModule !== formModule) {
try { try {
user = await store.getIsLogin(); await store.getIsLogin();
if (window.location.href.endsWith('/#/login')) {
window.location.replace("/#/setting/personsetting");
}
} catch (e) { } catch (e) {
// console.error(e) // nothing
} }
} }
if (user && user.id) {
redirectLoginPath(to.fullPath, next); if (to.name === "login_redirect" || to.path === "/login") {
} else {
next(); next();
return;
}
// 二级菜单权限控制
let changedPath = getDefaultSecondLevelMenu(to.fullPath);
sessionStorage.setItem('redirectUrl', changedPath);
if (changedPath === to.fullPath) {
// 有权限则放行
next();
} else {
// 未通过校验,放行至有权限路由
next({path: changedPath});
} }
}); });
// 登入后跳转至原路径
function redirectLoginPath(originPath, next) {
let redirectUrl = sessionStorage.getItem('redirectUrl');
let loginSuccess = sessionStorage.getItem('loginSuccess');
if (!redirectUrl || redirectUrl === '/') {
if (hasPermissions('PROJECT_USER:READ', 'PROJECT_ENVIRONMENT:READ', 'PROJECT_OPERATING_LOG:READ', 'PROJECT_FILE:READ+JAR', 'PROJECT_FILE:READ+FILE', 'PROJECT_CUSTOM_CODE:READ', 'PROJECT_TEMPLATE:READ', 'PROJECT_MESSAGE:READ')) {
redirectUrl = '/project/home';
} else if (hasPermissions('WORKSPACE_SERVICE:READ', 'PROJECT_MESSAGE:READ', 'WORKSPACE_USER:READ', 'WORKSPACE_PROJECT_MANAGER:READ', 'WORKSPACE_PROJECT_ENVIRONMENT:READ', 'WORKSPACE_OPERATING_LOG:READ')) {
redirectUrl = '/setting/project/:type';
} else if (hasPermissions('SYSTEM_USER:READ', 'SYSTEM_WORKSPACE:READ', 'SYSTEM_GROUP:READ', 'SYSTEM_TEST_POOL:READ', 'SYSTEM_SETTING:READ', 'SYSTEM_AUTH:READ', 'SYSTEM_QUOTA:READ', 'SYSTEM_OPERATING_LOG:READ')) {
redirectUrl = '/setting';
} else {
redirectUrl = '/';
}
}
sessionStorage.setItem('lastUser', getCurrentUserId());
sessionStorage.setItem('redirectUrl', originPath);
sessionStorage.removeItem('loginSuccess');
let defaultMenuRoute = sessionStorage.getItem('defaultMenuRoute');
if (redirectUrl && loginSuccess) {
// 登录后只执行一次
sessionStorage.removeItem('loginSuccess');
let changedPath = getDefaultSecondLevelMenu(originPath);
if (changedPath === originPath) {
// 通过了权限校验,保留路由相关信息,直接放行
next();
} else {
// 未通过校验,放行至有权限路由
next({path: changedPath});
}
} else {
if (!defaultMenuRoute) {
// 记录标识,防止死循环
sessionStorage.setItem('defaultMenuRoute', 'sign');
let changedPath = getDefaultSecondLevelMenu(originPath);
if (changedPath === originPath) {
// 通过了权限校验,保留路由相关信息,直接放行
next();
} else {
// 未通过校验,放行至有权限路由
next({path: changedPath});
}
if (router.currentRoute.fullPath === originPath) {
sessionStorage.setItem('redirectUrl', originPath);
// 路径相同时,移除标识
sessionStorage.removeItem("defaultMenuRoute");
}
} else {
sessionStorage.setItem('redirectUrl', originPath);
sessionStorage.removeItem("defaultMenuRoute");
next();
}
}
}
export function getDefaultSecondLevelMenu(toPath) { export function getDefaultSecondLevelMenu(toPath) {
let {TRACK: tracks, API: apis, LOAD: loads, UI: ui, REPORT: report} = SECOND_LEVEL_ROUTE_PERMISSION_MAP; let {TRACK: tracks, API: apis, LOAD: loads, UI: ui, REPORT: report} = SECOND_LEVEL_ROUTE_PERMISSION_MAP;
if (tracks.map(r => r.router).indexOf(toPath) > -1) { if (tracks.map(r => r.router).indexOf(toPath) > -1) {

View File

@ -20,7 +20,7 @@ router.beforeEach(async (to, from, next) => {
if (user && user.id) { if (user && user.id) {
if (to.path === '/login') { if (to.path === '/login') {
next({path: '/'}); next();
NProgress.done(); // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939 NProgress.done(); // hack: https://github.com/PanJiaChen/vue-element-admin/pull/2939
} else { } else {
// const roles = user.roles.filter(r => r.id); // const roles = user.roles.filter(r => r.id);

View File

@ -109,15 +109,16 @@ export default {
}, },
userLogout() { userLogout() {
clearSessionStorage();
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
logout().then(() => { logout().then(() => {
clearSessionStorage() location.href = '/#/login';
location.reload() location.reload();
resolve() resolve();
}).catch(error => { }).catch(error => {
clearSessionStorage() location.href = '/#/login';
location.reload() location.reload();
reject(error) reject(error);
}) })
}) })
}, },

View File

@ -57,6 +57,10 @@ public class LoginController {
baseUserService.autoSwitch(userDTO); baseUserService.autoSwitch(userDTO);
SessionUser sessionUser = SessionUser.fromUser(userDTO, SessionUtils.getSessionId()); SessionUser sessionUser = SessionUser.fromUser(userDTO, SessionUtils.getSessionId());
SessionUtils.putUser(sessionUser); SessionUtils.putUser(sessionUser);
// 用户只有工作空间权限
if (StringUtils.isBlank(sessionUser.getLastProjectId())) {
sessionUser.setLastProjectId("no_such_project");
}
return ResultHolder.success(sessionUser); return ResultHolder.success(sessionUser);
} }
return ResultHolder.error(rsaKey.getPublicKey()); return ResultHolder.error(rsaKey.getPublicKey());