Created
March 11, 2026 09:59
-
-
Save RuliLG/d7707a516f84f00052667b2223c4239c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { Request, Response, NextFunction } from "express"; | |
| import jwt from "jsonwebtoken"; | |
| const JWT_SECRET = process.env.JWT_SECRET || "dev-secret"; | |
| export interface AuthRequest extends Request { | |
| userId?: string; | |
| } | |
| export function requireAuth(req: AuthRequest, res: Response, next: NextFunction) { | |
| const token = req.headers.authorization?.split(" ")[1]; | |
| if (!token) { | |
| return res.status(401).json({ error: "No token provided" }); | |
| } | |
| try { | |
| const decoded = jwt.verify(token, JWT_SECRET) as { userId: string }; | |
| req.userId = decoded.userId; | |
| next(); | |
| } catch { | |
| return res.status(401).json({ error: "Invalid token" }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment