权限管理包含三部分:访问页面的权限,操作功能的权限和获取数据权限。
- 页面权限:登录用户所属角色的可访问页面的权限
- 功能权限:登录用户所属角色的可访问页面的操作权限
- 数据权限:登录用户所属角色的访问页面的数据访问的权限
需求
- 先不考虑数据权限,实现页面权限和功能权限。将两个权限存到menu表中,参考role表,以树形结构存储
- 不支持新增和删除
- 编辑
约定
- Headers: Authorization:`Bearer ${token}`
- Body: roleid(必填),isMenu(必填)
- 成功:{code:200,msg:'查询成功',data}
- 失败:{code:400,msg:'查询失败'}
- Headers: Authorization:`Bearer ${token}`
- Body: roleid(必填)
- 成功:{code:200,msg:'查询成功',data}
- 失败:{code:200,msg:'查询失败'}
- Headers: Authorization:`Bearer ${token}`
- Body: name,pid
- 成功:{code:200,msg:'编辑成功'}
- 失败:{code:400,msg:'编辑失败'}
实现
新增menu表,现在和user表,role表无关联,除menu操作之外的其他和之前一样,没有改动
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;
};
'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;
'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;
/
- @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);
};
{
"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" }
测试
总结
- 基本和角色表操作一样,重点主要是获取菜单树时要将操作叶子剪掉,直接在递归的时候加个判断即可
参考
<div id="blog_post_info">
<div class="clear"></div>
<div id="post_next_prev">
<a href="https://www.cnblogs.com/xingguozhiming/p/12157019.html" class="p_n_p_prefix">« </a> 上一篇: <a href="https://www.cnblogs.com/xingguozhiming/p/12157019.html" title="发布于 2020-01-06 16:31">egg实现登录鉴权(六):角色树的CRUD操作</a>
<br>
<a href="https://www.cnblogs.com/xingguozhiming/p/12340543.html" class="p_n_p_prefix">» </a> 下一篇: <a href="https://www.cnblogs.com/xingguozhiming/p/12340543.html" title="发布于 2020-02-21 10:52">egg实现登录鉴权(八):sequelize联表查询</a>
转载:https://www.cnblogs.com/xingguozhiming/p/12172597.html