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

128 lines
3.1 KiB
JavaScript
Raw Normal View History

2020-10-31 20:16:58 +00:00
const SyncConnector = require('./sync-connector');
require('./sync-db');
require('./sync-sip');
require('./sync-ldap');
require('./sync-samba');
module.exports = class SyncEngine {
async init($) {
let accountConfig = await $.AccountConfig.findOne({
fields: ['homedir', 'shell', 'idBase']
});
let mailConfig = await $.MailConfig.findOne({
fields: ['domain']
});
let connectors = [];
for (let ConnectorClass of SyncConnector.connectors) {
let connector = new ConnectorClass();
Object.assign(connector, {
se: this,
$
});
if (!await connector.init()) continue;
connectors.push(connector);
}
Object.assign(this, {
connectors,
$,
accountConfig,
mailConfig
});
}
async deinit() {
for (let connector of this.connectors)
await connector.deinit();
}
async sync(userName, password, syncGroups) {
let {
$,
accountConfig,
mailConfig
} = this;
if (!userName) return;
userName = userName.toLowerCase();
// Skip conflicting users
if (['administrator', 'root'].indexOf(userName) >= 0)
return;
let user = await $.Account.findOne({
where: {name: userName},
fields: [
'id',
'nickname',
'email',
'lang',
'roleFk',
'sync',
'active',
'created',
'bcryptPassword',
'updated'
],
include: {
relation: 'roles',
scope: {
include: {
relation: 'inherits',
scope: {
fields: ['name']
}
}
}
}
});
let extraParams;
let hasAccount = false;
if (user) {
hasAccount = user.active
&& await $.UserAccount.exists(user.id);
extraParams = {
corporateMail: `${userName}@${mailConfig.domain}`,
uidNumber: accountConfig.idBase + user.id
};
}
let info = {
user,
extraParams,
hasAccount,
accountConfig,
mailConfig
};
let errs = [];
for (let connector of this.connectors) {
try {
await connector.sync(info, userName, password);
if (syncGroups)
await connector.syncGroups(user, userName);
} catch (err) {
errs.push(err);
}
}
if (errs.length) throw errs[0];
}
async getUsers() {
let usersToSync = new Set();
for (let connector of this.connectors)
await connector.getUsers(usersToSync);
return usersToSync;
}
};