59 lines
1.8 KiB
JavaScript
59 lines
1.8 KiB
JavaScript
|
const UserError = require('vn-loopback/util/user-error');
|
||
|
|
||
|
module.exports = Self => {
|
||
|
Self.remoteMethodCtx('privileges', {
|
||
|
description: 'Change role and hasGrant if user has privileges',
|
||
|
accepts: [
|
||
|
{
|
||
|
arg: 'id',
|
||
|
type: 'number',
|
||
|
required: true,
|
||
|
description: 'The user id',
|
||
|
http: {source: 'path'}
|
||
|
},
|
||
|
{
|
||
|
arg: 'roleFk',
|
||
|
type: 'number',
|
||
|
description: 'The new role for user',
|
||
|
},
|
||
|
{
|
||
|
arg: 'hasGrant',
|
||
|
type: 'boolean',
|
||
|
description: 'Whether to has grant'
|
||
|
}
|
||
|
],
|
||
|
http: {
|
||
|
path: `/:id/privileges`,
|
||
|
verb: 'POST'
|
||
|
}
|
||
|
});
|
||
|
|
||
|
Self.privileges = async function(ctx, id, roleFk, hasGrant, options) {
|
||
|
const models = Self.app.models;
|
||
|
const userId = ctx.req.accessToken.userId;
|
||
|
|
||
|
const myOptions = {};
|
||
|
|
||
|
if (typeof options == 'object')
|
||
|
Object.assign(myOptions, options);
|
||
|
|
||
|
const user = await models.Account.findById(userId, null, myOptions);
|
||
|
|
||
|
if (!user.hasGrant)
|
||
|
throw new UserError(`You don't have enough privileges`);
|
||
|
|
||
|
const userToUpdate = await models.Account.findById(id);
|
||
|
if (hasGrant != null)
|
||
|
return await userToUpdate.updateAttribute('hasGrant', hasGrant, myOptions);
|
||
|
if (!roleFk) return;
|
||
|
|
||
|
const role = await models.Role.findById(roleFk, null, myOptions);
|
||
|
const hasRole = await models.Account.hasRole(userId, role.name, myOptions);
|
||
|
|
||
|
if (!hasRole)
|
||
|
throw new UserError(`You don't have enough privileges`);
|
||
|
|
||
|
await userToUpdate.updateAttribute('roleFk', roleFk, myOptions);
|
||
|
};
|
||
|
};
|