salix/back/models/notificationSubscription.js

72 lines
2.2 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;
const modifiedUser = await getUserToModify(user, models);
2022-12-27 13:32:19 +00:00
if (userId == modifiedUser.id || userId == modifiedUser.bossFk)
return;
else
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-05 13:13:42 +00:00
const modifiedUser = await getUserToModify(notificationId, models);
2022-12-27 13:32:19 +00:00
if (user == modifiedUser.id || modifiedUser.bossFk == user) {
2023-01-05 13:13:42 +00:00
await models.NotificationSubscription.destroyById(notificationId);
2022-12-27 13:32:19 +00:00
return;
} else
throw new UserError('You dont have permission to modify this user');
};
2023-01-05 13:13:42 +00:00
async function getUserToModify(notificationId = null, userFk = null, models) {
if (notificationId != null) {
const subscription = await models.NotificationSubscription.findById(notificationId);
const user = await subscription.userFk;
return await models.Worker.findOne({
fields: ['id', 'bossFk'],
where: {
id: user
}
});
} else {
return await models.Worker.findOne({
fields: ['id', 'bossFk'],
where: {
id: userFk
}
});
}
}
};