npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

rbac-mongo

v1.0.0

Published

Role-Based Access Control (RBAC) package with MongoDB integration

Readme

RBAC MongoDB

A Role-Based Access Control (RBAC) library with MongoDB integration for Node.js applications. Includes built-in support for Express.js and Next.js middleware.

✨ Features

  • 🔐 Full RBAC System – Users, Roles, and Permissions management
  • 🗄️ MongoDB Integration – Powered by Mongoose
  • 🔑 Access Key Authentication – Header-based API authentication
  • 🛡️ Express Middleware – Ready-to-use authorization middleware
  • 📊 Permission Validation – Flexible strategies (ALL / ANY)
  • 🚀 Simple Setup – Quick integration with minimal boilerplate

📦 Installation

npm install rbac-mongodb

⚡ Quick Start

1. Connect Database

const { connectDB } = require('rbac-mongodb');

await connectDB('mongodb://localhost:27017/your-database');

2. Create Roles

const { createRole } = require('rbac-mongodb');

const adminRole = await createRole('admin', [
  'user.create',
  'user.read',
  'user.update',
  'user.delete',
  'role.manage'
]);

const userRole = await createRole('user', [
  'user.read',
  'profile.update'
]);

3. Assign Roles

const { assignRole } = require('rbac-mongodb');

await assignRole(userId, adminRole._id);

4. Generate Access Keys

const { generateAccessKey } = require('rbac-mongodb');

const keys = await generateAccessKey(userId);
console.log(keys.accessKey, keys.secretKey);

5. Use Middleware (Express)

const express = require('express');
const { authorize } = require('rbac-mongodb');

const app = express();

// Single permission
app.get('/admin/users',
  authorize('user.read'),
  (req, res) => res.json({ users: [], currentUser: req.user })
);

// Multiple permissions (ALL required)
app.post('/admin/users',
  authorize(['user.create', 'user.manage']),
  (req, res) => res.json({ message: 'User created' })
);

// Multiple permissions (ANY required)
app.get('/dashboard',
  authorize(['user.read', 'admin.read'], { strategy: 'ANY' }),
  (req, res) => res.json({ message: 'Dashboard data' })
);

📚 API Reference

Database

  • connectDB(uri, options) → Connect to MongoDB
  • isDBConnected() → Check connection status

Role Management

  • createRole(name, permissions) → Create new role
  • assignRole(userId, roleId) → Assign role to user
  • findRoleByName(roleName) → Fetch role by name
  • getAllRoles() → List all roles

Permissions

  • checkPermission(userId, permission) → Check user permission
  • getUserPermissions(userId) → List all permissions for user
  • getUserRoleInfo(userId) → Get user role + permissions info

Access Keys

  • generateAccessKey(userId, options) → Generate access/secret keys
  • authenticateWithAccessKey(accessKey, secretKey) → Authenticate user
  • getUserAccessKeys(userId, activeOnly) → Get active/all keys
  • deactivateAccessKey(accessKey, userId) → Deactivate access key

Middleware

  • authorize(permission, options) → Permission-based middleware
  • authorizeRole(role, options) → Role-based middleware
  • optionalAuthorize(permission) → Optional (silent) middleware

🗄️ Database Models

User

{
  _id: ObjectId,
  email: String (unique, required),
  passwordHash: String (required),
  roleId: ObjectId (ref: 'Role', required),
  createdAt: Date,
  updatedAt: Date
}

Role

{
  _id: ObjectId,
  name: String (unique, required),
  permissions: [String] (required),
  createdAt: Date,
  updatedAt: Date
}

AccessKey

{
  _id: ObjectId,
  userId: ObjectId (ref: 'User', required),
  accessKey: String (unique, required),
  secretKey: String (required),
  createdAt: Date,
  isActive: Boolean (default: true),
  updatedAt: Date
}

🔑 Authentication Headers

// fetch example
fetch('/api/protected', {
  headers: {
    'x-access-key': 'AK_your_key',
    'x-secret-key': 'SK_your_key'
  }
});
// axios example
axios.get('/api/protected', {
  headers: {
    'x-access-key': accessKey,
    'x-secret-key': secretKey
  }
});

❌ Error Responses

401 Unauthorized

{ "error": "Missing access key or secret key", "code": "MISSING_CREDENTIALS" }
{ "error": "Invalid access key or secret key", "code": "INVALID_CREDENTIALS" }

403 Forbidden

{
  "error": "Required permission: user.delete",
  "code": "INSUFFICIENT_PERMISSIONS",
  "userPermissions": ["user.read", "user.update"]
}

🚀 Complete Example

const express = require('express');
const bcrypt = require('bcryptjs');
const {
  connectDB, createRole, findRoleByName,
  assignRole, generateAccessKey, authorize, User
} = require('rbac-mongodb');

const app = express();
app.use(express.json());

async function initializeApp() {
  await connectDB('mongodb://localhost:27017/rbac-demo');
  await createRole('admin', ['user.create','user.read','user.update','user.delete']);
  await createRole('user', ['user.read']);
  console.log('RBAC initialized');
}

// Registration route
app.post('/register', async (req, res) => {
  const { email, password } = req.body;
  const passwordHash = await bcrypt.hash(password, 10);
  const userRole = await findRoleByName('user');
  const user = new User({ email, passwordHash, roleId: userRole._id });
  const savedUser = await user.save();
  const keys = await generateAccessKey(savedUser._id);
  res.json({ message: 'Registered successfully', ...keys });
});

// Protected route
app.get('/api/users', authorize('user.read'), async (req, res) => {
  const users = await User.find().populate('roleId');
  res.json({ users, currentUser: req.user });
});

initializeApp().then(() => app.listen(3000, () => console.log('Server running on 3000')));

📄 License

MIT


💬 Support

For issues or feature requests, please open an issue on GitHub.