91 lines
2.1 KiB
JavaScript
Raw Permalink Normal View History

2021-09-07 09:45:45 +02:00
'use strict';
const _ = require('lodash');
const { async, errors } = require('@strapi/utils');
2021-09-07 09:45:45 +02:00
const { getService } = require('../utils');
2021-10-20 17:30:05 +02:00
const { validateDeleteRoleBody } = require('./validation/user');
2021-09-07 09:45:45 +02:00
const { ApplicationError, ValidationError } = errors;
const sanitizeOutput = async (role) => {
const { sanitizeLocalizationFields } = strapi.plugin('i18n').service('sanitize');
const schema = strapi.getModel('plugin::users-permissions.role');
return async.pipe(sanitizeLocalizationFields(schema))(role);
};
2021-09-07 09:45:45 +02:00
module.exports = {
/**
* Default action.
*
* @return {Object}
*/
async createRole(ctx) {
if (_.isEmpty(ctx.request.body)) {
2021-10-20 17:30:05 +02:00
throw new ValidationError('Request body cannot be empty');
2021-09-07 09:45:45 +02:00
}
await getService('role').createRole(ctx.request.body);
ctx.send({ ok: true });
},
async findOne(ctx) {
2021-09-07 09:45:45 +02:00
const { id } = ctx.params;
const role = await getService('role').findOne(id);
2021-09-07 09:45:45 +02:00
if (!role) {
return ctx.notFound();
}
const safeRole = await sanitizeOutput(role);
ctx.send({ role: safeRole });
2021-09-07 09:45:45 +02:00
},
async find(ctx) {
const roles = await getService('role').find();
2021-09-07 09:45:45 +02:00
const safeRoles = await Promise.all(roles.map(sanitizeOutput));
ctx.send({ roles: safeRoles });
2021-09-07 09:45:45 +02:00
},
async updateRole(ctx) {
const roleID = ctx.params.role;
if (_.isEmpty(ctx.request.body)) {
2021-10-20 17:30:05 +02:00
throw new ValidationError('Request body cannot be empty');
2021-09-07 09:45:45 +02:00
}
await getService('role').updateRole(roleID, ctx.request.body);
ctx.send({ ok: true });
},
async deleteRole(ctx) {
const roleID = ctx.params.role;
if (!roleID) {
2021-10-20 17:30:05 +02:00
await validateDeleteRoleBody(ctx.params);
2021-09-07 09:45:45 +02:00
}
// Fetch public role.
2024-03-13 15:40:30 +01:00
const publicRole = await strapi.db
2021-09-07 09:45:45 +02:00
.query('plugin::users-permissions.role')
.findOne({ where: { type: 'public' } });
const publicRoleID = publicRole.id;
// Prevent from removing the public role.
if (roleID.toString() === publicRoleID.toString()) {
2021-10-20 17:30:05 +02:00
throw new ApplicationError('Cannot delete public role');
2021-09-07 09:45:45 +02:00
}
await getService('role').deleteRole(roleID, publicRoleID);
ctx.send({ ok: true });
},
};