u
This commit is contained in:
@@ -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' });
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user