64 lines
2.4 KiB
JavaScript
64 lines
2.4 KiB
JavaScript
const UnitOfWork = require('../../database/UnitOfWork');
|
|
const PermissionService = require('../../services/permissions/PermissionService');
|
|
const PermissionRepository = require('../../repositories/permissions/PermissionRepository');
|
|
|
|
class PermissionController {
|
|
static async list(req, res) {
|
|
const unitOfWork = new UnitOfWork();
|
|
await unitOfWork.start();
|
|
try {
|
|
const permissions = await PermissionService.getAllPermissions(unitOfWork);
|
|
await unitOfWork.commit();
|
|
res.json({ success: true, permissions });
|
|
} catch (error) {
|
|
await unitOfWork.rollback(error);
|
|
res.status(500).json({ success: false, message: error.message });
|
|
}
|
|
}
|
|
|
|
static async create(req, res) {
|
|
const { name, description, is_active } = req.body;
|
|
const userId = req.user.userId; // Get user ID from access token
|
|
if (!name) {
|
|
return res.status(400).json({ success: false, message: 'Permission name is required' });
|
|
}
|
|
const unitOfWork = new UnitOfWork();
|
|
await unitOfWork.start();
|
|
try {
|
|
const permission = await PermissionService.createPermission({ name, description, is_active }, userId, unitOfWork);
|
|
await unitOfWork.commit();
|
|
res.status(201).json({ success: true, permission });
|
|
} catch (error) {
|
|
await unitOfWork.rollback(error);
|
|
res.status(400).json({ success: false, message: error.message });
|
|
}
|
|
}
|
|
|
|
static async getUserPermissions(req, res) {
|
|
// Access control: only self or admin/super_admin can view
|
|
const requestedUserId = Number(req.params.id);
|
|
const requesterUserId = req.user.userId;
|
|
const requesterRole = req.user.role;
|
|
|
|
if (requestedUserId !== requesterUserId && requesterRole !== 'admin' && requesterRole !== 'super_admin') {
|
|
return res.status(403).json({ success: false, message: 'Forbidden' });
|
|
}
|
|
|
|
const unitOfWork = new UnitOfWork();
|
|
await unitOfWork.start();
|
|
try {
|
|
// Use PermissionRepository for data access
|
|
const repo = new PermissionRepository(unitOfWork);
|
|
const permissions = await repo.getPermissionsByUserId(requestedUserId);
|
|
await unitOfWork.commit();
|
|
res.json({ success: true, permissions });
|
|
} catch (error) {
|
|
await unitOfWork.rollback(error);
|
|
res.status(500).json({ success: false, message: error.message });
|
|
}
|
|
}
|
|
}
|
|
|
|
module.exports = PermissionController;
|
|
module.exports = PermissionController;
|