access-control.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /**
  2. * 权限验证中间件,一般情况下,无需修改此处的代码
  3. */
  4. const methodPermission = require('../config/permission');
  5. const { ERROR } = require('../common/error');
  6. function isAccessAllowed(user = {}, setting) {
  7. const {
  8. role: userRole = [],
  9. permission: userPermission = []
  10. } = user
  11. const {
  12. role: settingRole = [],
  13. permission: settingPermission = []
  14. } = setting
  15. if (userRole.includes('admin')) {
  16. return;
  17. }
  18. if (settingRole.length > 0 && settingRole.every(item => !userRole.includes(item))) {
  19. throw { errCode: ERROR[50403] };
  20. }
  21. if (settingPermission.length > 0 && settingPermission.every(item => !userPermission.includes(item))) {
  22. throw { errCode: ERROR[50403] };
  23. }
  24. }
  25. module.exports = async function() {
  26. const methodName = this.getMethodName();
  27. if (!(methodName in methodPermission)) {
  28. return;
  29. }
  30. const {
  31. auth,
  32. role,
  33. permission
  34. } = methodPermission[methodName];
  35. if (auth || role || permission) {
  36. await this.middleware.auth();
  37. }
  38. if (role && role.length === 0) {
  39. throw new Error('[AccessControl]Empty role array is not supported');
  40. }
  41. if (permission && permission.length === 0) {
  42. throw new Error('[AccessControl]Empty permission array is not supported');
  43. }
  44. return isAccessAllowed(this.authInfo, {
  45. role,
  46. permission
  47. })
  48. }