access-control.js 1.3 KB
Newer Older
study夏羽's avatar
study夏羽 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
const methodPermission = require('../config/permission')
const {
  ERROR
} = require('../common/error')

function isAccessAllowed (user, setting) {
  const {
    role: userRole = [],
    permission: userPermission = []
  } = user
  const {
    role: settingRole = [],
    permission: settingPermission = []
  } = setting
  if (userRole.includes('admin')) {
    return
  }
  if (
    settingRole.length > 0 &&
    settingRole.every(item => !userRole.includes(item))
  ) {
    throw {
      errCode: ERROR.PERMISSION_ERROR
    }
  }
  if (
    settingPermission.length > 0 &&
    settingPermission.every(item => !userPermission.includes(item))
  ) {
    throw {
      errCode: ERROR.PERMISSION_ERROR
    }
  }
}

module.exports = async function () {
  const methodName = this.getMethodName()
  if (!(methodName in methodPermission)) {
    return
  }
  const {
    auth,
    role,
    permission
  } = methodPermission[methodName]
  if (auth || role || permission) {
    await this.middleware.auth()
  }
  if (role && role.length === 0) {
    throw new Error('[AccessControl]Empty role array is not supported')
  }
  if (permission && permission.length === 0) {
    throw new Error('[AccessControl]Empty permission array is not supported')
  }
  return isAccessAllowed(this.authInfo, {
    role,
    permission
  })
}