MCPcopy Create free account
hub / github.com/dexisback/backend-101 / authMiddleWare

Function authMiddleWare

auth/src/middleware/auth.middleware.ts:6–35  ·  view source on GitHub ↗
(req: Request, res: Response, next: NextFunction)

Source from the content-addressed store, hash-verified

4import { env } from "../config/env.js";
5
6export 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}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected