@dax-crafta/auth
Version:
A powerful, flexible, and secure authentication plugin for the Crafta framework. Supports JWT, social login, 2FA, RBAC, audit logging, and enterprise-grade security features.
51 lines (44 loc) • 1.18 kB
JavaScript
const rateLimit = require('express-rate-limit');
const jwt = require('jsonwebtoken');
const createAuthMiddleware = (config) => {
const rateLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100 // limit each IP to 100 requests per windowMs
});
const verifyToken = (req, res, next) => {
const token = req.headers.authorization?.split(' ')[1];
if (!token) {
return res.status(401).json({
success: false,
error: 'No token provided'
});
}
try {
const decoded = jwt.verify(token, config.env.JWT_SECRET);
req.user = decoded;
next();
} catch (error) {
res.status(401).json({
success: false,
error: 'Invalid token'
});
}
};
const checkRole = (roles) => {
return (req, res, next) => {
if (!roles.includes(req.user.role)) {
return res.status(403).json({
success: false,
error: 'Insufficient permissions'
});
}
next();
};
};
return {
rateLimiter,
verifyToken,
checkRole
};
};
module.exports = createAuthMiddleware;