56 lines
1.8 KiB
JavaScript
56 lines
1.8 KiB
JavaScript
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
module.exports = Self => {
|
|
Self.observe('before save', async ctx => {
|
|
const changes = ctx.currentInstance || ctx.instance;
|
|
|
|
await Self.hasGrant(ctx, changes.mailAlias);
|
|
});
|
|
|
|
Self.observe('before delete', async ctx => {
|
|
const mailAliasAccount = await Self.findById(ctx.where.id);
|
|
|
|
await Self.hasGrant(ctx, mailAliasAccount.mailAlias);
|
|
});
|
|
|
|
/**
|
|
* Checks if current user has
|
|
* grant to add/remove alias
|
|
*
|
|
* @param {Object} ctx - Request context
|
|
* @param {Interger} mailAlias - mailAlias id
|
|
* @return {Boolean} True for user with grant
|
|
*/
|
|
Self.hasGrant = async function(ctx, mailAlias) {
|
|
const models = Self.app.models;
|
|
const accessToken = {req: {accessToken: ctx.options.accessToken}};
|
|
const userId = accessToken.req.accessToken.userId;
|
|
|
|
const canEditAlias = await models.ACL.checkAccessAcl(accessToken, 'MailAliasAccount', 'canEditAlias', 'WRITE');
|
|
if (canEditAlias) return true;
|
|
|
|
const user = await models.VnUser.findById(userId, {fields: ['hasGrant']});
|
|
if (!user.hasGrant)
|
|
throw new UserError(`You don't have grant privilege`);
|
|
|
|
const account = await models.Account.findById(userId, {
|
|
fields: ['id'],
|
|
include: {
|
|
relation: 'aliases',
|
|
scope: {
|
|
fields: ['mailAlias']
|
|
}
|
|
}
|
|
});
|
|
|
|
const aliases = account.aliases().map(alias => alias.mailAlias);
|
|
|
|
const hasAlias = aliases.includes(mailAlias);
|
|
if (!hasAlias)
|
|
throw new UserError(`You cannot assign/remove an alias that you are not assigned to`);
|
|
|
|
return true;
|
|
};
|
|
};
|