Files
mbmanager-api/middlewares/permissionMiddleware.js
T
2024-12-22 16:52:30 +03:30

77 lines
2.5 KiB
JavaScript

const Permission = require('../components/permission/permissionModel')
const Role = require('../components/role/roleModel')
const AppError = require('../globalErrorHandler/AppError')
const catchAsync = require('../globalErrorHandler/catchAsync')
const User = require('../components/user/userModel')
const ErrorLocalization = require('../globalErrorHandler/errorLocalization')
const el = new ErrorLocalization()
let checker = (arr, target) => arr.includes(target)
const requires = (...permissions) => {
return async (req, res, next) => {
const role = await Role.findById(req.user.role)
const perm = await Permission.findOne({ key: permissions[0] })
const rolePerm = role?.permissions || []
const userPerm = req.user.extraPermissions || []
// some features: permission denied when all roles are not same --> we want to access user with either roles
if (
!checker(rolePerm, perm?._id) &&
!checker(userPerm, perm?._id) &&
role._id.toString() !== process.env.SUPER_ADMIN_ID
) {
throw new AppError('NoPermissionAccess', 403, {})
}
next()
}
}
const adminCheck = () => {
return async (req, res, next) => {
try {
const user = await User.findOne({
phoneNumber: req.body.phoneNumber,
}).populate('role')
if (!user) {
throw new AppError('UserDoesNotExist', 403, {})
}
const perm = await Permission.findOne(
{ key: 'admindashboard' },
null,
null
)
let rolePerm = user.role?.permissions || []
let userPerm = user.extraPermissions || []
// some features: permission denied when all roles are not same --> we want to access user with either roles
if (
!checker(rolePerm, perm?._id) &&
!checker(userPerm, perm?._id) &&
user.role?._id.toString() !== process.env.SUPER_ADMIN_ID
) {
throw new AppError('NoPermissionAccess', 403, {})
}
next()
} catch (err) {
console.log(err)
err.message = el.getErrorText(err.name, err.parameters, 'persian')
res.status(500).json({
status: 'error',
message:
err.message ||
'An error occurred while checking permissions.',
})
}
}
}
module.exports = {
checker,
requires,
adminCheck,
}