myex-cli
Version:
Opinionated Express.js framework with CLI tools
72 lines (65 loc) • 2.16 kB
JavaScript
import jwt from 'jsonwebtoken';
import { logger } from '../utils/logger.js';
export const authMiddleware = {
/**
* Middleware to authenticate JWT token
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {import('express').NextFunction} next - Express next function
*/
authenticateToken: (req, res, next) => {
try {
// Get token from Authorization header
const authHeader = req.headers.authorization;
const token = authHeader && authHeader.split(' ')[1];
if (!token) {
return res.status(401).json({
status: 'error',
message: 'Authentication required',
});
}
// Verify token
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
logger.warn(`Invalid token: ${err.message}`);
return res.status(403).json({
status: 'error',
message: 'Invalid or expired token',
});
}
// Attach user to request
req.user = user;
next();
});
} catch (error) {
logger.error(`Authentication error: ${error.message}`);
res.status(500).json({
status: 'error',
message: 'Authentication failed',
});
}
},
/**
* Middleware to check if user has admin role
* @param {import('express').Request} req - Express request object
* @param {import('express').Response} res - Express response object
* @param {import('express').NextFunction} next - Express next function
*/
requireAdmin: (req, res, next) => {
// Check if user is authenticated and has admin role
if (!req.user) {
return res.status(401).json({
status: 'error',
message: 'Authentication required',
});
}
if (req.user.role !== 'admin') {
logger.warn(`Access denied: User ${req.user.id} attempted to access admin resource`);
return res.status(403).json({
status: 'error',
message: 'Access denied: Insufficient permissions',
});
}
next();
},
};