(req: Request, res: Response, next: NextFunction)
| 4 | import { env } from "../config/env.js"; |
| 5 | |
| 6 | export const authMiddleWare = (req: Request, res: Response, next: NextFunction) => { |
| 7 | const authHeader = req.headers.authorization; |
| 8 | if (!authHeader || !authHeader.startsWith("Bearer ")) { |
| 9 | res.status(401).json({ |
| 10 | success: false, |
| 11 | error: "Access token required, or the access token is incorrect" |
| 12 | }) |
| 13 | return |
| 14 | } |
| 15 | //now yaha se the good ol way of extracting token and then using it |
| 16 | const token = authHeader.split(" ")[1] |
| 17 | if (!token) { |
| 18 | res.status(401).json({ |
| 19 | success: false, |
| 20 | error: "Access token missing" |
| 21 | }) |
| 22 | return |
| 23 | } |
| 24 | try { |
| 25 | const payload = jwt.verify(token, env.ACCESS_TOKEN_SECRET) as unknown as { userId: string } |
| 26 | //@ts-ignore adding userId to req object: |
| 27 | req.userId = payload.userId |
| 28 | next() |
| 29 | } catch (err) { |
| 30 | res.status(401).json({ |
| 31 | success: false, |
| 32 | error: "invalid or expired access token" |
| 33 | }) |
| 34 | } |
| 35 | } |
nothing calls this directly
no outgoing calls
no test coverage detected