Roles and Permissions – How to add check if project assign to

I’m working on a Roles and Permissions system where users are assigned roles, and each role has multiple permissions. A user can have only one role, but a role can have many permissions, and permissions can belong to multiple roles.

Projects can have one or more Site Admins assigned, creating a many-to-many relationship between projects and users.

Currently, I have a basic implementation: for instance, both Super Admin and Site Admin roles have EDIT_PROJECT permissions.

I’m trying to add a middleware to check authorization dynamically, so that Site Admins can only edit projects they are assigned to. I want to avoid hard-coded conditions.

I’m working on a Roles and Permissions system where users are assigned roles, and each role has multiple permissions. A user can have only one role, but a role can have many permissions, and permissions can belong to multiple roles.

Currently, I have a basic implementation: for instance, both Super Admin and Site Admin roles have EDIT_PROJECT and EDIT_TASK permissions. The key difference is that while Super Admins can update all projects, Site Admins can only update projects assigned to them.

Projects can have one or more Site Admins assigned, creating a many-to-many relationship between projects and users.

I’m trying to add a middleware to check authorization dynamically, so that Site Admins can only edit projects they are assigned to. I want to avoid hard-coded conditions.

/**
 * Middleware to check if the user has the required permission(s).
 * @param permissions - Array of permissions required to access the route.
 */
const authorizeRoles = (permissions: string[]) => {
    return (req: Request, res: Response, next: NextFunction) => {
        try {
            // Check if the user object exists in the request
            if (!req.user || !req.user.role || !req.user.role.permissions) {
                return RequestResponseMappings.sendErrorMessage(res, {}, "Unauthorized access", 401);
            }

            const userPermissions = req.user.role.permissions.map((permission: any) => permission.name); // Extract the permission names

            // Check if the user has at least one of the required permissions
            const hasPermission = permissions.some(permission => userPermissions.includes(permission));

            if (!hasPermission) {
                return RequestResponseMappings.sendErrorMessage(res, {}, "Forbidden: Insufficient permissions", 403);
            }

            next(); // User has the required permission, proceed to the next middleware or route handler
        } catch (error: any) {
            return RequestResponseMappings.sendErrorMessage(res, {}, error.message, 500);
        }
    };
};

Now I want to update middleware to check if the request comes from super admin, allow edit to all projects, but if request comes from site admin, check if site admin is assigned to project, if yes, proceed, otherwise don’t.

How can I implement this middleware to handle authorization checks efficiently?

Will appreciate your suggestions.

For your middleware to handle both Super Admin and Site Admin permissions dynamically, you can do something like:

Updated Middleware:

const authorizeRoles = (permissions: string[]) => {
    return async (req: Request, res: Response, next: NextFunction) => {
        try {
            // Check if the user object exists in the request
            if (!req.user || !req.user.role || !req.user.role.permissions) {
                return RequestResponseMappings.sendErrorMessage(res, {}, "Unauthorized access", 401);
            }

            const userRole = req.user.role.name;
            const userPermissions = req.user.role.permissions.map((permission: any) => permission.name); // Extract the permission names

            if (userRole === 'Super Admin') {
                return next();
            }

            // Check if the user has at least one of the required permissions
            const hasPermission = permissions.some(permission => userPermissions.includes(permission));

            if (!hasPermission) {
                return RequestResponseMappings.sendErrorMessage(res, {}, "Forbidden: Insufficient permissions", 403);
            }

            // If the user is a Site Admin, check if they are assigned to the project
            if (userRole === 'Site Admin') {
                const projectId = req.params.projectId; // Assuming project ID is in route params
                
                const isAssignedToProject = await checkIfSiteAdminAssignedToProject(req.user.id, projectId);

                if (!isAssignedToProject) {
                    return RequestResponseMappings.sendErrorMessage(res, {}, "Forbidden: You are not assigned to this project", 403);
                }
            }

            next(); // User has the required permission and is authorized
        } catch (error: any) {
            return RequestResponseMappings.sendErrorMessage(res, {}, error.message, 500);
        }
    };
};

Explanation:

  1. Super Admin Check: We first check if the user has the Super Admin role. If they do, they are allowed to proceed with any operation, skipping other checks.
  2. Permission Check: Check if the user has the required permissions for the route.
  3. Site Admin Check: If the user is a Site Admin, the code checks if they are assigned to the specific project they are trying to edit. This is done using the checkIfSiteAdminAssignedToProject function (you’ll need to implement this function to query the database and verify the user’s assignment).

EDIT

Define roles and permissions

interface Permission {
     name: string; // e.g., 'EDIT_PROJECT', 'VIEW_TEAM'
     entityType: string; // e.g., 'Project', 'Team'
     entityId: number; // specific project or team ID
   }




interface Role {
     name: string; // 'Super Admin', 'Site Admin'
     permissions: Permission[];
   }



   interface User {
     id: number;
     role: Role;
   }

Service to check for user role and permission

const hasPermissionForEntity = async (
     user: User, 
     requiredPermission: string, 
     entityType: string, 
     entityId: number
   ): Promise<boolean> => {
     if (user.role.name === 'Super Admin') {
       return true;
     } //this check can be removed and Super Admin users can be treated same as all users, and follow below logic
     // Check if the user has the required permission for the specific entity
     return user.role.permissions.some(permission =>
       permission.name === requiredPermission &&
       permission.entityType === entityType &&
       permission.entityId === entityId
     );
   };

Middleware to check the entity type and ID provided in the request:

const authorizeForEntity = (requiredPermission: string, entityType: string) => {
     return async (req: Request, res: Response, next: NextFunction) => {
       const { user } = req;
       const entityId = req.params.entityId; // Assuming entity ID is passed in the route params
   
       if (!user || !entityId) {
         return res.status(401).send('Unauthorized');
       }

       const hasPermission = await hasPermissionForEntity(user, requiredPermission, entityType, Number(entityId));

       if (!hasPermission) {
         return res.status(403).send('Forbidden: Insufficient permissions');
       }

       next(); // Proceed if permission check passes
     };
   };

Hope this helps

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật