const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateUser', { description: 'Updates the user information', accepts: [ { arg: 'id', type: 'number', description: 'The user id' }, { arg: 'name', type: 'string', description: 'the user name' }, { arg: 'email', type: 'any', description: 'the user email' }, { arg: 'active', type: 'boolean', description: 'whether the user is active or not' }, ], http: { path: '/:id/updateUser', verb: 'PATCH' } }); Self.updateUser = async function(ctx, id, options) { const models = Self.app.models; const userId = ctx.req.accessToken.userId; let tx; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); if (!myOptions.transaction) { tx = await models.Account.beginTransaction({}); myOptions.transaction = tx; } try { const isSalesPerson = await models.Account.hasRole(userId, 'salesPerson', myOptions); if (!isSalesPerson) throw new UserError(`Not enough privileges to edit a client`); const isClient = await models.Client.findById(id, null, myOptions); const isUserAccount = await models.UserAccount.findById(id, null, myOptions); if (isClient && !isUserAccount) { const user = await models.Account.findById(id, null, myOptions); await user.updateAttributes(ctx.args, myOptions); } else throw new UserError(`Modifiable user details only by an administrator`); if (tx) await tx.commit(); } catch (e) { if (tx) await tx.rollback(); throw e; } }; };