feat: implement internal and user security middlewares and refactor route structures to support view and API separation

This commit is contained in:
Giuseppe Raffa
2026-04-04 19:11:29 +02:00
parent 0f511c2cf9
commit 3cd5a84cc1
8 changed files with 83 additions and 42 deletions

View File

@@ -1,32 +1,11 @@
// api.mebboat.it/users
const router = require('express').Router();
const jwt = require('../tools/jwt');
const { query } = require('../storage/database');
const userAuth = require('../middlewares/user.security');
const internalAuth = require('../middlewares/internal.security');
// Middleware di autenticazione: estrae l'utente dal token JWT
const requireAuth = (req, res, next) => {
// Estraiamo il token dai cookies (inserito al login) o dall'header "Authorization"
const token = (req.cookies && req.cookies.auth_token) || jwt.getToken(req.headers['authorization']);
if (!token) {
return res.status(401).json({ error: 'Non autorizzato: token mancante' });
}
const verified = jwt.verifyToken(token);
if (!verified.valid) {
return res.status(401).json({ error: 'Non autorizzato: token scaduto o non valido', reason: verified.reason });
}
// Il riferimento all'identità dell'utente viene agganciato all'oggetto `req`
// (payload conterrà { user_id, username, session_id })
req.user = verified.payload;
next();
};
router.use(requireAuth);
router.get('/', async (req, res) => {
router.get('/', internalAuth, async (req, res) => {
try {
const result = await query(
'SELECT id, username, is_active, created_at, telegram_id FROM users'
@@ -37,7 +16,7 @@ router.get('/', async (req, res) => {
}
})
router.get('/tonotify/', async (req, res) => {
router.get('/tonotify', internalAuth, async (req, res) => {
try {
const result = await query(
'SELECT telegram_id FROM users WHERE telegram_id IS NOT NULL'
@@ -48,6 +27,8 @@ router.get('/tonotify/', async (req, res) => {
}
})
router.use(userAuth);
router.get('/me', async (req, res) => {
try {
const result = await query(