2023-07-12 11:55:57 +00:00
|
|
|
|
|
|
|
const UserError = require('vn-loopback/util/user-error');
|
|
|
|
|
|
|
|
module.exports = Self => {
|
2023-07-12 13:07:06 +00:00
|
|
|
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);
|
|
|
|
});
|
2023-07-12 11:55:57 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Checks if current user has
|
2023-07-12 12:04:17 +00:00
|
|
|
* grant to add/remove alias
|
2023-07-12 11:55:57 +00:00
|
|
|
*
|
|
|
|
* @param {Object} ctx - Request context
|
|
|
|
* @param {Interger} mailAlias - mailAlias id
|
|
|
|
* @return {Boolean} True for user with grant
|
|
|
|
*/
|
2023-07-12 13:07:06 +00:00
|
|
|
Self.hasGrant = async function(ctx, mailAlias) {
|
2023-07-12 11:55:57 +00:00
|
|
|
const models = Self.app.models;
|
2023-07-12 13:07:06 +00:00
|
|
|
const accessToken = {req: {accessToken: ctx.options.accessToken}};
|
|
|
|
const userId = accessToken.req.accessToken.userId;
|
2023-07-12 11:55:57 +00:00
|
|
|
|
2023-07-12 13:07:06 +00:00
|
|
|
const canEditAlias = await models.ACL.checkAccessAcl(accessToken, 'MailAliasAccount', 'canEditAlias', 'WRITE');
|
2023-07-12 11:55:57 +00:00
|
|
|
if (canEditAlias) return true;
|
|
|
|
|
2023-07-12 13:07:06 +00:00
|
|
|
const user = await models.VnUser.findById(userId, {fields: ['hasGrant']});
|
2023-07-12 11:55:57 +00:00
|
|
|
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']
|
|
|
|
}
|
|
|
|
}
|
2023-07-12 13:07:06 +00:00
|
|
|
});
|
2023-07-12 11:55:57 +00:00
|
|
|
|
|
|
|
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;
|
|
|
|
};
|
|
|
|
};
|