vueログイン権限管理

29760 ワード

1.必要な知識点
vue-routerルーティングガード
Vue RouterはVueです.js公式のルーティングマネージャは、vue項目でログインブロックジャンプ機能を実現するには、必ずvue-routerから離れられない.ここでは主要な知識点、vue-routerのナビゲーションガードに適用され、機能の実現を開始する前に、この知識点をよく見ることをお勧めします.
ナビゲーション・ガードは、グローバル・ナビゲーション・ガード、個別ルーティング・ガード、およびコンポーネント固有のガードに分けられます.ここでは、主にグローバル・ナビゲーション・ガードが適用されます.
beforeEach((to,from,next)=>{})これはグローバルフロントガードです
afterEach(to,from))これはグローバルバックグラウンドガードです
toはターゲットルーティングを示す
fromは現在離れているルーティングを表します
nextは簡単に言えば次の意味ですが、ここでは下に実行すると理解できます.主に以下の3つの使い方があります.next()next(false)next(’/path’)はあまり説明しません.公式サイトでは説明が行き届いています.
2.機能分析
1.ユーザーはアカウントパスワードでログインし、ログインに成功したバックグラウンドからtokenに戻り、tokenに基づいて権限情報を取得する.
2.router.jsのルーティングは2つの部分に分けられ、一部は一定のルーティングであり、一部はアクセス権が必要な非同期ロードルーティングであり、ページ初期化時に一定のルーティングのみをロードする.404ページは最後の宣言に置くことに注意する.そうしないと、ログインブロック後に非同期ロードルーティングは404ページにブロックされ、非同期ロードルーティングの宣言ではmetaラベルでユーザー権限を追加することができる.ここで設定するユーザ権限は$routerを通過することができる.matched取得.
3.vuexはルーティング情報を格納し、ナビゲーションバーのデータソースはvuexから取得する.権限情報を取得してvuexのメソッドを呼び出し,権限を判断し,権限情報に基づいて現在のユーザに対応するすべてのルーティング情報を計算し,vuexのstateに格納する.
4.permission.jsでは,グローバルルーティングガードにより異なるログインと権限状況を解析的に判断する.
注意一:roter.addRoutes()は不可欠であり,このステップはルーティングをユーザがアクセス可能なルーティングに変えることである.
注意2:routerを繰り返し使用することはできません.addRoutes()コンソールに警告Duplicate named routes definitionがあるので、毎回routerをオンにします.addRoutes()が動的にマウントされている場合は、権限情報が取得されているかどうかを判断し、ルーティングが行われています.
一、ログイン状況分析
1.ログインの有無を判断する
2.ログインキャッシュがある場合
                next('/home')
               next()

3.ログインキャッシュがない場合
                next()
                        next('/login')

二、権限状況分析
1.ユーザがtokenに基づいて権限情報を取得したか否かを判断する
2.権限情報を取得していない
      
  vuex                 
          

3.権限情報を取得しました
next()/ユーザー権限がある場合、アクセス可能なすべてのルーティングが生成されたことを説明します.アクセス権限がない場合は、404ページに自動的にアクセスします.
3.具体コード
router.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)

export const constantRoutes = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/login'),
    hidden: true
  },
  {
    path: '/monitor',
    component: () => import('@/views/layout'),
    meta: {
      title: '    ',
      icon: ''
    },
    children: [
      {
        path: '/monitor',
        name: 'Monitor',
        component: () => import('@/views/monitor/index')
      }
    ]
  }
]

export const asyncRoutes = [
  {
    path: '/asyncPage',
    component: () => import('@/views/layout'),
    meta: {
      title: '      ',
      icon: '',
      roles: ['admin']
    },
    children: [
      {
        path: '/asyncPage',
        name: 'AsyncPage',
        component: () => import('@/views/asyncPage/index')
      }
    ]
  },
  {
    path: '*',
    redirect: '/404',
    hidden: true
  }
]

const router = new Router({
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})
export default router


vuex
import { asyncRoutes, constantRoutes } from '@/router'

/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.includes(role))
  } else {
    return true
  }
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      let accessedRoutes
      if (roles.includes('admin')) {
        accessedRoutes = asyncRoutes || []
      } else {
        accessedRoutes = filterAsyncRoutes(asyncRoutes, roles)
      }
      commit('SET_ROUTES', accessedRoutes)
      resolve(accessedRoutes)
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}


permission.js
// main.js
import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

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

const whiteList = ['/login', '/auth-redirect'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()

  if (hasToken) {
    if (to.path === '/login') {
      // if is logged in, redirect to the home page
      next({ path: '/' })
      NProgress.done()
    } else {
      // determine whether the user has obtained his permission roles through getInfo
      const hasRoles = store.getters.roles && store.getters.roles.length > 0
      if (hasRoles) {
        next()
      } else {
        try {
          // get user info
          // note: roles must be a object array! such as: ['admin'] or ,['developer','editor']
          const { roles } = await store.dispatch('user/getInfo')
          // generate accessible routes map based on roles
          const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
          // dynamically add accessible routes
          router.addRoutes(accessRoutes)

          // hack method to ensure that addRoutes is complete
          // set the replace: true, so the navigation will not leave a history record
          next({ ...to, replace: true })
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch('user/resetToken')
          Message.error(error || 'Has Error')
          next(`/login?redirect=${to.path}`)
          NProgress.done()
        }
      }
    }
  } else {
    /* 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()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})