egg實現登錄鑒權(七):權限管理


權限管理包含三部分:訪問頁面的權限,操作功能的權限和獲取數據權限。

  • 頁面權限:登錄用戶所屬角色的可訪問頁面的權限
  • 功能權限:登錄用戶所屬角色的可訪問頁面的操作權限
  • 數據權限:登錄用戶所屬角色的訪問頁面的數據訪問的權限

需求

  • 先不考慮數據權限,實現頁面權限和功能權限。將兩個權限存到menu表中,參考role表,以樹形結構存儲
  • 不支持新增和刪除
  • 編輯
    • 修改結構
    • 修改名稱
  • 查詢
    • 以樹形結構返回菜單,不包含操作
    • 包含操作,剪除葉子

約定

  • 獲取菜單樹(GET)
    • 傳參
      • Headers: Authorization:`Bearer ${token}`
      • Body: roleid(必填),isMenu(必填)
    • 成功:{code:200,msg:'查詢成功',data}
    • 失敗:{code:400,msg:'查詢失敗'}
  • 獲取菜單權限樹(GET)
    • 傳參
      • Headers: Authorization:`Bearer ${token}`
      • Body: roleid(必填)
    • 成功:{code:200,msg:'查詢成功',data}
    • 失敗:{code:200,msg:'查詢失敗'}
  • 編輯菜單樹(POST)
    • 傳參
      • Headers: Authorization:`Bearer ${token}`
      • Body: name,pid
    • 成功:{code:200,msg:'編輯成功'}
    • 失敗:{code:400,msg:'編輯失敗'}

實現

新增menu表,現在和user表,role表無關聯,除menu操作之外的其他和之前一樣,沒有改動

  • 數據庫(mysql)

image.png

  • 項目目錄

image.png

  • app/model/menu.js

 

'use strict';

module.exports = app => {
  const { INTEGER, STRING } = app.Sequelize;
  const Menu = app.model.define('menu', {
    id: { type: INTEGER, primaryKey: true, autoIncrement: true },
    name: STRING(50),
    pid: INTEGER,
  }, {
    timestamps: false,
  });
  return Menu;
};

 

 

  • app/controller/menu.js

 

'use strict';
const Controller = require('egg').Controller;

class menuController extends Controller {
  async index() {
    const { ctx } = this;
    const { isMenu } = ctx.request.body;
    ctx.body = await ctx.service.menu.getMenu(isMenu);
  }
  async update() {
    const { ctx } = this;
    const { name, pid } = ctx.request.body;
    await ctx.service.menu.editMenu(ctx.params.id, name, pid);
    if (ctx.status === 404) {
      ctx.body = { code: 400, msg: '編輯失敗' };
    } else {
      ctx.body = { code: 200, msg: '編輯成功' };
    }
  }
}

module.exports = menuController;

 

 

  • app/service/menu.js

 

'use strict';
const Service = require('egg').Service;
function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}
class MenuService extends Service {
  // 構建菜單權限樹
  // 如果id為空,則構建所有的數據
  // id不為空,則構建以id為根結點的樹
  buildTree(id, data, isMenu) {
    const res = [];
    if (id) {
      for (const item of data) {
        if (toInt(item.id) === toInt(id)) {
          item.children = getNode(id);
          res.push(item);
        }
      }
    } else {
      for (const item of data) {
        if (!item.pid) {
          item.children = getNode(item.id);
          res.push(item);
        }
      }
    }
    // 傳入根結點id 遞歸查找所有子節點
    function getNode(id) {
      const node = [];
      for (const item of data) {
        if (toInt(item.pid) === toInt(id) && (isMenu === 'true' ? item.children : true)) {
          item.children = getNode(item.id);
          node.push(item);
        }
      }
      if (node.length === 0) return;
      return node;
    }
    return res;
  }
  // 獲取所有子節點集合
  getChildrenIds(treeData) {
    const res = [];
    function getIds(treeData, res) {
      for (const item of treeData) {
        res.push(item.id);
        if (item.children) { getIds(item.children, res); }
      }
    }
    getIds(treeData, res);
    return res;
  }
  // 查詢角色並構建菜單樹
  async getMenu(isMenu) {
    const { ctx } = this;
    const query = { limit: toInt(ctx.query.limit), offset: toInt(ctx.query.offset) };
    const data = await ctx.model.Menu.findAll({ query, raw: true });
    return this.buildTree(null, data, isMenu);
  }
  // 根據id查詢角色
  async getMenuById(id) {
    const { ctx } = this;
    return await ctx.model.Menu.findByPk(toInt(id));
  }
  // 編輯菜單
  async editMenu(id, name, pid) {
    const { ctx } = this;
    const menu = await this.getMenuById(toInt(id));
    if (!menu) {
      ctx.status = 404;
      return;
    }
    await menu.update({ name: name || menu.name, pid: pid || menu.pid });
    ctx.status = 200;
  }
}

module.exports = MenuService;

 

 

  • app/router.js

 

'use strict';

/**
 * @param {Egg.Application} app - egg application
 */
module.exports = app => {
  const { router, controller, jwt } = app;
  router.get('/', controller.home.index);

  router.post('/user/login', controller.user.login);
  // 查詢用戶
  router.get('/user', controller.user.index);
  router.get('/user/:id', jwt, controller.user.show);
  // 新增
  router.put('/user', jwt, controller.user.create);
  // 修改密碼
  router.post('/user/:id', jwt, controller.user.updatePwd);


  // 獲取角色
  router.get('/role', controller.role.index);
  router.get('/role/:id', controller.role.show);
  // 插入角色
  router.put('/role', jwt, controller.role.create);
  // 修改角色
  router.post('/role/:id', jwt, controller.role.update);
  // 刪除角色
  router.delete('/role/:id', jwt, controller.role.remove);

  // 獲取菜單
  router.get('/menu', controller.menu.index);
  // 編輯菜單
  router.post('/menu/:id', jwt, controller.menu.update);
};

 

  • package.json
{
  "name": "jwt", "version": "1.0.0", "description": "", "private": true, "egg": { "declarations": true }, "dependencies": { "egg": "^2.15.1", "egg-cors": "^2.2.3", "egg-jwt": "^3.1.7", "egg-scripts": "^2.11.0", "egg-sequelize": "^5.2.0", "mysql2": "^2.0.2" }, "devDependencies": { "autod": "^3.0.1", "autod-egg": "^1.1.0", "egg-bin": "^4.11.0", "egg-ci": "^1.11.0", "egg-mock": "^3.21.0", "eslint": "^5.13.0", "eslint-config-egg": "^7.1.0" }, "engines": { "node": ">=10.0.0" }, "scripts": { "start": "egg-scripts start --daemon --title=egg-server-jwt", "stop": "egg-scripts stop --title=egg-server-jwt", "dev": "egg-bin dev", "debug": "egg-bin debug", "test": "npm run lint -- --fix && npm run test-local", "test-local": "egg-bin test", "cov": "egg-bin cov", "lint": "eslint .", "ci": "npm run lint && npm run cov", "autod": "autod" }, "ci": { "version": "10" }, "repository": { "type": "git", "url": "" }, "author": "", "license": "MIT" }

 

測試

  • 獲取菜單樹

image.png

  • 獲取菜單權限樹

image.png

  • 編輯菜單樹

image.png

image.png

總結

  • 基本和角色表操作一樣,重點主要是獲取菜單樹時要將操作葉子剪掉,直接在遞歸的時候加個判斷即可

參考


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM