access-control.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. const methodPermission = require('../config/permission')
  2. const {
  3. ERROR
  4. } = require('../common/error')
  5. function isAccessAllowed (user, setting) {
  6. const {
  7. role: userRole = [],
  8. permission: userPermission = []
  9. } = user
  10. const {
  11. role: settingRole = [],
  12. permission: settingPermission = []
  13. } = setting
  14. if (userRole.includes('admin')) {
  15. return
  16. }
  17. if (
  18. settingRole.length > 0 &&
  19. settingRole.every(item => !userRole.includes(item))
  20. ) {
  21. throw {
  22. errCode: ERROR.PERMISSION_ERROR
  23. }
  24. }
  25. if (
  26. settingPermission.length > 0 &&
  27. settingPermission.every(item => !userPermission.includes(item))
  28. ) {
  29. throw {
  30. errCode: ERROR.PERMISSION_ERROR
  31. }
  32. }
  33. }
  34. module.exports = async function () {
  35. const methodName = this.getMethodName()
  36. if (!(methodName in methodPermission)) {
  37. return
  38. }
  39. const {
  40. auth,
  41. role,
  42. permission
  43. } = methodPermission[methodName]
  44. if (auth || role || permission) {
  45. await this.middleware.auth()
  46. }
  47. if (role && role.length === 0) {
  48. throw new Error('[AccessControl]Empty role array is not supported')
  49. }
  50. if (permission && permission.length === 0) {
  51. throw new Error('[AccessControl]Empty permission array is not supported')
  52. }
  53. return isAccessAllowed(this.authInfo, {
  54. role,
  55. permission
  56. })
  57. }