使用Ant Design of vue脚手架,后端服务使用nodejs(koa+router+mysql)实现角色权限系统

1,338 阅读2分钟

整体项目描述

前端使用Ant Design of vue脚手架,后端服务使用nodejs(koa+router+mysql)。实现权限管理系统,主要实现功能为根据用户账号下不同的角色权限编码字段登录系统,控制系统展示不同的界面。另外再实现对表的增删改查的功能。

文中只介绍核心代码,具体实现代码请参考以下链接:

Ant Design of Vue - Ant Design Vue

Ant Design Pro of Vue

Koa2中文文档_Koa2教程

ps:只为简单实现,细节处理请自行考虑

权限系统实现思路

用户登录发送请求(前端)->接收请求查找数据库响应对应用户的数据(服务端)->接收响应数据,设置token(前端)->登录请求收到响应,尝试跳转页面(系统首页,profile)(前端)->router.beforeEach(初次进入由于没有角色数据触发)发送getInfo请求(前端)->接收请求查找数据库响应对应用户的数据(服务端) ["profile", "author", "center", "detail", "option"]->接收响应数据roles,filterAsyncRouter处理路由,完成后router.addRoutes

挂载路由(前端)->页面跳转,进入系统

核心代码

  • 数据表user(偷懒只做一个表)

  • 用户登录发送Login请求,参数为{username: 'admin', password: '123456'}

  • 服务端接收请求,根据参数查找数据

// 登录
router.post(URL.Login, async (ctx, next) => {
    const {username, password} = ctx.request.body
    let SQL = `SELECT * FROM user WHERE name = "${username}" AND password = "${password}"`
    const data = await Auth.Login(SQL)
    ctx.body = data;
})

  • 登录请求接收响应数据,this.$router.push({ name: 'profile' }),跳转页面,触发router.beforeach,前端store.dispatch('GetInfo')再次发送GetInfo请求获取当前账户的配置(即下代码中res.data = ["profile", "author", "center", "detail", "option"])

    store.dispatch('GetInfo').then(res => {
        const roles = res.data
        store.dispatch('GenerateRoutes', { roles }).then(() => {
        // 根据roles权限生成可访问的路由表
        // 动态添加可访问路由表
        router.addRoutes(store.getters.addRouters)
        const redirect = decodeURIComponent(from.query.redirect || to.path)
        if (to.path === redirect) {
          next({ ...to, replace: true })
        } else {
        // 跳转到目的路由
        next({ path: redirect })
       }
    })
    

  • 后端响应数据["profile", "author", "center", "detail", "option"]赋值给roles,然后执行store.dispatch('GenerateRoutes', { roles })

GenerateRoutes ({ commit }, data) {
      return new Promise(resolve => {
        const { roles } = data
        const accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
        commit('SET_ROUTERS', accessedRouters)
        resolve()
      })
    }

// 根据roles数据匹配asyncRouterMap路由数据中meta.permission后过滤出目标路由数据
function filterAsyncRouter (routerMap, roles) {
  const accessedRouters = routerMap.filter(route => {
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
} 

  • 根据roles数据匹配asyncRouterMap路由数据中meta.permission后过滤出目标路由数据,然后将处理好的路由数据router.addRoutes挂载,然后正式跳转profile页面

演示

(图片压缩过,可能会模糊,可以通过缩放浏览器观看)

  • 账号admin拥有全部页面权限profile,author,center,detail,option(对应页面为:基础详情页,操作记录,权限列表,个人中心,详细介绍)

  • 账号user拥有部分页面权限profile,author,center(对应页面为:基础详情页,权限列表,个人中心)

备注:下篇介绍权限列表界面对Nodejs增删改查的操作