const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.rewriteDbError(function(err) { if (err.code === 'ER_DUP_ENTRY') return new UserError(`You already have the mailAlias`); return err; }); Self.observe('before save', async ctx => { const changes = ctx.currentInstance || ctx.instance; await checkModifyPermission(ctx, changes.mailAlias); }); Self.observe('before delete', async ctx => { const mailAliasAccount = await Self.findById(ctx.where.id); await checkModifyPermission(ctx, mailAliasAccount.mailAlias); }); async function checkModifyPermission(ctx, mailAliasFk) { const userId = ctx.options.accessToken.userId; const models = Self.app.models; const roles = await models.RoleMapping.find({ fields: ['roleId'], where: {principalId: userId} }); const availableMailAlias = await models.MailAliasAcl.findOne({ fields: ['mailAliasFk'], include: {relation: 'mailAlias'}, where: { roleFk: { inq: roles.map(role => role.roleId), }, mailAliasFk } }); if (!availableMailAlias) throw new UserError('The alias cant be modified'); } };