salix/back/models/notificationSubscription.js

63 lines
2.0 KiB
JavaScript
Raw Normal View History

2022-12-27 13:32:19 +00:00
const UserError = require('vn-loopback/util/user-error');
module.exports = Self => {
2022-12-27 13:32:19 +00:00
Self.observe('before save', async function(ctx) {
const models = Self.app.models;
const userId = ctx.options.accessToken.userId;
const user = await ctx.instance.userFk;
2023-01-09 07:43:11 +00:00
const modifiedUser = await getUserToModify(null, user, models);
2022-12-27 13:32:19 +00:00
2023-01-18 06:41:10 +00:00
if (userId != modifiedUser.id && userId != modifiedUser.bossFk)
2022-12-27 13:32:19 +00:00
throw new UserError('You dont have permission to modify this user');
});
Self.remoteMethod('deleteNotification', {
2023-01-03 07:12:46 +00:00
description: 'Deletes a notification subscription',
2022-12-27 13:32:19 +00:00
accepts: [
{
arg: 'ctx',
type: 'object',
http: {source: 'context'}
},
{
2023-01-05 13:13:42 +00:00
arg: 'notificationId',
type: 'number',
required: true
2022-12-27 13:32:19 +00:00
},
],
returns: {
type: 'object',
root: true
},
http: {
verb: 'POST',
path: '/deleteNotification'
}
});
2023-01-05 13:13:42 +00:00
Self.deleteNotification = async function(ctx, notificationId) {
const models = Self.app.models;
2023-01-03 07:12:46 +00:00
const user = ctx.req.accessToken.userId;
2023-01-09 07:43:11 +00:00
const modifiedUser = await getUserToModify(notificationId, null, models);
2022-12-27 13:32:19 +00:00
2023-01-18 06:41:10 +00:00
if (user != modifiedUser.id && user != modifiedUser.bossFk)
2022-12-27 13:32:19 +00:00
throw new UserError('You dont have permission to modify this user');
2023-01-18 06:41:10 +00:00
await models.NotificationSubscription.destroyById(notificationId);
2022-12-27 13:32:19 +00:00
};
2023-01-18 06:41:10 +00:00
async function getUserToModify(notificationId, userFk, models) {
2023-01-18 08:06:17 +00:00
let userToModify = userFk;
if (notificationId) {
2023-01-05 13:13:42 +00:00
const subscription = await models.NotificationSubscription.findById(notificationId);
2023-01-18 08:06:17 +00:00
userToModify = subscription.userFk;
2023-01-05 13:13:42 +00:00
}
2023-01-18 08:06:17 +00:00
return await models.Worker.findOne({
fields: ['id', 'bossFk'],
where: {
id: userToModify
}
});
}
};