Files
Zumri-Backend/app/controllers/permission.controller.js
T
Isuru Bimsara 81d0e65686 first commit
2026-08-14 22:46:02 +05:30

869 lines
21 KiB
JavaScript

/**
* Copyright (c) 2026 Niolla
* All rights reserved.
*
* This source code is proprietary and confidential.
* Unauthorized copying, modification, distribution, or use
* of this file, via any medium, is strictly prohibited.
*/
// app/controllers/permission.controller.js
// PERMISSIONS:
// 1. createPermission --> Done
// 2. getAllPermissions --> Done
// 3. getPermissionById --> Done
// 4. updatePermission --> Done
// 5. deletePermission --> Done
// ROLES:
// 1. createRole --> Done
// 2. createRolePermission --> Done
// 3. getAllRoles --> Done
// 4. getRoleById --> Done
// 5. updateRole --> Done
// 6. deleteRole --> Done
// USER PERMISSIONS:
// 1. getUserPermissions --> Done
const db = require("../models");
const User = db.User;
const Role = db.roles;
const Permission = db.permission;
const RolePermission = db.rolePermission;
const UserPermission = db.userPermission;
// Create a new permission
exports.createPermission = async (req, res) => {
try {
const { permissionName, permissionDescription, page, module, action } = req.body;
if (!permissionName || !page || !module || !action) {
return res.status(400).json({ message: "Permission name, page, module, and action are required" });
}
const permissionId = `${module}.${page}.${action}`;
// Check if permission already exists
const existingPermission = await Permission.findOne({ where: { permission_id: permissionId } });
if (existingPermission) {
return res.status(400).json({ message: "Permission already exists" });
}
// Create the new permission
const newPermission = await Permission.create({
permission_id: permissionId,
permissionName,
permissionDescription,
page,
module,
action
});
res.status(201).json({
success: true,
data: newPermission
});
} catch (error) {
console.error("Error creating permission:", error);
res.status(500).json({ message: "Internal server error" });
}
};
// Bulk create permissions
exports.bulkCreatePermissions = async (req, res) => {
try {
const { permissions } = req.body;
if (!permissions || !Array.isArray(permissions) || permissions.length === 0) {
return res.status(400).json({
success: false,
message: "Permissions array is required and must not be empty"
});
}
const results = {
created: [],
failed: []
};
for (const item of permissions) {
try {
const { permissionName, permissionDescription, page, module, action } = item;
if (!permissionName || !page || !module || !action) {
results.failed.push({
...item,
error: "Permission name, page, module, and action are required"
});
continue;
}
const permissionId = `${module}.${page}.${action}`;
// Check if permission already exists
const existingPermission = await Permission.findOne({ where: { permission_id: permissionId } });
if (existingPermission) {
results.failed.push({
...item,
error: "Permission already exists"
});
continue;
}
const newPermission = await Permission.create({
permission_id: permissionId,
permissionName,
permissionDescription,
page,
module,
action
});
results.created.push(newPermission);
} catch (itemError) {
results.failed.push({
...item,
error: itemError.message
});
}
}
res.status(201).json({
success: results.failed.length === 0,
data: results
});
} catch (error) {
console.error("Error bulk creating permissions:", error);
res.status(500).json({
success: false,
message: "An error occurred while bulk creating permissions."
});
}
};
// Get all permissions
exports.getAllPermissions = async (req, res) => {
try {
const permissions = await Permission.findAll();
res.status(200).json({
success: true,
data: permissions
});
} catch (error) {
console.error("Error fetching permissions:", error);
res.status(500).json({
success: false,
message: "An error occurred while fetching permissions."
});
}
};
// Get permission by ID
exports.getPermissionById = async (req, res) => {
try {
const { permissionId } = req.params;
const permission = await Permission.findByPk(permissionId);
if (!permission) {
return res.status(404).json({
success: false,
message: "Permission not found"
});
}
res.status(200).json({
success: true,
data: permission
});
} catch (error) {
console.error("Error fetching permission:", error);
res.status(500).json({
success: false,
message: "An error occurred while fetching permission."
});
}
};
// Update permission
exports.updatePermission = async (req, res) => {
try {
const { permissionId } = req.params;
const { permissionName, permissionDescription, page, module, action } = req.body;
const permission = await Permission.findByPk(permissionId);
if (!permission) {
return res.status(404).json({
success: false,
message: "Permission not found"
});
}
// Update permission fields
await permission.update({
permissionName: permissionName || permission.permissionName,
permissionDescription: permissionDescription || permission.permissionDescription,
page: page || permission.page,
module: module || permission.module,
action: action || permission.action
});
res.status(200).json({
success: true,
data: permission,
message: "Permission updated successfully"
});
} catch (error) {
console.error("Error updating permission:", error);
res.status(500).json({
success: false,
message: "An error occurred while updating permission."
});
}
};
// Delete permission
exports.deletePermission = async (req, res) => {
try {
const { permissionId } = req.params;
const permission = await Permission.findByPk(permissionId);
if (!permission) {
return res.status(404).json({
success: false,
message: "Permission not found"
});
}
// Delete associated user and role permissions first
await UserPermission.destroy({ where: { permission_id: permissionId } });
await RolePermission.destroy({ where: { permission_id: permissionId } });
// Delete the permission
await permission.destroy();
res.status(200).json({
success: true,
message: "Permission deleted successfully"
});
} catch (error) {
console.error("Error deleting permission:", error);
res.status(500).json({
success: false,
message: "An error occurred while deleting permission."
});
}
};
// Create a new role
exports.createRole = async (req, res) => {
try {
const { roleName, roleDescription } = req.body;
if (!roleName) {
return res.status(400).json({
success: false,
message: "Role name is required"
});
}
// Generate role ID
const roleId = `role_${Date.now()}`;
const newRole = await Role.create({
role_id: roleId,
roleName,
roleDescription
});
res.status(201).json({
success: true,
data: newRole
});
} catch (error) {
console.error("Error creating role:", error);
res.status(500).json({
success: false,
message: "An error occurred while creating role."
});
}
};
// Create role-permission assignment
exports.createRolePermission = async (req, res) => {
try {
const { role_id, permission_id } = req.body;
if (!role_id || !permission_id) {
return res.status(400).json({
success: false,
message: "Role ID and Permission ID are required"
});
}
// Verify role and permission exist
const role = await Role.findByPk(role_id);
if (!role) {
return res.status(404).json({
success: false,
message: "Role not found"
});
}
const permission = await Permission.findByPk(permission_id);
if (!permission) {
return res.status(404).json({
success: false,
message: "Permission not found"
});
}
// Check if assignment already exists
const existingAssignment = await RolePermission.findOne({
where: { role_id, permission_id }
});
if (existingAssignment) {
return res.status(400).json({
success: false,
message: "Role permission already exists"
});
}
const rpId = `rp_${Date.now()}`;
const newRolePermission = await RolePermission.create({
rp_id: rpId,
role_id,
permission_id
});
res.status(201).json({
success: true,
data: newRolePermission
});
} catch (error) {
console.error("Error creating role permission:", error);
res.status(500).json({
success: false,
message: "An error occurred while creating role permission."
});
}
};
// Bulk create role permissions
exports.bulkCreateRolePermissions = async (req, res) => {
try {
const { role_id, permission_ids } = req.body;
if (!role_id || !permission_ids || !Array.isArray(permission_ids) || permission_ids.length === 0) {
return res.status(400).json({
success: false,
message: "Role ID and permission_ids array are required and must not be empty"
});
}
// Verify role exists
const role = await Role.findByPk(role_id);
if (!role) {
return res.status(404).json({
success: false,
message: "Role not found"
});
}
const results = {
created: [],
failed: []
};
for (const permission_id of permission_ids) {
try {
if (!permission_id) {
results.failed.push({
role_id,
permission_id,
error: "Permission ID is required"
});
continue;
}
// Verify permission exists
const permission = await Permission.findByPk(permission_id);
if (!permission) {
results.failed.push({
role_id,
permission_id,
error: "Permission not found"
});
continue;
}
// Check if assignment already exists
const existingAssignment = await RolePermission.findOne({
where: { role_id, permission_id }
});
if (existingAssignment) {
results.failed.push({
role_id,
permission_id,
error: "Role permission already exists"
});
continue;
}
const rpId = `rp_${Date.now()}`;
const newRolePermission = await RolePermission.create({
rp_id: rpId,
role_id,
permission_id
});
results.created.push(newRolePermission);
} catch (itemError) {
results.failed.push({
role_id,
permission_id,
error: itemError.message
});
}
}
res.status(201).json({
success: results.failed.length === 0,
data: results
});
} catch (error) {
console.error("Error bulk creating role permissions:", error);
res.status(500).json({
success: false,
message: "An error occurred while bulk creating role permissions."
});
}
};
// Get all roles
exports.getAllRoles = async (req, res) => {
try {
const roles = await Role.findAll({
include: [
{
model: RolePermission,
as: "rolePermissions",
include: [
{
model: Permission,
as: "permission",
attributes: ["permission_id", "permissionName", "page", "module", "action"]
}
]
}
]
});
res.status(200).json({
success: true,
data: roles
});
} catch (error) {
console.error("Error fetching roles:", error);
res.status(500).json({
success: false,
message: "An error occurred while fetching roles."
});
}
};
// Get role by ID
exports.getRoleById = async (req, res) => {
try {
const { roleId } = req.params;
const role = await Role.findByPk(roleId, {
include: [
{
model: RolePermission,
as: "rolePermissions",
include: [
{
model: Permission,
as: "permission",
attributes: ["permission_id", "permissionName", "page", "module", "action"]
}
]
}
]
});
if (!role) {
return res.status(404).json({
success: false,
message: "Role not found"
});
}
res.status(200).json({
success: true,
data: role
});
} catch (error) {
console.error("Error fetching role:", error);
res.status(500).json({
success: false,
message: "An error occurred while fetching role."
});
}
};
// Update role
exports.updateRole = async (req, res) => {
try {
const { roleId } = req.params;
const { roleName, roleDescription } = req.body;
const role = await Role.findByPk(roleId);
if (!role) {
return res.status(404).json({
success: false,
message: "Role not found"
});
}
// Update role fields
await role.update({
roleName: roleName || role.roleName,
roleDescription: roleDescription || role.roleDescription
});
res.status(200).json({
success: true,
data: role,
message: "Role updated successfully"
});
} catch (error) {
console.error("Error updating role:", error);
res.status(500).json({
success: false,
message: "An error occurred while updating role."
});
}
};
// Delete role
exports.deleteRole = async (req, res) => {
try {
const { roleId } = req.params;
const role = await Role.findByPk(roleId);
if (!role) {
return res.status(404).json({
success: false,
message: "Role not found"
});
}
// Delete associated role permissions first
await RolePermission.destroy({ where: { role_id: roleId } });
// Delete the role
await role.destroy();
res.status(200).json({
success: true,
message: "Role deleted successfully"
});
} catch (error) {
console.error("Error deleting role:", error);
res.status(500).json({
success: false,
message: "An error occurred while deleting role."
});
}
};
// Get user permissions
exports.getUserPermissions = async (req, res) => {
try {
const userId = req.params.userId;
// Fetch user permissions
const userPermissions = await UserPermission.findAll({
where: { user_id: userId },
include: [
{
model: Permission,
as: "permission",
attributes: ["permission_id", "permissionName", "page", "module", "action"]
}
]
});
res.status(200).json({
success: true,
data: userPermissions
});
} catch (error) {
console.error("Error fetching user permissions:", error);
res.status(500).json({
success: false,
message: "An error occurred while fetching user permissions."
});
}
};
// Create user permission
exports.createUserPermission = async (req, res) => {
try {
const { user_id, permission_id } = req.body;
if (!user_id || !permission_id) {
return res.status(400).json({
success: false,
message: "User ID and Permission ID are required"
});
}
// Verify user and permission exist
const user = await User.findByPk(user_id);
if (!user) {
return res.status(404).json({
success: false,
message: "User not found"
});
}
const permission = await Permission.findByPk(permission_id);
if (!permission) {
return res.status(404).json({
success: false,
message: "Permission not found"
});
}
// Check if assignment already exists
const existingAssignment = await UserPermission.findOne({
where: { user_id, permission_id }
});
if (existingAssignment) {
return res.status(400).json({
success: false,
message: "User permission already exists"
});
}
const newUserPermission = await UserPermission.create({
user_id,
permission_id
});
res.status(201).json({
success: true,
data: newUserPermission
});
} catch (error) {
console.error("Error creating user permission:", error);
res.status(500).json({
success: false,
message: "An error occurred while creating user permission."
});
}
};
// Bulk create user permissions
exports.bulkCreateUserPermissions = async (req, res) => {
try {
const { user_id, permission_ids } = req.body;
if (!user_id || !permission_ids || !Array.isArray(permission_ids) || permission_ids.length === 0) {
return res.status(400).json({
success: false,
message: "User ID and permission_ids array are required and must not be empty"
});
}
// Verify user exists
const user = await User.findByPk(user_id);
if (!user) {
return res.status(404).json({
success: false,
message: "User not found"
});
}
const results = {
created: [],
failed: []
};
for (const permission_id of permission_ids) {
try {
if (!permission_id) {
results.failed.push({
user_id,
permission_id,
error: "Permission ID is required"
});
continue;
}
// Verify permission exists
const permission = await Permission.findByPk(permission_id);
if (!permission) {
results.failed.push({
user_id,
permission_id,
error: "Permission not found"
});
continue;
}
// Check if assignment already exists
const existingAssignment = await UserPermission.findOne({
where: { user_id, permission_id }
});
if (existingAssignment) {
results.failed.push({
user_id,
permission_id,
error: "User permission already exists"
});
continue;
}
const newUserPermission = await UserPermission.create({
user_id,
permission_id
});
results.created.push(newUserPermission);
} catch (itemError) {
results.failed.push({
user_id,
permission_id,
error: itemError.message
});
}
}
res.status(201).json({
success: results.failed.length === 0,
data: results
});
} catch (error) {
console.error("Error bulk creating user permissions:", error);
res.status(500).json({
success: false,
message: "An error occurred while bulk creating user permissions."
});
}
};
// Update user permission
exports.updateUserPermission = async (req, res) => {
try {
const { upId } = req.params;
const { permission_id } = req.body;
if (!permission_id) {
return res.status(400).json({
success: false,
message: "Permission ID is required"
});
}
const userPermission = await UserPermission.findByPk(upId);
if (!userPermission) {
return res.status(404).json({
success: false,
message: "User permission not found"
});
}
// Verify permission exists
const permission = await Permission.findByPk(permission_id);
if (!permission) {
return res.status(404).json({
success: false,
message: "Permission not found"
});
}
// Check if new permission assignment already exists for this user
const existingAssignment = await UserPermission.findOne({
where: {
user_id: userPermission.user_id,
permission_id
}
});
if (existingAssignment && existingAssignment.up_id !== upId) {
return res.status(400).json({
success: false,
message: "This permission is already assigned to this user"
});
}
await userPermission.update({ permission_id });
res.status(200).json({
success: true,
data: userPermission,
message: "User permission updated successfully"
});
} catch (error) {
console.error("Error updating user permission:", error);
res.status(500).json({
success: false,
message: "An error occurred while updating user permission."
});
}
};
// Delete user permission
exports.deleteUserPermission = async (req, res) => {
try {
const { upId } = req.params;
const userPermission = await UserPermission.findByPk(upId);
if (!userPermission) {
return res.status(404).json({
success: false,
message: "User permission not found"
});
}
await userPermission.destroy();
res.status(200).json({
success: true,
message: "User permission deleted successfully"
});
} catch (error) {
console.error("Error deleting user permission:", error);
res.status(500).json({
success: false,
message: "An error occurred while deleting user permission."
});
}
};