78 lines
2.4 KiB
JavaScript
78 lines
2.4 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) {
|
|
if (!(hasGrant != null || roleFk)) return;
|
|
|
|
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, {fields: ['hasGrant']}, myOptions);
|
|
|
|
if (!user.hasGrant)
|
|
throw new UserError(`You don't have grant privilege`);
|
|
|
|
const [userToUpdate] = await models.Account.find({
|
|
fields: ['id', 'name', 'hasGrant', 'roleFk', 'password'],
|
|
include: {
|
|
relation: 'role',
|
|
scope: {
|
|
fields: ['name']
|
|
}
|
|
},
|
|
where: {
|
|
id: id
|
|
}
|
|
}, myOptions);
|
|
|
|
if (hasGrant != null)
|
|
userToUpdate.hasGrant = hasGrant;
|
|
|
|
if (roleFk) {
|
|
const role = await models.Role.findById(roleFk, {fields: ['name']}, myOptions);
|
|
const hasRole = await models.Account.hasRole(userId, role.name, myOptions);
|
|
const hasRoleFromUser = await models.Account.hasRole(userId, userToUpdate.role().name, myOptions);
|
|
|
|
if (!hasRole || !hasRoleFromUser)
|
|
throw new UserError(`You don't own the role and you can't assign it to another user`);
|
|
|
|
userToUpdate.roleFk = roleFk;
|
|
}
|
|
|
|
await userToUpdate.save(userToUpdate);
|
|
await models.UserAccount.sync(userToUpdate.name);
|
|
};
|
|
};
|