fix: additional fix for auth login flow and auth web pages and database
connection.
This commit is contained in:
@@ -1,31 +1,45 @@
|
||||
const jwt = require('../tools/jwt');
|
||||
const { validateSession } = require('../core/auth.core');
|
||||
|
||||
/**
|
||||
* Middleware di autenticazione per utenti finali.
|
||||
* Verifica il JWT dal cookie 'auth_token' o dall'header 'Authorization: Bearer <token>'.
|
||||
*
|
||||
* Se valido, inietta req.user con { user_id, username, session_id }.
|
||||
*/
|
||||
const userAuth = (req, res, next) => {
|
||||
const userAuth = async (req, res, next) => {
|
||||
const token = (req.cookies && req.cookies.auth_token) || jwt.getToken(req.headers['authorization']);
|
||||
|
||||
if (!token || typeof token !== 'string') {
|
||||
const redirectToLogin = () => {
|
||||
if (req.accepts('html')) {
|
||||
const redirect = encodeURIComponent(req.originalUrl);
|
||||
return res.redirect(`/login?redirect=${redirect}`);
|
||||
}
|
||||
return res.status(401).json({ error: 'Accesso negato: token mancante' });
|
||||
};
|
||||
|
||||
if (!token || typeof token !== 'string') {
|
||||
return redirectToLogin();
|
||||
}
|
||||
|
||||
// Limite ragionevole sulla lunghezza del token per evitare abusi
|
||||
if (token.length > 2048) {
|
||||
return res.status(400).json({ error: 'Token non valido' });
|
||||
return redirectToLogin();
|
||||
}
|
||||
|
||||
const verified = jwt.verifyToken(token);
|
||||
if (!verified.valid) {
|
||||
return res.status(401).json({
|
||||
error: 'Sessione non valida o scaduta',
|
||||
reason: verified.reason
|
||||
if (req.accepts('html')) {
|
||||
return res.redirect('/login');
|
||||
}
|
||||
return res.status(401).json({
|
||||
error: 'Sessione non valida o scaduta',
|
||||
reason: verified.reason
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await validateSession(verified.payload.session_id);
|
||||
} catch {
|
||||
if (req.accepts('html')) {
|
||||
return res.redirect('/login');
|
||||
}
|
||||
return res.status(401).json({ error: 'Sessione non valida o revocata' });
|
||||
}
|
||||
|
||||
req.user = verified.payload;
|
||||
next();
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user