nodejs-role-permissions
Beta and Testing Versions
nodejs-role-permissions, is a Node.js library created to simplify role-based access control (RBAC) in Express applications. It offers a flexible middleware system for managing user roles, and securing routes based on assigned roles.
Creating New Collections
The package creates five collections in your MongoDB database: roles, userRoles, permissions, role-permission and user-permission These collections are used to store role information, user-role mappings, and permissions.
Roles Collection
The roles collection stores the available roles in your application. You can add roles manually using a MongoDB client or your application logic.
User-Roles Mapping Collection
The userRoles collection stores the mapping between users and their assigned roles. When a new user is created or when roles are updated for a user, entries are added or modified in this collection.
Permission Collection
The Permission collection is a crucial component of the role-based access control (RBAC) system. It serves as a repository for defining and managing various permissions that can be assigned to roles or directly to users.
Role-Permission Mapping Collection
The RolePermission collection is responsible for managing the relationship between roles and the permissions associated with each role. In the context of role-based access control (RBAC), this collection facilitates the assignment and removal of permissions for specific roles.
User-Permission Mapping Collection
The UserPermission collection serves as a mapping between users and the permissions assigned to them. In the context of role-based access control, this collection helps manage the direct assignment of specific permissions to individual users.
Customizing Collection Names
Edit the Configuration File
Open roleConfig.js in your preferred text editor and modify the settings according to your requirements.
module.exports = {
userCollection: 'User', //Make sure this is user model for authentication
};
How to assign a role to user
const userId = '4d539894a4761d3c05e3'; // Replace with the actual user ID
const roleName = 'Admin'; //Assuming you have this role
assignRole(userId, roleName);
If user already has one role it will be removed and add new role
A Basic example how to add role just after creating user
const { assignRole} = require("node-role-permissions");
const hash = await bcrypt.hash(password, 10)
const newUser = new User({
name: name,
email: email,
phone: phone,
address:address,
password:hash,
verify:0
});
newUser.save();
assignRole(newUser.id,'Admin');
How to use Role as a middleware
Important!
const userId = req.userId; // Make sure to pass your userId in this format from your authMiddleware while using role middleware;
// app.js or your main server file
const express = require('express');
const app = express();
const { checkUserRole } = require('node-role-permissions');
app.get('/admin/dashboard', authenticateMiddleware checkUserRole('admin'), (req, res) => {
// This route requires the 'admin' role
res.send('Welcome to the admin dashboard!');
});
// Another route without middleware
app.get('/public', (req, res) => {
res.send('This is a public route.');
});
Note: Ensure that the user ID is sent to the middleware through the authentication process.
How to get user Role
const userId = 'yourUserIdObjID'; // Replace with the actual user ID
(async () => {
const userRole = await getUserRole(userId);
console.log(userRole);
})();
How to assign/give permission to a role
Note: All users with this role will have access to the given permission
const {assignPermissionToRole } = require("node-role-permissions");
assignPermissionToRole('Admin', 'Edit'); //Assuming 'Admin' role and 'Edit' permissions already exist
How to assign/give permission to a user
const {assignPermissionToUser } = require("node-role-permissions");
const userId = '4d539894a4761d3c05e3'; // Replace with the actual user ID
assignPermissionToUser(userId, 'Edit'); //Assuming 'Edit' Permission already exist
How to use Permission as a middleware
Important!
const userId = req.userId; // Make sure to pass your userId in this format from your authMiddleware while using permission middleware;
// app.js or your main server file
const express = require('express');
const app = express();
const { checkPermission } = require('node-role-permissions');
app.get('/admin/dashboard', authenticateMiddleware, checkPermission('Edit'), (req, res) => {
// This route requires the 'edit' Permission
res.send('You can edit this route content.');
});
app.get('/public', (req, res) => {
res.send('This is a public route.');
});
Note: Ensure that the user ID is sent to the middleware through the authentication process.
Upcoming Features
In the next update, we're excited to introduce a comprehensive permission management feature to complement our existing roles functionality. This enhancement will empower you with more fine-grained control over user access, allowing you to tailor permissions to meet the specific needs of your application. Get ready for a more versatile and powerful user access management system!