fix: additional fix for auth login flow and auth web pages and database
connection.
This commit is contained in:
@@ -44,27 +44,40 @@ router.post('/register', async (req, res) => {
|
||||
});
|
||||
|
||||
router.post('/login', async (req, res) => {
|
||||
const { username, password, redirect } = req.body;
|
||||
const { username, password, redirect, _csrf } = req.body;
|
||||
|
||||
const loginRedirect = (errorKey, safeRedirect) => {
|
||||
const params = new URLSearchParams({ error: errorKey });
|
||||
if (safeRedirect) params.set('redirect', safeRedirect);
|
||||
return res.redirect(`/login?${params.toString()}`);
|
||||
};
|
||||
|
||||
// Validazione CSRF (double-submit cookie)
|
||||
const csrfCookie = req.cookies && req.cookies._csrf;
|
||||
if (!_csrf || !csrfCookie || _csrf !== csrfCookie) {
|
||||
return loginRedirect('csrf', '');
|
||||
}
|
||||
|
||||
// Validazione base
|
||||
if (!username || !password || typeof username !== 'string' || typeof password !== 'string') {
|
||||
return res.render('loginpage', { error: 'Credenziali non valide', redirect: redirect || '' });
|
||||
return loginRedirect('invalid_credentials', redirect || '');
|
||||
}
|
||||
|
||||
// Limiti di lunghezza per prevenire abuse
|
||||
if (username.length > 50 || password.length > PASSWORD_MAX_LENGTH) {
|
||||
return res.render('loginpage', { error: 'Credenziali non valide', redirect: redirect || '' });
|
||||
return loginRedirect('invalid_credentials', redirect || '');
|
||||
}
|
||||
|
||||
// Validazione redirect URL per prevenire open redirect attacks
|
||||
let safeRedirect = '';
|
||||
if (redirect && typeof redirect === 'string') {
|
||||
try {
|
||||
const redirectUrl = new URL(redirect);
|
||||
const consoleUrl = new URL(CONSOLE_URL);
|
||||
// Permetti redirect solo allo stesso dominio del CONSOLE_URL
|
||||
if (redirectUrl.hostname !== consoleUrl.hostname) {
|
||||
return res.render('loginpage', { error: 'Redirect non autorizzato', redirect: '' });
|
||||
return loginRedirect('invalid_redirect', '');
|
||||
}
|
||||
safeRedirect = redirect;
|
||||
} catch {
|
||||
// URL relativo o non valido — ignora il redirect
|
||||
}
|
||||
@@ -87,13 +100,13 @@ router.post('/login', async (req, res) => {
|
||||
}
|
||||
|
||||
res.cookie('auth_token', token, cookieOptions);
|
||||
res.clearCookie('_csrf');
|
||||
|
||||
const destination = redirect || CONSOLE_URL;
|
||||
const destination = safeRedirect || CONSOLE_URL;
|
||||
res.redirect(destination);
|
||||
} catch (err) {
|
||||
console.error('[AUTH] Login failed:', err.message);
|
||||
// Mai rivelare se è l'utente o la password ad essere sbagliati
|
||||
res.render('loginpage', { error: 'Credenziali non valide', redirect: redirect || '' });
|
||||
return loginRedirect('invalid_credentials', safeRedirect);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user