salix/back/models/notificationSubscription.js

75 lines
2.5 KiB
JavaScript
Raw Permalink Normal View History

2022-12-27 13:32:19 +00:00
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
2023-05-09 09:34:32 +00:00
require('../methods/notification/getList')(Self);
2022-12-27 13:32:19 +00:00
2023-05-09 09:34:32 +00:00
Self.observe('before save', async function(ctx) {
await checkModifyPermission(ctx);
2022-12-27 13:32:19 +00:00
});
2023-05-09 09:34:32 +00:00
Self.observe('before delete', async function(ctx) {
await checkModifyPermission(ctx);
2022-12-27 13:32:19 +00:00
});
2023-05-09 09:34:32 +00:00
async function checkModifyPermission(ctx) {
const models = Self.app.models;
2023-05-09 09:34:32 +00:00
const instance = ctx.instance;
const userId = ctx.options.accessToken.userId;
2023-01-18 06:41:10 +00:00
2023-05-09 09:34:32 +00:00
let notificationFk;
let workerId;
2023-05-09 09:34:32 +00:00
if (instance) {
notificationFk = instance.notificationFk;
workerId = instance.userFk;
} else {
const notificationSubscription = await models.NotificationSubscription.findById(ctx.where.id);
notificationFk = notificationSubscription.notificationFk;
workerId = notificationSubscription.userFk;
2023-01-05 13:13:42 +00:00
}
2023-05-09 09:34:32 +00:00
const worker = await models.Worker.findById(workerId, {fields: ['id', 'bossFk']});
const available = await Self.getAvailable(workerId);
const hasAcl = available.has(notificationFk);
2023-05-09 09:34:32 +00:00
if (!hasAcl || (userId != worker.id && userId != worker.bossFk))
throw new UserError('The notification subscription of this worker cant be modified');
}
Self.getAvailable = async function(userId, options) {
const availableNotificationsMap = new Map();
const models = Self.app.models;
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const roles = await models.RoleMapping.find({
fields: ['roleId'],
where: {principalId: userId}
}, myOptions);
const availableNotifications = await models.NotificationAcl.find({
fields: ['notificationFk', 'roleFk'],
include: {relation: 'notification'},
where: {
roleFk: {
inq: roles.map(role => role.roleId),
},
}
}, myOptions);
for (available of availableNotifications) {
availableNotificationsMap.set(available.notificationFk, {
id: null,
notificationFk: available.notificationFk,
name: available.notification().name,
description: available.notification().description,
active: false
});
}
return availableNotificationsMap;
};
};