diff options
Diffstat (limited to 'backend/src/middleware/authCheck.ts')
| -rw-r--r-- | backend/src/middleware/authCheck.ts | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/backend/src/middleware/authCheck.ts b/backend/src/middleware/authCheck.ts new file mode 100644 index 0000000..4ee0806 --- /dev/null +++ b/backend/src/middleware/authCheck.ts @@ -0,0 +1,36 @@ +import { NextFunction, Request, Response } from "express"; +import jwt from "jsonwebtoken"; +import type { AuthorizedUser } from "../types/user.js"; + +async function authenticateUser( + req: Request, + res: Response, + next: NextFunction +) { + const authHeader = req.headers.authorization; + + if (!authHeader || !authHeader.startsWith("Bearer ")) { + return res.status(401).json({ + message: "User authentication failed.", + }); + } + + const token = authHeader.split(" ")[1]; + + try { + const authorizedUser = jwt.verify( + token, + process.env.JWT_SECRET! + ) as AuthorizedUser; + + req.user = authorizedUser; + next(); + } catch (error) { + console.error("User authentication failed: ", error); + return res.status(403).json({ + message: "User authentication failed.", + }); + } +} + +export default authenticateUser; |
