Role-Based Access Control (RBAC) is a common approach to manage access to resources in a system based on roles assigned to users. In the context of MongoDB and Node.js, you can implement RBAC by leveraging MongoDB's document structure and features.
Here is a simplified example of implementing RBAC in Node.js with MongoDB:
javascript// models/user.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
username: { type: String, unique: true },
password: String,
roles: [{ type: String, enum: ['admin', 'editor', 'viewer'] }],
});
const User = mongoose.model('User', userSchema);
module.exports = User;
javascript// middleware/authorize.js
const authorize = (requiredRole) => {
return (req, res, next) => {
const user = req.user; // Assuming you store the user information in the request object
if (!user.roles.includes(requiredRole)) {
return res.status(403).json({ message: 'Permission denied' });
}
next();
};
};
module.exports = authorize;
javascriptconst express = require('express');
const User = require('./models/user');
const authorize = require('./middleware/authorize');
const app = express();
// Example route accessible only to admins
app.get('/admin', authorize('admin'), (req, res) => {
res.json({ message: 'Admin-only access granted' });
});
// Example route accessible to both editors and admins
app.get('/editor', authorize(['admin', 'editor']), (req, res) => {
res.json({ message: 'Editor access granted' });
});
// Example route accessible to all users
app.get('/public', (req, res) => {
res.json({ message: 'Public access granted' });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
This is a basic example, and in a real-world scenario, you might want to consider additional security measures, like encrypting passwords, using HTTPS, and handling user sessions securely. Additionally, you may need to implement a more complex RBAC system with role hierarchies, resource-specific permissions, etc., depending on your application's requirements.