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:
- 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. - Permission Check: Check if the user has the required permissions for the route.
- 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 thecheckIfSiteAdminAssignedToProject
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