summaryrefslogtreecommitdiff
path: root/backend/src/middleware
diff options
context:
space:
mode:
authorArne Rief <riearn@proton.me>2025-12-19 20:03:03 +0100
committerArne Rief <riearn@proton.me>2025-12-19 20:03:03 +0100
commit655ec610fcce8dd7748f10772d520bdff4f7c78e (patch)
tree35b79f30d2cb5aea88cf76ce27f480da93cefd32 /backend/src/middleware
Basic setup & login
Diffstat (limited to 'backend/src/middleware')
-rw-r--r--backend/src/middleware/authCheck.ts36
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;