eletrotupi / tcc/ api/src/middleware/auth.ts16e98ad4fc123f536ae1c082c199095289a3ee05
970 B | 33 lines Raw
1
import { Request, Response, NextFunction } from 'express';
2
import { verifyToken } from '@app/lib/jwt';
3

4
export interface AuthenticatedRequest extends Request {
5
  userId?: number;
6
  userEmail?: string;
7
}
8

9
export const requireAuth = (req: AuthenticatedRequest, res: Response, next: NextFunction) => {
10
  try {
11
    const authHeader = req.headers.authorization;
12

13
    if (!authHeader || !authHeader.startsWith('Bearer ')) {
14
      return res.status(401).json({ error: 'Unauthorized: No token provided' });
15
    }
16

17
    const token = authHeader.substring(7);
18
    const payload = verifyToken(token);
19

20
    req.userId = payload.userId;
21
    req.userEmail = payload.email;
22

23
    next();
24
  } catch (err: any) {
25
    if (err.name === 'JsonWebTokenError') {
26
      return res.status(401).json({ error: 'Unauthorized: Invalid token' });
27
    }
28
    if (err.name === 'TokenExpiredError') {
29
      return res.status(401).json({ error: 'Unauthorized: Token expired' });
30
    }
31
    next(err);
32
  }
33
};