strapi-plugin-config-sync/server/types/user-role.js

77 lines
2.4 KiB
JavaScript
Raw Normal View History

2021-10-15 14:54:58 +02:00
const { sanitizeConfig } = require('../utils');
2021-10-14 16:37:32 +02:00
const ConfigType = require("../services/type");
2021-10-15 14:54:58 +02:00
const UserRolePermissionsConfigType = class UserRolePermissionsConfigType extends ConfigType {
2021-10-14 16:37:32 +02:00
/**
* Import a single role-permissions config file into the db.
*
* @param {string} configName - The name of the config file.
* @param {string} configContent - The JSON content of the config file.
* @returns {void}
*/
importSingle = async (configName, configContent) => {
// Check if the config should be excluded.
2021-10-15 14:54:58 +02:00
const shouldExclude = strapi.config.get('plugin.config-sync.exclude').includes(`${this.configPrefix}.${configName}`);
2021-10-14 16:37:32 +02:00
if (shouldExclude) return;
const roleService = strapi.plugin('users-permissions').service('role');
const role = await strapi
.query(this.queryString)
.findOne({ where: { type: configName } });
if (role && configContent === null) {
const publicRole = await strapi.query(this.queryString).findOne({ where: { type: 'public' } });
const publicRoleID = publicRole.id;
await roleService.deleteRole(role.id, publicRoleID);
return;
}
const users = role ? role.users : [];
configContent.users = users;
if (!role) {
await roleService.createRole(configContent);
} else {
await roleService.updateRole(role.id, configContent);
}
}
/**
* Get all role-permissions config from the db.
*
* @returns {object} Object with key value pairs of configs.
*/
getAllFromDatabase = async () => {
const UPService = strapi.plugin('users-permissions').service('users-permissions');
const roleService = strapi.plugin('users-permissions').service('role');
const [roles, plugins] = await Promise.all([
roleService.getRoles(),
UPService.getPlugins(),
]);
const rolesWithPermissions = await Promise.all(
roles.map(async (role) => roleService.getRole(role.id, plugins))
);
const configs = {};
rolesWithPermissions.map(({ id, ...config }) => {
// Check if the config should be excluded.
const shouldExclude = strapi.config.get('plugin.config-sync.exclude').includes(`${this.configPrefix}.${config.type}`);
if (shouldExclude) return;
2021-10-15 14:54:58 +02:00
config = sanitizeConfig(config);
2021-10-14 16:37:32 +02:00
configs[`${this.configPrefix}.${config.type}`] = config;
});
return configs;
}
};
2021-10-15 14:54:58 +02:00
module.exports = UserRolePermissionsConfigType;