salix/modules/account/back/models/role-config.js

107 lines
4.1 KiB
JavaScript
Raw Permalink Normal View History

module.exports = Self => {
Self.getSynchronizer = async function() {
let NODE_ENV = process.env.NODE_ENV;
if (!NODE_ENV || NODE_ENV == 'development')
return null;
2022-02-19 13:05:35 +00:00
return await Self.findOne({
fields: ['id', 'rolePrefix', 'userPrefix', 'userHost']
});
};
Object.assign(Self.prototype, {
async init() {
const [row] = await Self.rawSql('SELECT VERSION() AS `version`');
if (row.version.includes('MariaDB'))
this.dbType = 'MariaDB';
else
this.dbType = 'MySQL';
},
async syncUser(userName, info, password) {
let mysqlUser = userName;
2022-02-19 13:05:35 +00:00
if (this.dbType == 'MySQL')
mysqlUser = this.userPrefix + mysqlUser;
const [row] = await Self.rawSql(
`SELECT COUNT(*) AS nRows
FROM mysql.user
WHERE User = ?
AND Host = ?`,
2022-02-19 13:05:35 +00:00
[mysqlUser, this.userHost]
);
let userExists = row.nRows > 0;
let isUpdatable = true;
if (this.dbType == 'MariaDB') {
const [row] = await Self.rawSql(
`SELECT Priv AS priv
FROM mysql.global_priv
WHERE User = ?
AND Host = ?`,
2022-02-19 13:05:35 +00:00
[mysqlUser, this.userHost]
);
const priv = row && JSON.parse(row.priv);
2022-02-19 13:05:35 +00:00
isUpdatable = !row || (priv && priv.autogenerated);
}
if (!isUpdatable) {
console.warn(`RoleConfig.syncUser(): User '${userName}' cannot be updated, not managed by me`);
return;
}
if (info.hasAccount) {
if (password) {
if (!userExists) {
await Self.rawSql('CREATE USER ?@? IDENTIFIED BY ?',
2022-02-19 13:05:35 +00:00
[mysqlUser, this.userHost, password]);
2022-08-04 06:53:31 +00:00
await Self.rawSql(
`UPDATE mysql.global_priv
SET Priv = JSON_SET(Priv, '$.autogenerated' , TRUE)
WHERE User = ? AND Host = ?`,
[mysqlUser, this.userHost]
);
userExists = true;
} else {
switch (this.dbType) {
case 'MariaDB':
await Self.rawSql('ALTER USER ?@? IDENTIFIED BY ?',
2022-02-19 13:05:35 +00:00
[mysqlUser, this.userHost, password]);
break;
default:
await Self.rawSql('SET PASSWORD FOR ?@? = PASSWORD(?)',
2022-02-19 13:05:35 +00:00
[mysqlUser, this.userHost, password]);
}
}
}
if (userExists && this.dbType == 'MariaDB') {
2022-02-19 13:05:35 +00:00
let role = `${this.rolePrefix}${info.user.role().name}`;
try {
await Self.rawSql('REVOKE ALL, GRANT OPTION FROM ?@?',
2022-02-19 13:05:35 +00:00
[mysqlUser, this.userHost]);
} catch (err) {
if (err.code == 'ER_REVOKE_GRANTS')
console.warn(`${err.code}: ${err.sqlMessage}: ${err.sql}`);
else
throw err;
}
await Self.rawSql('GRANT ? TO ?@?',
2022-02-19 13:05:35 +00:00
[role, mysqlUser, this.userHost]);
if (role) {
await Self.rawSql('SET DEFAULT ROLE ? FOR ?@?',
2022-02-19 13:05:35 +00:00
[role, mysqlUser, this.userHost]);
} else {
await Self.rawSql('SET DEFAULT ROLE NONE FOR ?@?',
2022-02-19 13:05:35 +00:00
[mysqlUser, this.userHost]);
}
}
} else if (userExists)
2022-02-19 13:05:35 +00:00
await Self.rawSql('DROP USER ?@?', [mysqlUser, this.userHost]);
}
});
};