| import { Request, Response, NextFunction } from 'express'; | |
| import jwt from 'jsonwebtoken'; | |
| import { config } from '../config'; | |
| import { User } from '../models'; | |
| export interface AuthRequest extends Request { | |
| userId?: string; | |
| userRole?: string; | |
| } | |
| export const authMiddleware = async ( | |
| req: AuthRequest, | |
| res: Response, | |
| next: NextFunction | |
| ): Promise<void> => { | |
| try { | |
| const authHeader = req.headers.authorization; | |
| if (!authHeader || !authHeader.startsWith('Bearer ')) { | |
| res.status(401).json({ error: 'Access denied. No token provided.' }); | |
| return; | |
| } | |
| const token = authHeader.split(' ')[1]; | |
| const decoded = jwt.verify(token, config.jwt.secret) as { | |
| userId: string; | |
| role: string; | |
| }; | |
| const user = await User.findById(decoded.userId); | |
| if (!user) { | |
| res.status(401).json({ error: 'Invalid token. User not found.' }); | |
| return; | |
| } | |
| req.userId = decoded.userId; | |
| req.userRole = decoded.role; | |
| next(); | |
| } catch (error) { | |
| res.status(401).json({ error: 'Invalid or expired token.' }); | |
| } | |
| }; | |
| export const adminMiddleware = ( | |
| req: AuthRequest, | |
| res: Response, | |
| next: NextFunction | |
| ): void => { | |
| if (req.userRole !== 'admin') { | |
| res.status(403).json({ error: 'Admin access required.' }); | |
| return; | |
| } | |
| next(); | |
| }; | |