dev1/backend/utils/authenticateUser.js
Josh 5838f782e7
Some checks failed
ci/woodpecker/push/woodpecker Pipeline failed
removed files from tracking, dependencies, fixed encryption
2025-08-19 12:24:54 +00:00

29 lines
820 B
JavaScript

import jwt from "jsonwebtoken";
const JWT_SECRET = process.env.JWT_SECRET;
const COOKIE_NAME = process.env.COOKIE_NAME || 'aptiva_session';
/**
* Adds `req.user = { id }`
* Accepts either Bearer token or httpOnly cookie.
* 401 on missing; 401 again on invalid/expired.
*/
export default function authenticateUser(req, res, next) {
let token = req.headers.authorization?.startsWith('Bearer ')
? req.headers.authorization.split(' ')[1]
: null;
if (!token) {
token = req.cookies?.[COOKIE_NAME] || req.cookies?.token || null;
}
if (!token) return res.status(401).json({ error: "Authorization token required" });
try {
const { id } = jwt.verify(token, JWT_SECRET);
req.user = { id };
next();
} catch {
return res.status(401).json({ error: "Invalid or expired token" });
}
}