guards.js 1.68 KB
Newer Older
1
import { loginIgnore } from '@/router/index';
水落(YangLei)'s avatar
水落(YangLei) committed
2
import { getUserInfo } from '@/utils';
3 4
import { checkAuthorization } from '@/utils/requestUtil';
import NProgress from 'nprogress';
水落(YangLei)'s avatar
水落(YangLei) committed
5
import { globalRoutes } from '@/router/config';
wb-ct393452's avatar
wb-ct393452 committed
6

7
NProgress.configure({ showSpinner: false });
wb-ct393452's avatar
wb-ct393452 committed
8

水落(YangLei)'s avatar
水落(YangLei) committed
9 10
function hasAuthority(to) {
    const { path } = to;
11
    if (globalRoutes.find((m) => m.path === path)) return true;
水落(YangLei)'s avatar
水落(YangLei) committed
12
    const { menuList = [] } = getUserInfo();
13
    return !!menuList.find((i) => i.menuUrl === path);
水落(YangLei)'s avatar
水落(YangLei) committed
14 15
}

wb-ct393452's avatar
wb-ct393452 committed
16 17 18 19 20 21 22
/**
 * 进度条开始
 * @param to
 * @param form
 * @param next
 */
const progressStart = (to, from, next) => {
23 24 25 26 27 28
    // start progress bar
    if (!NProgress.isStarted()) {
        NProgress.start();
    }
    next();
};
wb-ct393452's avatar
wb-ct393452 committed
29 30 31 32 33 34 35 36 37

/**
 * 登录守卫
 * @param to
 * @param form
 * @param next
 * @param options
 */
const loginGuard = (to, from, next, options) => {
38 39 40 41 42 43 44 45
    const { message } = options;
    if (!loginIgnore.includes(to) && !checkAuthorization()) {
        message.warning('登录已失效,请重新登录');
        next({ path: '/login' });
    } else {
        next();
    }
};
wb-ct393452's avatar
wb-ct393452 committed
46 47 48 49 50 51 52 53 54

/**
 * 权限守卫
 * @param to
 * @param form
 * @param next
 * @param options
 */
const authorityGuard = (to, from, next, options) => {
水落(YangLei)'s avatar
水落(YangLei) committed
55 56
    const { message } = options;
    if (!hasAuthority(to)) {
57 58 59 60 61 62
        message.warning(`对不起,您无权访问页面: ${to.fullPath},请联系管理员`);
        next({ path: '/403' });
    } else {
        next();
    }
};
wb-ct393452's avatar
wb-ct393452 committed
63 64 65 66 67 68 69 70

/**
 * 进度条结束
 * @param to
 * @param form
 * @param options
 */
const progressDone = () => {
71 72 73
    // finish progress bar
    NProgress.done();
};
wb-ct393452's avatar
wb-ct393452 committed
74 75

export default {
水落(YangLei)'s avatar
水落(YangLei) committed
76
    beforeEach: [progressStart, loginGuard, authorityGuard],
77 78
    afterEach: [progressDone],
};