Express.js
While role-baker doesn’t provide specific utilities for frameworks like Express.js, it delivers the most important functionality through the hasPermission
function. This function checks whether a user has the necessary permissions for a particular resource and action, and it can be easily integrated into Express.js to provide permission-based access control for routes and middleware.
In Express.js, we can use this function to create middleware that checks whether the user has the necessary permissions before allowing access to certain routes.
Permission Middleware for Route Protection
In Express, we can create a middleware that checks the user's permissions for a given resource and action before allowing them to access specific routes.
import { Request, Response, NextFunction } from 'express';
import { hasPermission, MyResourceConfig } from '../access-control'; // Adjust path as needed
interface PermissionMiddlewareInput<R extends keyof MyResourceConfig["resources"]> {
resource: R;
action: MyResourceConfig["resources"][R]["action"];
data?: MyResourceConfig["resources"][R]["dataType"];
}
export function checkPermissionMiddleware<R extends keyof MyResourceConfig["resources"]>(
resource: R,
action: MyResourceConfig["resources"][R]["action"],
data?: MyResourceConfig["resources"][R]["dataType"]
) {
return (req: Request, res: Response, next: NextFunction) => {
const user = req.user; // Assume user is attached to the request, e.g., via authentication middleware
if (!user || !hasPermission(user, resource, action, data)) {
return res.status(403).json({ error: 'Forbidden' }); // Return 403 if permission is denied
}
next(); // Allow access if permission is granted
};
}
Example Usage in Routes:
import express from 'express';
import { checkPermissionMiddleware } from './middleware/permission-middleware'; // Adjust path
const app = express();
// Example route with permission check
app.get(
'/todos',
checkPermissionMiddleware('todos', 'read'),
(req, res) => {
// Only accessible if the user has 'read' permission for 'todos'
res.json({ todos: ['Learn Express.js', 'Integrate role-baker'] });
}
);
// Example route with permission check for creating a new todo
app.post(
'/todos',
checkPermissionMiddleware('todos', 'create'),
(req, res) => {
// Only accessible if the user has 'create' permission for 'todos'
res.status(201).json({ message: 'Todo created' });
}
);
// 403 handler
app.use((req, res) => {
res.status(403).json({ error: 'Forbidden' });
});
app.listen(3000, () => {
console.log('Server running on http://localhost:3000');
});
Explanation:
checkPermissionMiddleware
: This middleware intercepts the request and checks whether the user has the necessary permission for a specific resource and action (likeread
orcreate
for thetodos
resource). If the permission is granted, the request proceeds to the next middleware or route handler; otherwise, a 403 Forbidden response is sent.hasPermission
Check: This middleware relies on thehasPermission
function to verify whether the current user has access to the resource and action defined in the route.- Express Route Usage: The middleware is applied directly to routes, ensuring that the appropriate permission is checked before proceeding with the route handler logic.