This commit is contained in:
seb
2026-10-01 22:48:44 +02:00
parent ea51f30a8d
commit 20886e7c76
9 changed files with 16471 additions and 62 deletions

View File

@@ -47,7 +47,7 @@ function authMeJson(res, req, status, body) {
}
export const authMiddleware = async (req, res, next) => {
if (req.path === '/' || req.path === '/api/auth/login' || req.path === '/api/auth/logout' || req.path === '/api/health') {
if (req.path === '/' || req.path === '/api/auth/login' || req.path === '/api/auth/logout' || req.path === '/api/health' || req.path === '/api/openapi.json') {
return next();
}
@@ -59,14 +59,23 @@ export const authMiddleware = async (req, res, next) => {
return next();
}
const token = req.cookies.token;
if (!token) return authMeJson(res, req, 401, { error: 'Unauthorized' });
const bearerToken = req.headers.authorization?.startsWith('Bearer ')
? req.headers.authorization.slice(7).trim()
: null;
const token = req.cookies.token || bearerToken;
const isDocs = req.path.startsWith('/docs') || req.path.startsWith('/api/docs');
if (!token) {
if (isDocs) return next();
return authMeJson(res, req, 401, { error: 'Unauthorized' });
}
try {
const decoded = jwt.verify(token, env.jwtSecret);
const authId = Number(decoded.id);
if (!Number.isInteger(authId) || authId <= 0) {
clearTokenCookie(res);
if (req.cookies.token) clearTokenCookie(res);
if (isDocs) return next();
return authMeJson(res, req, 401, { error: 'Invalid token' });
}
@@ -82,7 +91,8 @@ export const authMiddleware = async (req, res, next) => {
}
if (!user) {
clearCachedUser(authId);
clearTokenCookie(res);
if (req.cookies.token) clearTokenCookie(res);
if (isDocs) return next();
return authMeJson(res, req, 403, { error: 'User is no longer authorized' });
}
@@ -93,7 +103,7 @@ export const authMiddleware = async (req, res, next) => {
};
const now = Math.floor(Date.now() / 1000);
if (decoded.exp - now < 2 * 60 * 60) {
if (req.cookies.token && decoded.exp - now < 2 * 60 * 60) {
const newToken = jwt.sign({ id: user.id }, env.jwtSecret, { expiresIn: '1d' });
res.cookie('token', newToken, {
...TOKEN_COOKIE,
@@ -103,7 +113,9 @@ export const authMiddleware = async (req, res, next) => {
next();
} catch {
clearTokenCookie(res);
if (req.cookies.token) clearTokenCookie(res);
if (isDocs) return next();
return authMeJson(res, req, 401, { error: 'Invalid token' });
}
};