48 lines
1.3 KiB
JavaScript
48 lines
1.3 KiB
JavaScript
const jwt = require('../tools/jwt');
|
|
const { validateSession } = require('../core/auth.core');
|
|
|
|
const userAuth = async (req, res, next) => {
|
|
const token = (req.cookies && req.cookies.auth_token) || jwt.getToken(req.headers['authorization']);
|
|
|
|
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();
|
|
}
|
|
|
|
if (token.length > 2048) {
|
|
return redirectToLogin();
|
|
}
|
|
|
|
const verified = jwt.verifyToken(token);
|
|
if (!verified.valid) {
|
|
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();
|
|
};
|
|
|
|
module.exports = userAuth;
|