@dax-crafta/auth 1.1.0 → 1.2.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
CHANGED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const rateLimit = require('express-rate-limit');
|
|
2
|
+
const jwt = require('jsonwebtoken');
|
|
3
|
+
|
|
4
|
+
const createAuthMiddleware = (config) => {
|
|
5
|
+
const rateLimiter = rateLimit({
|
|
6
|
+
windowMs: 15 * 60 * 1000, // 15 minutes
|
|
7
|
+
max: 100 // limit each IP to 100 requests per windowMs
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
const verifyToken = (req, res, next) => {
|
|
11
|
+
const token = req.headers.authorization?.split(' ')[1];
|
|
12
|
+
|
|
13
|
+
if (!token) {
|
|
14
|
+
return res.status(401).json({
|
|
15
|
+
success: false,
|
|
16
|
+
error: 'No token provided'
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
try {
|
|
21
|
+
const decoded = jwt.verify(token, config.env.JWT_SECRET);
|
|
22
|
+
req.user = decoded;
|
|
23
|
+
next();
|
|
24
|
+
} catch (error) {
|
|
25
|
+
res.status(401).json({
|
|
26
|
+
success: false,
|
|
27
|
+
error: 'Invalid token'
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const checkRole = (roles) => {
|
|
33
|
+
return (req, res, next) => {
|
|
34
|
+
if (!roles.includes(req.user.role)) {
|
|
35
|
+
return res.status(403).json({
|
|
36
|
+
success: false,
|
|
37
|
+
error: 'Insufficient permissions'
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
next();
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
rateLimiter,
|
|
46
|
+
verifyToken,
|
|
47
|
+
checkRole
|
|
48
|
+
};
|
|
49
|
+
};
|
|
50
|
+
|
|
51
|
+
module.exports = createAuthMiddleware;
|