18 lines
542 B
JavaScript
18 lines
542 B
JavaScript
import jwt from "jsonwebtoken";
|
|
|
|
export const JWT_SECRET = process.env.JWT_SECRET ?? "dev_secret_change_me";
|
|
|
|
export function authMiddleware(req, res, next) {
|
|
const authHeader = req.headers["authorization"];
|
|
if (!authHeader || !authHeader.startsWith("Bearer ")) {
|
|
return res.status(401).json({ error: "unauthorized" });
|
|
}
|
|
const token = authHeader.slice(7);
|
|
try {
|
|
const payload = jwt.verify(token, JWT_SECRET);
|
|
req.user = payload;
|
|
next();
|
|
} catch {
|
|
return res.status(401).json({ error: "invalid_token" });
|
|
}
|
|
} |