| 1 | import { NextFunction, Request, Response } from "express"; |
| 2 | import { StatusCodes } from "http-status-codes/build/cjs"; |
| 3 | import { AppError } from "../utils/errors"; |
| 4 | import { AuthService } from "../services/auth.service"; |
| 5 | |
| 6 | declare global { |
| 7 | namespace Express { |
| 8 | interface Request { |
| 9 | user?: { |
| 10 | userId: string; |
| 11 | email: string; |
| 12 | }; |
| 13 | } |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | export const authenticate = async ( |
| 18 | req: Request, |
| 19 | res: Response, |
| 20 | next: NextFunction |
| 21 | ) => { |
| 22 | try { |
| 23 | const authHeader = req.headers.authorization; |
| 24 | if (!authHeader || !authHeader.startsWith("Bearer ")) { |
| 25 | throw new AppError(StatusCodes.UNAUTHORIZED, "Unauthorized"); |
| 26 | } |
| 27 | |
| 28 | const token = authHeader.split(" ")[1]; |
| 29 | const decoded = AuthService.verifyToken(token); |
| 30 | |
| 31 | req.user = decoded; |
| 32 | next(); |
| 33 | } catch (error) { |
| 34 | next(error); |
| 35 | } |
| 36 | }; |