Skip to content

Commit

Permalink
Refactor permission module.
Browse files Browse the repository at this point in the history
  • Loading branch information
HranikBs23 committed Feb 23, 2022
1 parent 7e31156 commit 655b2ab
Show file tree
Hide file tree
Showing 4 changed files with 128 additions and 104 deletions.
219 changes: 117 additions & 102 deletions src/modules/platform/permission/permission.controller.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,60 @@
const path = require('path');
const Permission = require("./permission.model");
const Permission = require(path.join(process.cwd(), 'src/modules/platform/permission/permission.model'));
const Service = require(path.join(process.cwd(), 'src/modules/platform/service/service.model'));
const User = require(path.join(process.cwd(), 'src/modules/platform/user/user.model'));
const ProfilePermission = require(path.join(process.cwd(), 'src/modules/platform/permission/profile-permission.model'));
const RolePermission = require(path.join(process.cwd(), 'src/modules/platform/permission/role-permission.model'));
const { makeCustomSlug } = require(path.join(process.cwd(), 'src/modules/core/services/slug'));
const PermissionService = require("./permission-service.model");
const PermissionService = require(path.join(process.cwd(), 'src/modules/platform/permission/permission-service.model'));


async function getPermissions(req, res) {
try {
const page = req.query.page ? req.query.page - 1 : 0;
if (page < 0) return res.status(404).send("page must be greater or equal 1");

const limit = req.query.limit ? +req.query.limit : 15;
const offset = page * limit;

const orderBy = req.query.orderBy ? req.query.orderBy : null;
const orderType = req.query.orderType === "asc" || req.query.orderType === "desc" ? req.query.orderType : "asc";

const order = [
["created_at", "DESC"],
["id", "DESC"]
];

const sortableColumns = [
"title",
"slug",
"type",
"description",
"created_at"
];

if (orderBy && sortableColumns.includes(orderBy)) {
order.splice(0, 0, [orderBy, orderType]);
}

if (orderBy === "created_by") {
order.splice(0, 0, [
{ model: User, as: "createdByUser" },
"first_name",
orderType
]);
order.splice(1, 0, [
{ model: User, as: "createdByUser" },
"last_name",
orderType
]);
}

// const filterOptions = { id: { [Op.ne]: req.user.id } };

const permissions = await Permission.findAll({
offset,
limit,
order,
include: [
{
model: PermissionService,
Expand All @@ -22,13 +67,36 @@ async function getPermissions(req, res) {
attributes: ["id", "title", "slug"]
}
]
}
},
{
model: User,
as: "createdByUser",
attributes: ["id", "first_name", "last_name"]
},
{
model: User,
as: "updatedByUser",
attributes: ["id", "first_name", "last_name"]
},
]
});

if (!permissions) return res.status(404).send("Permissions not found");
res.status(200).send(permissions);
const totalPermissions = Permission.count();

const data = {
permissions,
metaData: {
page: page + 1,
limit: limit,
total: totalPermissions,
start: limit * page + 1,
end: offset + limit > totalPermissions ? totalPermissions : offset + limit,
}
}

res.status(200).send(data);
} catch (err) {
console.log(err);
return res.status(500).send("Internal server error.");
}
}
Expand All @@ -54,7 +122,17 @@ async function getPermission(req, res) {
attributes: ["id", "title", "slug"]
}
]
}
},
{
model: User,
as: "createdByUser",
attributes: ["id", "first_name", "last_name"]
},
{
model: User,
as: "updatedByUser",
attributes: ["id", "first_name", "last_name"]
},
]
}
);
Expand All @@ -71,9 +149,7 @@ async function getPermission(req, res) {

async function createPermission(req, res) {
try {
const userId = req.user.id;
const { title, type, description, services } = req.body;

const slug = makeCustomSlug(title);

const existingPermission = await Permission.findOne({
Expand All @@ -89,17 +165,21 @@ async function createPermission(req, res) {
slug,
type,
description,
created_by: userId,
updated_by: userId
created_by: req.user.id,
updated_by: req.user.id
});


services.forEach(async id =>
await PermissionService.create({
permission_id: permission.id,
service_id: id
})
);
services.forEach(async id => {
const service = await Service.findOne({ where: { id }});

if(service) {
await PermissionService.create({
permission_id: permission.id,
service_id: service.id
});
}
});


res.status(201).send(permission);
Expand All @@ -112,13 +192,10 @@ async function createPermission(req, res) {

async function updatePermission(req, res) {
try {
const { id } = req.params;
const { title, type, description, services } = req.body;

const permission = await Permission.findOne({
where: {
id
},
where: { id: req.params.id },
include: [
{
model: PermissionService,
Expand All @@ -135,36 +212,28 @@ async function updatePermission(req, res) {
}

if (type) await permission.update({ type });

if (description) await permission.update({ description });

if (services) {

permission.permission_services.forEach( async service => {
await PermissionService.destroy({where:{permission_id:permission.id}})
})
permission.permission_services.forEach( async () => {
await PermissionService.destroy({ where: { permission_id: permission.id }})
});

services.forEach(async serviceId => {
await PermissionService.create({
permission_id: permission.id,
service_id: serviceId
});
const service = await Service.findOne({ where: { id: serviceId }});

if(service) {
await PermissionService.create({
permission_id: permission.id,
service_id: service.id
});
}
});
}

// const updatedPermission = await Permission.findOne({
// where: {
// id
// },
// include: [
// {
// model: PermissionService,
// as: "permission_services"
// }
// ]
// });

res.status(201).send(permission);

} catch (err) {
console.log(err)
return res.status(500).send("Internal server error.");
Expand All @@ -173,73 +242,19 @@ async function updatePermission(req, res) {

async function deletePermission(req,res) {
try{
const {id} = req.params;

const permission = await Permission.findOne({
where:{
id,
},
include: [
{
model: PermissionService,
as: "permission_services"
}
]
})

if(!permission) return res.status(404).send('Permission not found!');

if(permission.type == "standard") return res.status(400).send("Standard permission can not be deleted.")



const rolePermissions = await RolePermission.findAll({
where: {
permission_id:permission.id
}
});

if(rolePermissions.length > 0){
rolePermissions.forEach( rolePermission =>{
rolePermission.destroy();
});
};

const profilePermissions = await ProfilePermission.findAll({
where: {
permission_id:permission.id
}
});

if(profilePermissions.length > 0){
profilePermissions.forEach( profilePermission =>{
profilePermission.destroy();
});
};

const permissionServices = await PermissionService.findAll({
where: {
permission_id:permission.id
}
});

if(permissionServices.length > 0){
permissionServices.forEach( permissionService =>{
permissionService.destroy();
});
};
const { id: permissionId } = req.params;

const rolePermissions = await RolePermission.findAll({ where: { permission_id: permissionId }});
if(rolePermissions.length > 0) return res.status(400).send('Permission assigned to roles.');

// permission.permission_services.forEach( async service => {
const profilePermissions = await ProfilePermission.findAll({ where: { permission_id: permissionId }});
if(profilePermissions.length > 0) return res.status(400).send('Permission assigned to profiles.');

// await PermissionService.destroy({where:{permission_id:permission.id}});
// await RolePermission.destroy({where:{permission_id:permission.id}});
// await ProfilePermission.destroy({where:{permission_id:permission.id}});
const permission = await Permission.findOne({ where: { id: permissionId, type: { [Op.ne]: 'standard' } }});
if(!permission) return res.status(404).send('Permission not found.');

// })


await permission.destroy();
await PermissionService.destroy({ where: { permission_id: permission.id }});

res.status(200).send(permission);
}
Expand Down
2 changes: 2 additions & 0 deletions src/modules/platform/permission/permission.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ const Permission = sequelize.define('permissions', {
type: DataTypes.STRING(500)
},
created_by: {
allowNull: false,
type: DataTypes.UUID
},
updated_by: {
allowNull: false,
type: DataTypes.UUID
}
}, {
Expand Down
7 changes: 5 additions & 2 deletions src/modules/platform/permission/permission.schema.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@ const permissionCreateSchema = object().shape({
.oneOf(Object.values(types)),
description: string().max(500, "Description must be at most 500 characters long.")
.required("Description is required."),
services: array().
min(1, 'At least one permission service is required.')
services: array()
.of(string())
.min(1, 'At least one permission service is required.')
});

const permissionUpdateSchema = object().shape({
Expand All @@ -23,6 +24,8 @@ const permissionUpdateSchema = object().shape({
.oneOf(Object.values(types)),
description: string().max(500, "Description must be at most 500 characters long."),
services: array()
.of(string())
.min(1, 'At least one permission service is required.')
});

module.exports.permissionCreateSchema = permissionCreateSchema;
Expand Down
4 changes: 4 additions & 0 deletions src/modules/platform/user/user.model.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const sequelize = require(path.join(process.cwd(), "src/config/lib/sequelize"));
const { DataTypes } = require("sequelize");
const Profile = require(path.join(process.cwd(), "src/modules/platform/profile/profile.model"));
const Role = require(path.join(process.cwd(), "src/modules/platform/role/role.model"));
const Permission = require(path.join(process.cwd(), "src/modules/platform/permission/permission.model"));
const User = sequelize.define("users", {
id: {
allowNull: false,
Expand Down Expand Up @@ -87,4 +88,7 @@ User.belongsTo(Profile, { as: 'profile', foreignKey: 'profile_id' });
Role.hasMany(User, { as: 'users', foreignKey: 'role_id' });
User.belongsTo(Role, { as: 'role', foreignKey: 'role_id' });

Permission.belongsTo(User, { as: 'createdByUser', foreignKey: 'created_by' });
Permission.belongsTo(User, { as: 'updatedByUser', foreignKey: 'created_by' });

module.exports = User;

0 comments on commit 655b2ab

Please sign in to comment.