ExpressJs

⌘K
  1. Home
  2. Docs
  3. ExpressJs
  4. Role And Permission
  5. Permission checking

Permission checking

const AppDataSource = require('../config/database');
const { Permission, UserRolePermission, UserGroupPermission, UserPermission, User } = require('../models');

/**
 * ইউজার রোল অনুমতি চেক করার জন্য মেথড
 * @function checkUserRolePermission
 * @description এই মেথডটি নির্দিষ্ট ইউজার রোলের অনুমতি চেক করে।
 * @param {number} userId - ইউজার আইডি।
 * @param {number} permissionId - অনুমতির আইডি।
 * @returns {Promise<boolean>} - যদি অনুমতি পাওয়া যায় তাহলে সত্য এবং না হলে মিথ্যা।
 */
const checkUserRolePermission = async (userId, permissionId) => {
    const userRolePermissionRepository = AppDataSource.getRepository(UserRolePermission);
    const userRepository = AppDataSource.getRepository(User);

    // ইউজারের রোলগুলো পাওয়া
    const user = await userRepository.findOne({
        where: { id: userId },
        relations: ['roles'] // Assuming roles are associated with the user
    });

    if (!user) return false;

    const userRolePermissions = await userRolePermissionRepository.find({
        where: { userRoleId: In(user.roles.map(role => role.id)), permissionId }
    });

    return userRolePermissions.length > 0;
};

/**
 * ইউজার গ্রুপ অনুমতি চেক করার জন্য মেথড
 * @function checkUserGroupPermission
 * @description এই মেথডটি নির্দিষ্ট ইউজার গ্রুপের অনুমতি চেক করে।
 * @param {number} userId - ইউজার আইডি।
 * @param {number} permissionId - অনুমতির আইডি।
 * @returns {Promise<boolean>} - যদি অনুমতি পাওয়া যায় তাহলে সত্য এবং না হলে মিথ্যা।
 */
const checkUserGroupPermission = async (userId, permissionId) => {
    const userGroupPermissionRepository = AppDataSource.getRepository(UserGroupPermission);
    const userRepository = AppDataSource.getRepository(User);

    // ইউজারের গ্রুপগুলো পাওয়া
    const user = await userRepository.findOne({
        where: { id: userId },
        relations: ['groups'] // Assuming groups are associated with the user
    });

    if (!user) return false;

    const userGroupPermissions = await userGroupPermissionRepository.find({
        where: { userGroupId: In(user.groups.map(group => group.id)), permissionId }
    });

    return userGroupPermissions.length > 0;
};

/**
 * ইউজার অনুমতি চেক করার জন্য মেথড
 * @function checkUserPermission
 * @description এই মেথডটি ইউজারের সরাসরি অনুমতি চেক করে।
 * @param {number} userId - ইউজার আইডি।
 * @param {number} permissionId - অনুমতির আইডি।
 * @returns {Promise<boolean>} - যদি অনুমতি পাওয়া যায় তাহলে সত্য এবং না হলে মিথ্যা।
 */
const checkUserPermission = async (userId, permissionId) => {
    const userPermissionRepository = AppDataSource.getRepository(UserPermission);

    const userPermissions = await userPermissionRepository.find({
        where: { userId, permissionId }
    });

    return userPermissions.length > 0;
};

/**
 * ইউজারের অনুমতি চেক করার জন্য মেথড
 * @function checkPermission
 * @description এই মেথডটি নির্দিষ্ট মডেল এবং অ্যাকশনের জন্য ইউজারের অনুমতি চেক করে।
 * @param {string} model - মডেল নাম যেটির অনুমতি চেক করা হবে।
 * @param {string} action - অ্যাকশন নাম যেটির অনুমতি চেক করা হবে।
 * @returns {function} - একটি মেথড যা রিকোয়েস্ট, রেসপন্স এবং নেক্সট মেথড নেয়।
 */
const checkPermission = (model, action) => {
    return async (req, res, next) => {
        const userId = req.user.id; // Assuming the user ID is stored in req.user

        try {
            const permissionRepository = AppDataSource.getRepository(Permission);

            // নির্দিষ্ট মডেল এবং অ্যাকশনের জন্য অনুমতি খুঁজে পাওয়া
            const permission = await permissionRepository.findOne({ where: { model, action } });
            if (!permission) {
                return res.status(403).json({ message: 'অনুমতি পাওয়া যায়নি' });
            }

            const permissionId = permission.id;

            // ইউজারের সরাসরি অনুমতি চেক করা হচ্ছে
            if (await checkUserPermission(userId, permissionId)) {
                return next(); // Permission exists for the user directly
            }

            // ইউজার গ্রুপের অনুমতি চেক করা হচ্ছে
            if (await checkUserGroupPermission(userId, permissionId)) {
                return next(); // Permission exists in user groups
            }

            // ইউজার রোলের অনুমতি চেক করা হচ্ছে
            if (await checkUserRolePermission(userId, permissionId)) {
                return next(); // Permission exists in user roles
            }

            // যদি কোন অনুমতি না পাওয়া যায়, তাহলে 403 স্টেটাস কোড পাঠানো হচ্ছে
            return res.status(403).json({ message: 'অনুমতি অগ্রহণযোগ্য' });

        } catch (err) {
            return res.status(500).json({ message: 'অনুমতি চেক করতে ত্রুটি', error: err.message });
        }
    };
};

module.exports = checkPermission;

To use the checkPermission middleware in your routes, you’ll need to follow these steps:

1. Import the Middleware

First, ensure you import the checkPermission middleware into the file where you define your routes

const express = require('express');
const checkPermission = require('./path/to/checkPermission'); // Adjust the path accordingly

2. Define Your Routes

Use the checkPermission middleware in your route definitions. You need to pass the model and action as arguments to checkPermission.

const router = express.Router();

// Example route where 'Product' is the model and 'can_add' is the action
router.post('/products', checkPermission('Product', 'can_add'), (req, res) => {
    // Handle the request if permission is granted
    res.status(200).json({ message: 'Product added successfully' });
});

// Example route where 'Order' is the model and 'can_view' is the action
router.get('/orders/:id', checkPermission('Order', 'can_view'), (req, res) => {
    // Handle the request if permission is granted
    res.status(200).json({ message: 'Order details fetched successfully' });
});

module.exports = router;

3. Setup Middleware in Express App

Make sure you use the router in your main Express app file, typically app.js or server.js.

const express = require('express');
const app = express();
const userRoutes = require('./path/to/userRoutes'); // Adjust the path accordingly

// Middleware to parse JSON bodies
app.use(express.json());

// Use the routes defined
app.use('/api', userRoutes);

// Start the server
app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

How can we help?