permission_filter.js 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. module.exports = option => {
  3. /**
  4. * 用户权限筛选中间件
  5. *
  6. * @param {function} next - 中间件继续执行的方法
  7. * @return {void}
  8. */
  9. return function* permissionFilter(next) {
  10. // 获取所有权限数据
  11. const permissionData = yield this.service.permission.getAllData(true, true);
  12. this.currentName = '';
  13. let currentPermissionId = 0;
  14. // 查找controller和action名称相同的数据
  15. for (const index in permissionData) {
  16. if (permissionData[index].controller === this.controllerName && permissionData[index].action === this.actionName) {
  17. this.currentName = permissionData[index].name;
  18. currentPermissionId = permissionData[index].id;
  19. break;
  20. }
  21. }
  22. // 如果页面没有录入db,则允许通过,否则进入权限判断
  23. if (currentPermissionId > 0) {
  24. // 查找当前用户是否有对应页面权限
  25. const managerSession = this.session.managerSession;
  26. const permission = managerSession.permission;
  27. try {
  28. checkPermission(permission, currentPermissionId);
  29. } catch (error) {
  30. this.session.message = {
  31. type: 'error',
  32. icon: 'exclamation-sign',
  33. message: error.toString(),
  34. };
  35. return this.redirect('/dashboard');
  36. }
  37. }
  38. // 找出对应页面的最顶层id
  39. this.permissionRootId = 0;
  40. this.service.permission.getTopPid(currentPermissionId, permissionData);
  41. // 查找最顶层数据
  42. this.topPermission = yield this.service.permission.getCacheDataById(this.permissionRootId);
  43. this.currentName = this.currentName === '' ? '后台管理' : this.currentName;
  44. yield next;
  45. };
  46. };
  47. /**
  48. * 判断权限
  49. *
  50. * @param {String} permissionList - 当前用户权限字符串
  51. * @param {Number} currentPermissionId - 当前被访问页面的权限id
  52. * @return {void}
  53. */
  54. function checkPermission(permissionList, currentPermissionId) {
  55. if (permissionList === '') {
  56. throw '用户组权限为空';
  57. }
  58. // 如果是超级管理员则直接返回
  59. if (permissionList === 'all') {
  60. return;
  61. }
  62. const permissionIdList = permissionList.split(',');
  63. if (permissionIdList.indexOf(currentPermissionId + '') < 0) {
  64. throw '当前用户组没有对应权限';
  65. }
  66. }