salix/modules/account/back/methods/account/sync.js

50 lines
1.5 KiB
JavaScript

const ForbiddenError = require('vn-loopback/util/forbiddenError');
module.exports = Self => {
Self.remoteMethod('sync', {
description: 'Synchronizes the user with the other user databases',
accepts: [
{
arg: 'userName',
type: 'string',
description: 'The user name',
required: true
}, {
arg: 'password',
type: 'string',
description: 'The password'
}, {
arg: 'force',
type: 'boolean',
description: 'Whether to force synchronization'
}
],
http: {
path: `/:userName/sync`,
verb: 'PATCH'
}
});
Self.sync = async function(userName, password, force, options) {
const myOptions = {};
if (typeof options == 'object')
Object.assign(myOptions, options);
const models = Self.app.models;
const user = await models.VnUser.findOne({
fields: ['id', 'password'],
where: {name: userName}
}, myOptions);
if (user && password && !await user.hasPassword(password))
throw new ForbiddenError('Wrong password');
const isSync = !await models.UserSync.exists(userName, myOptions);
if (!force && isSync && user) return;
await models.AccountConfig.syncUser(userName, password);
await models.UserSync.destroyById(userName, myOptions);
};
};