13-全局路由守卫

2019-08-26  本文已影响0人  云桃桃

其实和之前做的项目基本一样,取token,来验证用户信息,画个流程图就清晰多了,可根据业务需求再做处理。


全局路由守卫.png
import router from './router/index'
import store from './store/index'
import { getToken } from '@/utils/auth' // get token from localStorage
const whiteList = ['/login', '/auth-redirect'] // 白名单

router.beforeEach(async(to, from, next) => {
    // 确定用户是否有token 
    const hasToken = getToken()
    const hasRoles = store.getters.roles && store.getters.roles.length > 0
    if (hasToken) {
        if (to.path === '/login') {
            next()
        } else {
            try {
                if (hasRoles && to.path) {
                    next()
                } else {
                    // 解决了刷新问题
                    console.log('有token-无角色')
                    // 获取用户信息的角色  是一个array
                    const { roles } = await store.dispatch('user/getInfo')
                    const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
                    router.addRoutes(accessRoutes)
                    next({path:to.path,replace:true});
                }
            } catch (error) {
                console.log('无path')
                // remove token and go to login page to re-login
                await store.dispatch('user/resetToken')
                Message.error('Has Error')
                next(`/login`)
            }
        }
        return

    } 
    /* 无需token的页面*/
    if (whiteList.indexOf(to.path) !== -1) {
        console.log('---------白名单')
        // in the free login whitelist, go directly
        next()
    } else {
        console.log('---------回调到登录咯')
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`)
    }
})

上一篇下一篇

猜你喜欢

热点阅读