78 lines
2.4 KiB
JavaScript
78 lines
2.4 KiB
JavaScript
const express = require('express');
|
|
const crypto = require('crypto');
|
|
const rateLimit = require('express-rate-limit');
|
|
const User = require('../models/User');
|
|
const sendVerificationEmail = require('../utils/mailer');
|
|
const { log, error } = require('../utils/logger');
|
|
|
|
const router = express.Router();
|
|
|
|
const limiter = rateLimit({
|
|
windowMs: parseInt(process.env.RATE_LIMIT_WINDOW) * 60 * 1000,
|
|
max: parseInt(process.env.RATE_LIMIT_MAX),
|
|
message: 'Troppi tentativi. Riprova più tardi.'
|
|
});
|
|
|
|
router.post('/verifica-email', limiter, async (req, res) => {
|
|
const { nome, cognome, email, telefono, applicazione } = req.body;
|
|
|
|
if (!nome || !cognome || !email || !telefono || !applicazione) {
|
|
return res.status(400).json({ error: 'Tutti i campi sono obbligatori' });
|
|
}
|
|
|
|
const codice = crypto.randomInt(100000, 999999).toString();
|
|
|
|
try {
|
|
const nuovoUtente = new User({
|
|
nome, cognome, email, telefono, applicazione, codiceVerifica: codice
|
|
});
|
|
|
|
await nuovoUtente.save();
|
|
await sendVerificationEmail({ nome, email, codice, applicazione });
|
|
|
|
log(`Codice ${codice} inviato a ${email}`);
|
|
res.json({ message: 'Codice inviato via email' });
|
|
} catch (err) {
|
|
if (err.code === 11000) {
|
|
res.status(409).json({ error: 'Email già registrata' });
|
|
} else {
|
|
error('Errore registrazione:', err);
|
|
res.status(500).json({ error: 'Errore interno' });
|
|
}
|
|
}
|
|
});
|
|
|
|
router.post('/conferma-codice', async (req, res) => {
|
|
const { email, codice } = req.body;
|
|
|
|
const utente = await User.findOne({ email });
|
|
|
|
if (!utente) return res.status(404).json({ error: 'Utente non trovato' });
|
|
|
|
if (utente.codiceVerifica === codice) {
|
|
utente.verificato = true;
|
|
await utente.save();
|
|
log(`Email ${email} verificata`);
|
|
res.json({ message: 'Email verificata con successo' });
|
|
} else {
|
|
res.status(400).json({ error: 'Codice errato' });
|
|
}
|
|
});
|
|
|
|
router.post('/cancella_utente', async (req, res) => {
|
|
const { email } = req.body;
|
|
|
|
const utente = await User.findOne({ email });
|
|
|
|
if (!utente) return res.status(404).json({ error: 'Utente non trovato' });
|
|
|
|
if (utente.verificato) {
|
|
await User.deleteMany({ email });
|
|
log(`Utente cancellato Email ${email}`);
|
|
res.json({ message: `cancellazione utente ${email}`});
|
|
} else {
|
|
res.status(400).json({ error: 'Utente non verificato si cancella da solo entro 60 sec' });
|
|
}
|
|
});
|
|
|
|
module.exports = router;
|