rbac-express-auth 1.0.1

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.
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "rbac-express-auth",
3
+ "version": "1.0.1",
4
+ "description": "Lightweight RBAC middleware for Express.js",
5
+ "main": "src/index.js",
6
+ "keywords": [
7
+ "rbac",
8
+ "express",
9
+ "authorization",
10
+ "role-based-access-control",
11
+ "auth"
12
+ ],
13
+ "peerDependencies": {
14
+ "express": ">=4"
15
+ },
16
+ "author": "Akshay Chaudhary",
17
+ "license": "ISC",
18
+ "type": "module"
19
+ }
@@ -0,0 +1,28 @@
1
+ import { rbacErrors } from "./errors.js"
2
+
3
+
4
+ export const authorize = (allowedRoles = []) => {
5
+
6
+
7
+ if(!Array.isArray(allowedRoles)) {
8
+ throw new Error(rbacErrors.INVALID_ROLES.message)
9
+ }
10
+
11
+ return (req, res, next) => {
12
+
13
+ if(!req.user || req.user === undefined) {
14
+ return res.status(rbacErrors.UNAUTHORIZED.status).json(rbacErrors.UNAUTHORIZED.message)
15
+ }
16
+
17
+ if(!req.user.role || req.user.role === undefined) {
18
+ return res.status(rbacErrors.ROLE_MISSING.status).json(rbacErrors.ROLE_MISSING.message)
19
+ }
20
+
21
+ if(!allowedRoles.includes(req.user.role)){
22
+ return res.status(rbacErrors.FORBIDDEN.status).json(rbacErrors.FORBIDDEN.message)
23
+ }
24
+
25
+ next()
26
+
27
+ }
28
+ }
package/src/errors.js ADDED
@@ -0,0 +1,24 @@
1
+ export const rbacErrors = {
2
+
3
+ UNAUTHORIZED: {
4
+ status: 401,
5
+ message: 'unauthorized: user not authenticated'
6
+ },
7
+
8
+ ROLE_MISSING: {
9
+ status: 401,
10
+ message: 'Unauthorized: user role not found'
11
+ },
12
+
13
+ FORBIDDEN: {
14
+ status: 403,
15
+ message: 'unauthorized user: insufficient permissions'
16
+ },
17
+
18
+ INVALID_ROLES: {
19
+ status: 500,
20
+ message: 'Server error: invalid roles configuration'
21
+ }
22
+
23
+
24
+ }
package/src/index.js ADDED
@@ -0,0 +1,5 @@
1
+
2
+ import { authorize } from './authorize.js'
3
+
4
+
5
+ export { authorize }