permission.js 1.21 KB
Newer Older
wanli's avatar
wanli committed
1 2 3 4
import router from "@/router";
import store from "@/store";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
wanli's avatar
wanli committed
5
import { getPageTitle } from "@/utils/index";
wanli's avatar
wanli committed
6

wanli's avatar
wanli committed
7
const whiteList = ["/login", "/register"];
wanli's avatar
wanli committed
8 9 10 11

NProgress.configure({ showSpinner: false }); // NProgress Configuration

router.beforeEach(async (to, from, next) => {
wanli's avatar
wanli committed
12 13
    // start progress bar
    NProgress.start();
wanli's avatar
wanli committed
14

wanli's avatar
wanli committed
15 16
    // set page title
    document.title = getPageTitle(to.meta.title);
wanli's avatar
wanli committed
17

wanli's avatar
wanli committed
18 19
    // determine whether the user has logged in
    const hasToken = store.getters.token;
wanli's avatar
wanli committed
20

wanli's avatar
wanli committed
21 22 23 24 25 26 27 28
    if (hasToken) {
        if (to.path === "/login") {
            // if is logged in, redirect to the home page
            next({ path: "/" });
            NProgress.done();
        } else {
            next();
        }
wanli's avatar
wanli committed
29
    } else {
wanli's avatar
wanli committed
30 31 32 33 34 35 36 37 38
        /* has no token*/
        if (whiteList.indexOf(to.path) !== -1) {
            // in the free login whitelist, go directly
            next();
        } else {
            // other pages that do not have permission to access are redirected to the login page.
            next(`/login?redirect=${to.path}`);
            NProgress.done();
        }
wanli's avatar
wanli committed
39 40 41 42
    }
});

router.afterEach(() => {
wanli's avatar
wanli committed
43 44
    // finish progress bar
    NProgress.done();
wanli's avatar
wanli committed
45
});