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