index.ts109 lines, 2.7 KB
| 1 | import { Request, Response, NextFunction } from "express"; |
| 2 | import { JWTPayload, logError, ServiceError } from "../types"; |
| 3 | import { createErrorResponse } from "../utils"; |
| 4 | import jwt from "jsonwebtoken"; |
| 5 | |
| 6 | // extends express request interface to include custom properties |
| 7 | declare global { |
| 8 | namespace Express { |
| 9 | interface Request { |
| 10 | user?: any; |
| 11 | } |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | export function authenticateToken( |
| 16 | req: Request, |
| 17 | res: Response, |
| 18 | next: NextFunction |
| 19 | ) { |
| 20 | const authHeader = req.headers["authorization"]; |
| 21 | const token = authHeader && authHeader.split(" ")[1]; // Bearer token |
| 22 | |
| 23 | if (!token) { |
| 24 | return res.status(401).json(createErrorResponse("Access token required")); |
| 25 | } |
| 26 | |
| 27 | const jwtSecret = process.env.JWT_SECRET; |
| 28 | if (!jwtSecret) { |
| 29 | logError(new Error("JWT_SECRET is not defined")); |
| 30 | return res.status(500).json(createErrorResponse("Internal Server Error")); |
| 31 | } |
| 32 | |
| 33 | jwt.verify(token, jwtSecret, (err: any, decoded: any) => { |
| 34 | if (err) { |
| 35 | return res.status(403).json(createErrorResponse("Invalid token")); |
| 36 | } |
| 37 | |
| 38 | req.user = decoded as JWTPayload; // Attach user info to request |
| 39 | next(); |
| 40 | }); |
| 41 | } |
| 42 | |
| 43 | export function asyncHandler( |
| 44 | fn: (req: Request, res: Response, next: NextFunction) => Promise<any> |
| 45 | ) { |
| 46 | return (req: Request, res: Response, next: NextFunction): void => { |
| 47 | Promise.resolve(fn(req, res, next)).catch(next); |
| 48 | }; |
| 49 | } |
| 50 | |
| 51 | export function validateRequest(schema: any) { |
| 52 | return (req: Request, res: Response, next: NextFunction) => { |
| 53 | const { error } = schema.validate(req.body); |
| 54 | |
| 55 | if (error) { |
| 56 | const errors: Record<string, string[]> = {}; |
| 57 | error.details.forEach((detail: any) => { |
| 58 | const field = detail.path.join("."); |
| 59 | if (!error[field]) { |
| 60 | errors[field] = []; |
| 61 | } |
| 62 | errors[field].push(detail.message); |
| 63 | }); |
| 64 | |
| 65 | return res.status(400).json({ |
| 66 | success: false, |
| 67 | message: "Validation error", |
| 68 | errors, |
| 69 | }); |
| 70 | } |
| 71 | |
| 72 | next(); |
| 73 | }; |
| 74 | } |
| 75 | |
| 76 | export function errorHandler( |
| 77 | error: ServiceError, |
| 78 | req: Request, |
| 79 | res: Response, |
| 80 | next: NextFunction |
| 81 | ) { |
| 82 | logError(error, { |
| 83 | method: req.method, |
| 84 | url: req.url, |
| 85 | body: req.body, |
| 86 | params: req.params, |
| 87 | query: req.query, |
| 88 | }); |
| 89 | |
| 90 | const statusCode = error.statusCode || 500; |
| 91 | const message = error.message || "Internal Server Error"; |
| 92 | |
| 93 | res.status(statusCode).json(createErrorResponse(message)); |
| 94 | |
| 95 | next(); |
| 96 | } |
| 97 | |
| 98 | export function corsOptions() { |
| 99 | return { |
| 100 | origin: process.env.CORS_ORIGIN || "http://localhost:3000", |
| 101 | credentials: process.env.CORS_CREDENTIALS === "true", |
| 102 | methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], |
| 103 | allowedHeaders: ["Content-Type", "Authorization"], |
| 104 | }; |
| 105 | } |
| 106 | |
| 107 | export function healthCheck(req: Request, res: Response) { |
| 108 | res.json({ status: "ok", timestamp: new Date().toISOString() }); |
| 109 | } |