46 lines
1.5 KiB
JavaScript
46 lines
1.5 KiB
JavaScript
|
|
const ForbiddenError = require('vn-loopback/util/forbiddenError');
|
|
|
|
module.exports = Self => {
|
|
Self.rewriteDbError(function(err) {
|
|
if (err.code === 'ER_DUP_ENTRY')
|
|
return new UserError(`You already have the mailAlias`);
|
|
return err;
|
|
});
|
|
|
|
Self.beforeRemote('create', async function(ctx) {
|
|
const mailAlias = ctx.args.data?.mailAlias;
|
|
if (!mailAlias) return;
|
|
await checkModifyPermission(ctx, mailAlias);
|
|
});
|
|
Self.beforeRemote('deleteById', async function(ctx) {
|
|
const instance = await Self.findById(ctx.args.id,
|
|
{fields: ['mailAlias']}
|
|
);
|
|
await checkModifyPermission(ctx, instance.mailAlias);
|
|
});
|
|
|
|
async function checkModifyPermission(ctx, mailAliasFk) {
|
|
const models = Self.app.models;
|
|
const userId = ctx.req.accessToken.userId;
|
|
|
|
const canEditAlias = await models.ACL.checkAccessAcl(ctx,
|
|
'MailAliasAccount', 'canEditAlias', 'WRITE');
|
|
if (canEditAlias) return;
|
|
|
|
const allowedRoles = await models.MailAliasAcl.find({
|
|
fields: ['roleFk'],
|
|
where: {mailAliasFk}
|
|
});
|
|
const nRoles = allowedRoles.length &&
|
|
await models.RoleMapping.count({
|
|
principalId: userId,
|
|
principalType: 'USER',
|
|
roleId: {inq: allowedRoles.map(x => x.roleFk)}
|
|
});
|
|
|
|
if (!nRoles)
|
|
throw new ForbiddenError('You are not allowed to modify the alias');
|
|
}
|
|
};
|