78 lines
1.7 KiB
JavaScript
Raw Normal View History

2021-09-07 09:45:45 +02:00
'use strict';
const _ = require('lodash');
2021-10-20 17:30:05 +02:00
const { ApplicationError, ValidationError } = require('@strapi/utils').errors;
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
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();
}
ctx.send({ role });
},
async find(ctx) {
const roles = await getService('role').find();
2021-09-07 09:45:45 +02:00
ctx.send({ roles });
},
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.
const publicRole = await strapi
.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 });
},
};