File size: 1,091 Bytes
e9999a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import { Request, Response, NextFunction } from 'express';
import jwt from 'jsonwebtoken';
import { config } from '../../config';
export interface AuthRequest extends Request {
user?: { id: string; email: string; orgId: string; role: string };
}
export function requireAuth(req: AuthRequest, res: Response, next: NextFunction) {
const authHeader = req.headers.authorization;
if (!authHeader?.startsWith('Bearer ')) {
return res.status(401).json({ error: { message: 'Missing token', code: 'UNAUTHORIZED' } });
}
const token = authHeader.slice(7);
try {
const payload = jwt.verify(token, config.JWT_SECRET) as any;
req.user = payload;
next();
} catch {
return res.status(401).json({ error: { message: 'Invalid token', code: 'UNAUTHORIZED' } });
}
}
export function requireRole(...roles: string[]) {
return (req: AuthRequest, res: Response, next: NextFunction) => {
if (!req.user || !roles.includes(req.user.role)) {
return res.status(403).json({ error: { message: 'Insufficient permissions', code: 'FORBIDDEN' } });
}
next();
};
}
|