Entity
Services
Controller
Routes
Index.js
const { EntitySchema } = require('typeorm');
module.exports = new EntitySchema({
name: 'UserPermission',
tableName: 'user_permissions',
columns: {
userId: {
name: 'user_id',
type: 'int',
primary: true,
},
permissionId: {
name: 'permission_id',
type: 'int',
primary: true,
},
},
relations: {
user: {
type: 'many-to-one',
target: 'User', // Refers to the User entity
joinColumn: { name: 'user_id' },
onDelete: 'CASCADE',
},
permission: {
type: 'many-to-one',
target: 'Permission', // Refers to the Permission entity
joinColumn: { name: 'permission_id' },
onDelete: 'CASCADE',
},
},
});
// services/userPermission.service.js
const { getRepository } = require('typeorm');
const UserPermission = require('../entities/userPermission.entity');
const createUserPermission = async (data) => {
const userPermissionRepository = getRepository(UserPermission);
const newUserPermission = userPermissionRepository.create(data);
return await userPermissionRepository.save(newUserPermission);
};
const getUserPermission = async (userId, permissionId) => {
const userPermissionRepository = getRepository(UserPermission);
return await userPermissionRepository.findOne({ userId, permissionId });
};
const getAllUserPermissions = async () => {
const userPermissionRepository = getRepository(UserPermission);
return await userPermissionRepository.find();
};
const updateUserPermission = async (userId, permissionId, data) => {
const userPermissionRepository = getRepository(UserPermission);
const userPermission = await userPermissionRepository.findOne({ userId, permissionId });
if (userPermission) {
userPermissionRepository.merge(userPermission, data);
return await userPermissionRepository.save(userPermission);
}
return null;
};
const deleteUserPermission = async (userId, permissionId) => {
const userPermissionRepository = getRepository(UserPermission);
const result = await userPermissionRepository.delete({ userId, permissionId });
return result.affected > 0;
};
module.exports = {
createUserPermission,
getUserPermission,
getAllUserPermissions,
updateUserPermission,
deleteUserPermission,
};
// controllers/userPermission.controller.js
const userPermissionService = require('../services/userPermission.service');
const createUserPermission = async (req, res) => {
try {
const data = req.body;
const userPermission = await userPermissionService.createUserPermission(data);
res.status(201).json({ userPermission });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
const getUserPermission = async (req, res) => {
try {
const { userId, permissionId } = req.params;
const userPermission = await userPermissionService.getUserPermission(userId, permissionId);
if (userPermission) {
res.status(200).json({ userPermission });
} else {
res.status(404).json({ message: 'UserPermission not found' });
}
} catch (error) {
res.status(500).json({ message: error.message });
}
};
const getAllUserPermissions = async (req, res) => {
try {
const userPermissions = await userPermissionService.getAllUserPermissions();
res.status(200).json({ userPermissions });
} catch (error) {
res.status(500).json({ message: error.message });
}
};
const updateUserPermission = async (req, res) => {
try {
const { userId, permissionId } = req.params;
const data = req.body;
const updatedUserPermission = await userPermissionService.updateUserPermission(userId, permissionId, data);
if (updatedUserPermission) {
res.status(200).json({ updatedUserPermission });
} else {
res.status(404).json({ message: 'UserPermission not found' });
}
} catch (error) {
res.status(500).json({ message: error.message });
}
};
const deleteUserPermission = async (req, res) => {
try {
const { userId, permissionId } = req.params;
const isDeleted = await userPermissionService.deleteUserPermission(userId, permissionId);
if (isDeleted) {
res.status(200).json({ message: 'UserPermission deleted successfully' });
} else {
res.status(404).json({ message: 'UserPermission not found' });
}
} catch (error) {
res.status(500).json({ message: error.message });
}
};
module.exports = {
createUserPermission,
getUserPermission,
getAllUserPermissions,
updateUserPermission,
deleteUserPermission,
};
// routes/userPermission.routes.js
const express = require('express');
const userPermissionController = require('../controllers/userPermission.controller');
const router = express.Router();
// Create a new UserPermission
router.post('/user-permissions', userPermissionController.createUserPermission);
// Get a single UserPermission by userId and permissionId
router.get('/user-permissions/:userId/:permissionId', userPermissionController.getUserPermission);
// Get all UserPermissions
router.get('/user-permissions', userPermissionController.getAllUserPermissions);
// Update a UserPermission by userId and permissionId
router.put('/user-permissions/:userId/:permissionId', userPermissionController.updateUserPermission);
// Delete a UserPermission by userId and permissionId
router.delete('/user-permissions/:userId/:permissionId', userPermissionController.deleteUserPermission);
module.exports = router;
const userPermissionRoutes = require('./modules/Authentication/routes/userPermission.routes');
app.use('/api', userPermissionRoutes);
2.3 Assigning Permissions Directly to Users
Relationship: A user can have multiple permissions directly assigned, and a permission can be assigned to multiple users.
Implementation: Create a join table user_permissions
.
2.3.1 Create user_permissions
Join Table
const { EntitySchema } = require('typeorm');
module.exports = new EntitySchema({
name: 'UserPermission',
tableName: 'user_permissions',
columns: {
userId: {
name: 'user_id',
type: 'int',
primary: true,
},
permissionId: {
name: 'permission_id',
type: 'int',
primary: true,
},
},
relations: {
user: {
// Many-to-Many relationship (part of the join table definition)
// This field references the 'users' table via the foreign key 'user_id'.
type: 'many-to-one',
target: 'User', // Refers to the User entity
joinColumn: { name: 'user_id' }, // The foreign key in the 'user_permissions' table
onDelete: 'CASCADE', // If a user is deleted, remove the related entries in the join table
},
permission: {
// Many-to-Many relationship (part of the join table definition)
// This field references the 'permissions' table via the foreign key 'permission_id'.
type: 'many-to-one',
target: 'Permission', // Refers to the Permission entity
joinColumn: { name: 'permission_id' }, // The foreign key in the 'user_permissions' table
onDelete: 'CASCADE', // If a permission is deleted, remove the related entries in the join table
},
},
});
Explanation:
user_id
: References a user in theusers
table.permission_id
: References a permission in thepermissions
table.- Composite Primary Key: Ensures each user and permission pair is unique.
ON DELETE CASCADE
: Deletes related entries if a user or permission is removed.
Usage Example:
-- Assign 'DELETE_POST' permission directly to user with id 5
INSERT INTO user_permissions (user_id, permission_id)
VALUES (5, 6);
const AppDataSource = require('../config/database');
const { UserGroup, Permission, UserGroupPermission } = require('../entities');
/**
* ইউজারকে অনুমতি প্রদান করার জন্য মেথড
* @function assignPermissionsToUser
* @description এই মেথডটি নির্দিষ্ট ইউজারকে অনুমতি প্রদান করে।
* @param {object} req - রিকোয়েস্ট অবজেক্ট যা ইউজার আইডি এবং অনুমতি আইডি ধারণ করে।
* @param {object} res - রেসপন্স অবজেক্ট যা ক্লায়েন্টকে রেসপন্স পাঠাতে ব্যবহৃত হয়।
* @returns {Promise<void>} - ফাংশনটি একটি প্রমিস রিটার্ন করে যা রিকোয়েস্ট সম্পন্ন হওয়ার পর রেসপন্স প্রদান করে।
*/
const assignPermissionsToUser = async (req, res) => {
const { userId, permissionIds } = req.body;
try {
const userRepository = AppDataSource.getRepository(User);
const permissionRepository = AppDataSource.getRepository(Permission);
const userPermissionRepository = AppDataSource.getRepository(UserPermission);
// ইউজার চেক করা হচ্ছে
const user = await userRepository.findOne({ where: { id: userId } });
if (!user) {
return res.status(404).json({ message: 'ইউজার পাওয়া যায়নি' });
}
// অনুমতিগুলি চেক করা হচ্ছে
const permissions = await permissionRepository.findByIds(permissionIds);
if (permissions.length !== permissionIds.length) {
return res.status(404).json({ message: 'এক বা একাধিক অনুমতি পাওয়া যায়নি' });
}
// ইউজারকে অনুমতিগুলি অ্যাসাইন করা হচ্ছে
const userPermissions = permissions.map(permission => {
return userPermissionRepository.create({
user: user,
permission: permission
});
});
await userPermissionRepository.save(userPermissions);
return res.status(200).json({ message: 'অনুমতি সফলভাবে ইউজারকে প্রদান করা হয়েছে' });
} catch (err) {
return res.status(500).json({ message: 'অনুমতি প্রদান করতে ত্রুটি', error: err.message });
}
};
/**
* ইউজারগ্রুপ থেকে অনুমতি অপসারণ করার জন্য মেথড
* @function removePermissionsFromUserGroup
* @description এই মেথডটি নির্দিষ্ট ইউজারগ্রুপ থেকে অনুমতি অপসারণ করে।
* @param {object} req - রিকোয়েস্ট অবজেক্ট যা ইউজারগ্রুপ আইডি এবং অনুমতি আইডি ধারণ করে।
* @param {object} res - রেসপন্স অবজেক্ট যা ক্লায়েন্টকে রেসপন্স পাঠাতে ব্যবহৃত হয়।
* @returns {Promise<void>} - ফাংশনটি একটি প্রমিস রিটার্ন করে যা রিকোয়েস্ট সম্পন্ন হওয়ার পর রেসপন্স প্রদান করে।
*/
const removePermissionsFromUserGroup = async (req, res) => {
const { userGroupId, permissionIds } = req.body;
try {
const userGroupPermissionRepository = AppDataSource.getRepository(UserGroupPermission);
// চেক করা হচ্ছে ইউজারগ্রুপে নির্দিষ্ট অনুমতিগুলি আছে কিনা
const existingUserGroupPermissions = await userGroupPermissionRepository.find({
where: { userGroup: { id: userGroupId }, permission: { id: permissionIds } },
});
if (existingUserGroupPermissions.length === 0) {
return res.status(404).json({ message: 'প্রদত্ত অনুমতিগুলি ইউজারগ্রুপে পাওয়া যায়নি' });
}
// অনুমতিগুলি ইউজারগ্রুপ থেকে অপসারণ করা হচ্ছে
await userGroupPermissionRepository.remove(existingUserGroupPermissions);
return res.status(200).json({ message: 'অনুমতি সফলভাবে ইউজারগ্রুপ থেকে অপসারণ করা হয়েছে' });
} catch (err) {
return res.status(500).json({ message: 'অনুমতি অপসারণ করতে ত্রুটি', error: err.message });
}
};
/**
* নির্দিষ্ট ইউজারগ্রুপের জন্য অনুমতি তালিকা দেখানোর জন্য মেথড
* @function getPermissionsByUserGroup
* @description এই মেথডটি নির্দিষ্ট ইউজারগ্রুপের অনুমতিগুলির তালিকা দেখায়।
* @param {object} req - রিকোয়েস্ট অবজেক্ট যা ইউজারগ্রুপ আইডি ধারণ করে।
* @param {object} res - রেসপন্স অবজেক্ট যা ক্লায়েন্টকে রেসপন্স পাঠাতে ব্যবহৃত হয়।
* @returns {Promise<void>} - ফাংশনটি একটি প্রমিস রিটার্ন করে যা রিকোয়েস্ট সম্পন্ন হওয়ার পর রেসপন্স প্রদান করে।
*/
const getPermissionsByUserGroup = async (req, res) => {
const { userGroupId } = req.params;
try {
const userGroupPermissionRepository = AppDataSource.getRepository(UserGroupPermission);
// নির্দিষ্ট ইউজারগ্রুপের অনুমতিগুলি পাওয়া যাচ্ছে
const permissions = await userGroupPermissionRepository.find({
where: { userGroup: { id: userGroupId } },
relations: ['permission'],
});
return res.status(200).json({ permissions: permissions.map(up => up.permission) });
} catch (err) {
return res.status(500).json({ message: 'অনুমতি তালিকা দেখতে ত্রুটি', error: err.message });
}
};
/**
* নির্দিষ্ট ইউজারগ্রুপে অন্তর্ভুক্ত নয় এমন অনুমতিগুলির তালিকা দেখানোর জন্য মেথড
* @function getPermissionsNotInUserGroup
* @description এই মেথডটি নির্দিষ্ট ইউজারগ্রুপে অন্তর্ভুক্ত নয় এমন অনুমতিগুলির তালিকা দেখায়।
* @param {object} req - রিকোয়েস্ট অবজেক্ট যা ইউজারগ্রুপ আইডি ধারণ করে।
* @param {object} res - রেসপন্স অবজেক্ট যা ক্লায়েন্টকে রেসপন্স পাঠাতে ব্যবহৃত হয়।
* @returns {Promise<void>} - ফাংশনটি একটি প্রমিস রিটার্ন করে যা রিকোয়েস্ট সম্পন্ন হওয়ার পর রেসপন্স প্রদান করে।
*/
const getPermissionsNotInUserGroup = async (req, res) => {
const { userGroupId } = req.params;
try {
const permissionRepository = AppDataSource.getRepository(Permission);
const userGroupPermissionRepository = AppDataSource.getRepository(UserGroupPermission);
// নির্দিষ্ট ইউজারগ্রুপের অন্তর্ভুক্ত অনুমতিগুলি পাওয়া যাচ্ছে
const existingPermissions = await userGroupPermissionRepository.find({
where: { userGroup: { id: userGroupId } },
relations: ['permission'],
});
const existingPermissionIds = existingPermissions.map(up => up.permission.id);
// সমস্ত অনুমতি সংগ্রহ করা হচ্ছে
const allPermissions = await permissionRepository.find();
// ইউজারগ্রুপে অন্তর্ভুক্ত নয় এমন অনুমতিগুলি ফিল্টার করা হচ্ছে
const permissionsNotInUserGroup = allPermissions.filter(permission => !existingPermissionIds.includes(permission.id));
return res.status(200).json({ permissions: permissionsNotInUserGroup });
} catch (err) {
return res.status(500).json({ message: 'অনুমতি তালিকা দেখতে ত্রুটি', error: err.message });
}
};