rbac-express-auth 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +81 -0
  2. package/package.json +1 -1
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ ## rbac-express
2
+
3
+ Simple and lightweight Role-Based Access Control (RBAC) middleware for Express.js applications.
4
+
5
+ ## Why rbac-express-auth?
6
+
7
+ Most Express applications require role-based authorization, but implementing it repeatedly across projects leads to duplicated and error-prone code.
8
+ `rbac-express-auth` solves this by providing a clean, reusable authorization middleware that works seamlessly with JWT-based authentication systems.
9
+
10
+ ## Installation
11
+
12
+ ```bash
13
+
14
+ npm install rbac-express-auth
15
+
16
+ ```
17
+
18
+ ## Basic Usage
19
+
20
+ ```js
21
+
22
+ import express from "express";
23
+ import { authorize } from "rbac-express-auth";
24
+
25
+ const app = express();
26
+
27
+ // Example authenticated user
28
+ app.use((req, res, next) => {
29
+ req.user = { role: "ADMIN" };
30
+ next();
31
+ });
32
+
33
+ app.get(
34
+ "/admin",
35
+ authorize(["ADMIN"]),
36
+ (req, res) => {
37
+ res.send("Admin access granted");
38
+ }
39
+ );
40
+
41
+ ```
42
+
43
+ ## How it Works
44
+
45
+ 1. The middleware expects `req.user` to be populated (usually by an authentication middleware).
46
+ 2. It checks whether the user's role is included in the allowed roles.
47
+ 3. If authorized, the request proceeds to the next handler.
48
+ 4. If unauthorized, a standardized error response is returned.
49
+
50
+
51
+ ## Error Handling
52
+ The middleware returns structured HTTP errors:
53
+
54
+ - `401 Unauthorized` – if `req.user` is missing
55
+ - `403 Forbidden` – if the user's role is not permitted
56
+
57
+ ## Using with JWT Authentication
58
+
59
+ Make sure your authentication middleware sets `req.user`:
60
+
61
+ ```js
62
+ app.use((req, res, next) => {
63
+ // decoded JWT payload
64
+ req.user = { id: "123", role: "USER" };
65
+ next();
66
+ });
67
+
68
+ ```
69
+
70
+ Then protect your routes
71
+ ```js
72
+ app.get("/vendor", authorize(["VENDOR"]), handler);
73
+
74
+ ```
75
+
76
+
77
+ ### Best Practices
78
+
79
+ - Always run authentication middleware before `authorize()`
80
+ - Use constants or enums for role names
81
+ - Avoid hardcoding roles inside controllers
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rbac-express-auth",
3
- "version": "1.0.1",
3
+ "version": "1.0.3",
4
4
  "description": "Lightweight RBAC middleware for Express.js",
5
5
  "main": "src/index.js",
6
6
  "keywords": [