salix/modules/account/back/util/sync-db.js

58 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-10-31 20:16:58 +00:00
const SyncConnector = require('./sync-connector');
class SyncDb extends SyncConnector {
async sync(info, userName, password) {
let {$} = this;
let {user} = info;
if (user && user.active) {
let bcryptPassword = password
? $.User.hashPassword(password)
: user.bcryptPassword;
await $.Account.upsertWithWhere({id: user.id},
{bcryptPassword}
);
let dbUser = {
id: user.id,
username: userName,
email: user.email,
created: user.created,
updated: user.updated
};
if (bcryptPassword)
dbUser.password = bcryptPassword;
if (await $.user.exists(user.id))
await $.user.replaceById(user.id, dbUser);
else
await $.user.create(dbUser);
} else
await $.user.destroyAll({username: userName});
}
async getUsers(usersToSync) {
let accounts = await this.$.UserAccount.find({
fields: ['id'],
include: {
relation: 'user',
scope: {
fields: ['name'],
where: {active: true}
}
}
});
for (let account of accounts) {
let user = account.user();
if (!user) continue;
usersToSync.add(user.name);
}
}
}
SyncConnector.connectors.push(SyncDb);
module.exports = SyncDb;