Private
Public Access
1
0
Files
star-wars-wild-space/server/middleware/auth.js

22 lines
639 B
JavaScript

import jwt from "jsonwebtoken";
if (!process.env.JWT_SECRET) {
throw new Error("[startup] JWT_SECRET environment variable is required but not set.");
}
export const JWT_SECRET = process.env.JWT_SECRET;
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" });
}
}