ExpressJs

⌘K
  1. Home
  2. Docs
  3. ExpressJs
  4. Role And Permission
  5. Entities Definition
  6. 3.Permissions

3.Permissions

const { EntitySchema } = require('typeorm');

module.exports = new EntitySchema({
    name: 'Permission',
    tableName: 'permissions',
    columns: {
        id: {
            type: 'int',
            primary: true,
            generated: true,
        },
        name: {
            type: 'varchar',
            unique: true,
            nullable: false,
        },
        model: {
            type: 'varchar',
            nullable: false,
        },
        action: {
            type: 'varchar',
            nullable: false,
        },
        createdAt: {
            type: 'timestamp',
            createDate: true,
        },
        updatedAt: {
            type: 'timestamp',
            updateDate: true,
        },
    },
});

Explanation of Columns:

  • id: Auto-incremented primary key.
  • name: Name of the permission (e.g., Manage Users, Edit Posts). It’s set as UNIQUE to ensure no duplicate permission names.
  • model: The model or entity this permission applies to (e.g., User, Post).
  • action: The specific action allowed for this permission (e.g., create, edit, delete).
  • createdAt: Timestamp of when the permission was created.
  • updatedAt: Timestamp of when the permission was last updated.
// services/permission.service.js
const { AppDataSource } = require('../../../index'); // Ensure the path is correct
const Permission = require('../entities/permission.entity');

/**
 * @function formatPermissionResponse
 * @description Formats the permission data to ensure consistent field names across all responses.
 * @param {object} permission - The permission object to format.
 * @returns {object} - The formatted permission object.
 */
const formatPermissionResponse = (permission) => {
    if (!permission) return null;

    return {
        id: permission.id,
        name: permission.name,
        model: permission.model,
        action: permission.action,
        createdAt: permission.createdAt,
        updatedAt: permission.updatedAt,
    };
};

const createPermission = async (data) => {
    const permissionRepository = AppDataSource.getRepository(Permission);
    const permission = permissionRepository.create(data);
    const savedPermission = await permissionRepository.save(permission);
    return formatPermissionResponse(savedPermission);
};

const findPermissionById = async (id) => {
    const permissionRepository = AppDataSource.getRepository(Permission);
    const permission = await permissionRepository.findOneBy({ id });
    return formatPermissionResponse(permission);
};

const updatePermission = async (id, data) => {
    const permissionRepository = AppDataSource.getRepository(Permission);
    const permission = await findPermissionById(id);
    if (!permission) return null;

    Object.assign(permission, data);
    const updatedPermission = await permissionRepository.save(permission);
    return formatPermissionResponse(updatedPermission);
};

const deletePermission = async (id) => {
    const permissionRepository = AppDataSource.getRepository(Permission);
    const result = await permissionRepository.delete(id);
    return result.affected;
};

const getAllPermissions = async () => {
    const permissionRepository = AppDataSource.getRepository(Permission);
    const permissions = await permissionRepository.find();
    return permissions.map(formatPermissionResponse);
};

module.exports = {
    createPermission,
    findPermissionById,
    updatePermission,
    deletePermission,
    getAllPermissions,
};
// controllers/permission.controller.js
const permissionService = require('../services/permission.service');

/**
 * @function createPermission
 * @description Creates a new permission.
 * @param {object} req - Request object.
 * @param {object} res - Response object.
 */
const createPermission = async (req, res) => {
    try {
        const permission = await permissionService.createPermission(req.body);
        res.status(201).json(permission);
    } catch (error) {
        res.status(500).json({ message: 'Failed to create permission', error: error.message });
    }
};

/**
 * @function getPermissionById
 * @description Retrieves a permission by ID.
 * @param {object} req - Request object.
 * @param {object} res - Response object.
 */
const getPermissionById = async (req, res) => {
    try {
        const permission = await permissionService.findPermissionById(req.params.id);
        if (!permission) {
            return res.status(404).json({ message: 'Permission not found' });
        }
        res.status(200).json(permission);
    } catch (error) {
        res.status(500).json({ message: 'Failed to retrieve permission', error: error.message });
    }
};

/**
 * @function updatePermission
 * @description Updates a permission by ID.
 * @param {object} req - Request object.
 * @param {object} res - Response object.
 */
const updatePermission = async (req, res) => {
    try {
        const permission = await permissionService.updatePermission(req.params.id, req.body);
        if (!permission) {
            return res.status(404).json({ message: 'Permission not found' });
        }
        res.status(200).json(permission);
    } catch (error) {
        res.status(500).json({ message: 'Failed to update permission', error: error.message });
    }
};

/**
 * @function deletePermission
 * @description Deletes a permission by ID.
 * @param {object} req - Request object.
 * @param {object} res - Response object.
 */
const deletePermission = async (req, res) => {
    try {
        const result = await permissionService.deletePermission(req.params.id);
        if (result === 0) {
            return res.status(404).json({ message: 'Permission not found' });
        }
        res.status(204).send();
    } catch (error) {
        res.status(500).json({ message: 'Failed to delete permission', error: error.message });
    }
};

/**
 * @function getAllPermissions
 * @description Retrieves all permissions.
 * @param {object} req - Request object.
 * @param {object} res - Response object.
 */
const getAllPermissions = async (req, res) => {
    try {
        const permissions = await permissionService.getAllPermissions();
        if (!permissions) {
            return res.status(404).json({ message: 'No permissions found' });
        }
        res.status(200).json(permissions);
    } catch (error) {
        res.status(500).json({
            message: 'Internal server error',
            error: error.message || 'An unexpected error occurred',
        });
    }
};

module.exports = {
    createPermission,
    getPermissionById,
    updatePermission,
    deletePermission,
    getAllPermissions,
};
// routes/permission.routes.js
const express = require('express');
const router = express.Router();
const permissionController = require('../controllers/permission.controller');

// Define routes with corresponding controller methods
router.get('/permissions', permissionController.getAllPermissions);
router.post('/permissions', permissionController.createPermission); // Create a new permission
router.get('/permissions/:id', permissionController.getPermissionById); // Get permission by ID
router.put('/permissions/:id', permissionController.updatePermission); // Update permission by ID
router.delete('/permissions/:id', permissionController.deletePermission); // Delete permission by ID

module.exports = router;
    const permissionRoutes = require('./modules/Authentication/routes/permission.routes');
    app.use('/api', permissionRoutes);

File: src/controllers/permissionController.js

const AppDataSource = require('../config/database');
const { Permission } = require('../entities/Permission');
const UserGroup = require('../entities/UserGroup'); 
const Permission = require('./Permission');

/**
 * একটি নির্দিষ্ট নামের পারমিশন ডাটাবেজে বিদ্যমান কিনা তা পরীক্ষা করে।
 * @function checkIfPermissionExists
 * @param {string} permissionName - পারমিশনের নাম।
 * @returns {Promise<boolean>} - সত্য বা মিথ্যা।
 */
const checkIfPermissionExists = async (permissionName) => {
    const permissionRepository = AppDataSource.getRepository(Permission);
    const existingPermission = await permissionRepository.findOne({ where: { name: permissionName } });
    return !!existingPermission;
};

/**
 * একটি নির্দিষ্ট নামের জন্য পারমিশন তৈরি করে।
 * @function createPermission
 * @param {string} permissionName - পারমিশনের নাম।
 * @returns {Promise<void>}
 */
const createPermission = async (permissionName) => {
    const permissionRepository = AppDataSource.getRepository(Permission);
    const permission = new Permission();
    permission.name = permissionName;
    await permissionRepository.save(permission);
    console.log(`Permission ${permissionName} created.`);
};

/**
 * ডাটাবেস থেকে সকল এন্টিটি রিট্রিভ করে।
 * @function getAllEntities
 * @returns {Array} - সকল এন্টিটির নামের একটি অ্যারে।
 */
const getAllEntities = () => {
    return AppDataSource.entityMetadatas.map(entity => entity.name);
};

/**
 * নির্দিষ্ট একটি এন্টিটির জন্য স্বয়ংক্রিয়ভাবে ক্রিয়েট, রিড, আপডেট, ডিলিট পারমিশন তৈরি করে।
 * @function createPermissionsForEntity
 * @param {string} entityName - এন্টিটির নাম।
 * @returns {Promise<void>}
 */
const createPermissionsForEntity = async (entityName) => {
    const operations = ['create', 'read', 'update', 'delete', 'view'];

    for (let operation of operations) {
        const permissionName = `${operation}_${entityName}`;

        // পারমিশন বিদ্যমান কিনা তা পরীক্ষা করা হচ্ছে
        const exists = await checkIfPermissionExists(permissionName);
        if (!exists) {
            await createPermission(permissionName);
        } else {
            console.log(`Permission ${permissionName} already exists.`);
        }
    }
};

/**
 * সকল এন্টিটির জন্য স্বয়ংক্রিয়ভাবে ক্রিয়েট, রিড, আপডেট, ডিলিট পারমিশন তৈরি করে।
 * @function createPermissionsForAllEntities
 * @returns {Promise<void>}
 */
const createPermissionsForAllEntities = async () => {
    const entities = getAllEntities();

    for (let entityName of entities) {
        await createPermissionsForEntity(entityName);
    }

    console.log('সকল এন্টিটির জন্য পারমিশনগুলো সফলভাবে তৈরি করা হয়েছে।');
};






module.exports = {
    createPermissionsForEntity,
    createPermissionsForAllEntities,
     
};

How can we help?