72 lines
2.1 KiB
JavaScript
72 lines
2.1 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 models = Self.app.models;
|
|
const myOptions = {};
|
|
let tx;
|
|
|
|
if (typeof options == 'object')
|
|
Object.assign(myOptions, options);
|
|
|
|
if (!myOptions.transaction) {
|
|
tx = await Self.beginTransaction({});
|
|
myOptions.transaction = tx;
|
|
};
|
|
|
|
try {
|
|
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) {
|
|
if (tx) await tx.rollback();
|
|
return;
|
|
}
|
|
|
|
await Self.rawSql(`
|
|
SELECT id
|
|
FROM account.user
|
|
WHERE id = ?
|
|
FOR UPDATE`, [user.id], myOptions);
|
|
|
|
await models.AccountConfig.syncUser(userName, password);
|
|
await models.UserSync.destroyById(userName, myOptions);
|
|
if (tx) await tx.commit();
|
|
} catch (err) {
|
|
if (tx) await tx.rollback();
|
|
throw err;
|
|
}
|
|
};
|
|
};
|