Files
rxminder/services/auth/auth.middleware.ts

49 lines
1.3 KiB
TypeScript

import { Request, Response, NextFunction } from 'express';
import * as jwt from 'jsonwebtoken';
import { JWT_SECRET } from './auth.constants';
import { AuthError, handleAuthError } from './auth.error';
// Security: JWT authentication middleware
export const authenticate = (
req: Request,
res: Response,
next: NextFunction
) => {
try {
// Security: Get token from Authorization header
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
throw new AuthError('No authentication token provided', 401);
}
const token = authHeader.split(' ')[1];
// Security: Verify JWT token
const decoded = jwt.verify(token, JWT_SECRET);
// Add user information to request
req.user = decoded;
next();
} catch (error) {
handleAuthError(error, req, res, next);
}
};
// Security: Role-based authorization middleware
export const authorize = (..._allowedRoles: string[]) => {
return (req: Request, res: Response, next: NextFunction) => {
try {
// Security: Check if user exists in request
if (!req.user) {
throw new AuthError('Authentication required', 401);
}
// In a full implementation, we would check user roles
next();
} catch (error) {
handleAuthError(error, req, res, next);
}
};
};