/var/www/p4ela.kz/server/delivery/services
Edit: /var/www/p4ela.kz/server/delivery/services/auth.service.js (2522B)
const logger = require('../logger')({ service: 'OrderService' })
const { Op } = require('sequelize')
const { Forbidden, Unauthorized, BadRequest, ApiError } = require('../api/responseModels/errors')
module.exports = class AuthService {
constructor({ db, config }) {
this.db = db
this.config = config
this.permissions = []
logger.child({ service: 'AuthService', method: 'Constructor' }).info('Success')
}
async Run() {
let permissions = await this.db.permission.findAll({
include: [
{ model: this.db.role }
]
})
for (let p of permissions) {
for (const r of p.roles) {
const idx = this.permissions.findIndex(x => x.roleId === r.id && x.permissionId === p.id)
if (idx === -1) this.permissions.push({
roleId: r.id,
permissionId: p.id,
key: p.key
})
}
}
}
GetPermissions() { return this.permissions }
GetPermissionsByRole(roleId) { return this.permissions.filter(x => x.roleId === roleId) }
CheckUserPermissions(options) {
const { user, key, companyId, branchId } = options
if (!user) throw new Forbidden()
if (!key) throw new Forbidden()
if(user.roleKey === 'su') return
// проверка по роли пользователя
if (user.roleId > 0) {
const idx = this.permissions.findIndex(x => x.key === key && parseInt(x.roleId) === parseInt(user.roleId))
if (idx !== -1) return
}
// проверка по роли в компании
if (companyId) {
const companyRole = user.companies?.find(x => x.companyId === parseInt(companyId))
if (companyRole) {
const idx = this.permissions.findIndex(x => x.key === key && parseInt(x.roleId) === parseInt(companyRole.roleId))
if (idx !== -1) return
}
}
// проверка по роли в филиале
if (branchId) {
const branchRole = user.branches.find(x => x.branchId === parseInt(branchId))
if (!branchRole) throw new Forbidden()
const idx = this.permissions.findIndex(x => x.key === key && parseInt(x.roleId) === parseInt(branchRole.roleId))
if (idx !== -1) return
}
// нет разрещения
throw new Forbidden()
}
}