mirror of
https://github.com/andwati/order-service.git
synced 2026-11-26 19:08:46 +00:00
feat: implement authentication middleware and extend Express Request type
This commit is contained in:
@@ -1,13 +1,37 @@
|
|||||||
import { Router } from "express";
|
import type { NextFunction, Request, Response } from "express";
|
||||||
|
import { verifyToken } from "../utils/jwt.js";
|
||||||
|
|
||||||
const router = Router();
|
export function authMiddleware(
|
||||||
|
req: Request,
|
||||||
|
_res: Response,
|
||||||
|
next: NextFunction,
|
||||||
|
) {
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
||||||
|
return next({
|
||||||
|
status: 401,
|
||||||
|
message: "Missing or invalid Authorization header",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
router.post("/register", (_req, res) => {
|
const token = authHeader.split(" ")[1];
|
||||||
res.status(501).json({ message: "Register endpoint not implemented yet." });
|
|
||||||
});
|
|
||||||
|
|
||||||
router.post("/login", (_req, res) => {
|
if (!token) {
|
||||||
res.status(501).json({ message: "Login endpoint not implemented yet." });
|
return next({
|
||||||
});
|
status: 401,
|
||||||
|
message: "Missing token",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
export default router;
|
try {
|
||||||
|
const payload = verifyToken(token);
|
||||||
|
req.user = payload;
|
||||||
|
|
||||||
|
next();
|
||||||
|
} catch {
|
||||||
|
next({
|
||||||
|
statusCode: 401,
|
||||||
|
message: "Invalid or expired token",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Vendored
+9
@@ -0,0 +1,9 @@
|
|||||||
|
import { JwtPayload } from "../utils/jwt.js";
|
||||||
|
|
||||||
|
declare global {
|
||||||
|
namespace Express {
|
||||||
|
interface Request {
|
||||||
|
user?: JwtPayload;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user