- Sistemato INVITI alla App
- Completamento Profilo - Registrazione tramite Invito, senza richiedere conferma email.
This commit is contained in:
@@ -25,7 +25,6 @@ var file = `.env.${node_env}`;
|
||||
|
||||
// GLOBALI (Uguali per TUTTI)
|
||||
process.env.LINKVERIF_REG = '/vreg';
|
||||
process.env.LINK_INVITO_A_REG = '/invitetoreg';
|
||||
process.env.LINK_REQUEST_NEWPASSWORD = '/requestnewpwd';
|
||||
process.env.ADD_NEW_SITE = '/addNewSite';
|
||||
process.env.LINK_UPDATE_PASSWORD = '/updatepassword';
|
||||
|
||||
@@ -159,8 +159,10 @@ async function filterValidItems(mycart) {
|
||||
const OrdersCart = require('./orderscart');
|
||||
|
||||
// Cancella l'ordine su Order e OrderCart e cancella il record su Cart
|
||||
await OrdersCart.deleteOrderById(item.order._id.toString());
|
||||
await Order.deleteOrderById(item.order._id.toString());
|
||||
if (item.order) {
|
||||
await OrdersCart.deleteOrderById(item.order._id.toString());
|
||||
await Order.deleteOrderById(item.order._id.toString());
|
||||
}
|
||||
|
||||
haschanged = true;
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ const ListaInvitiEmailSchema = new Schema({
|
||||
userIdInvite: {
|
||||
type: String,
|
||||
},
|
||||
usernameInvitante: {
|
||||
type: String,
|
||||
},
|
||||
date_Invited: {
|
||||
type: Date,
|
||||
default: Date.now,
|
||||
@@ -84,4 +87,3 @@ module.exports.findAllIdApp = async function (idapp) {
|
||||
module.exports.createIndexes()
|
||||
.then(() => { })
|
||||
.catch((err) => { throw err; });
|
||||
|
||||
|
||||
@@ -375,9 +375,9 @@ module.exports.generateNewSite_IdApp = async function (idapp, params, createpage
|
||||
myp = new MyPage({
|
||||
order: 10,
|
||||
idapp: mysite.idapp,
|
||||
path: 'home_logout',
|
||||
path: 'presentazione',
|
||||
active: true,
|
||||
title: 'Home NoLoggato',
|
||||
title: 'Presentazione',
|
||||
});
|
||||
rispag = await myp.save();
|
||||
}
|
||||
|
||||
@@ -6,11 +6,44 @@ const nodemailer = require('nodemailer');
|
||||
const { authenticate, authenticate_noerror, auth_default } = require('../middleware/authenticate');
|
||||
|
||||
const sendemail = require('../sendemail');
|
||||
const tools = require('../tools/general');
|
||||
|
||||
const { User } = require('../models/user');
|
||||
const ListaInvitiEmail = require('../models/listainvitiemail');
|
||||
|
||||
// ==========================================
|
||||
// ENDPOINT API
|
||||
// ==========================================
|
||||
|
||||
router.post('/getinv', async (req, res) => {
|
||||
try {
|
||||
const { tok } = req.body;
|
||||
|
||||
// Validazione
|
||||
if (!tok) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
message: 'token non presente',
|
||||
});
|
||||
}
|
||||
|
||||
const invitoreg = await ListaInvitiEmail.findOne({ token: tok }).lean();
|
||||
|
||||
if (invitoreg) {
|
||||
|
||||
return res.status(200).json({ success: true, rec: invitoreg });
|
||||
} else {
|
||||
return res.status(200).json({ success: false, rec: null });
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
return res.status(200).json({
|
||||
success: false,
|
||||
message: 'Errore ' + e.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /inviti/invia-email
|
||||
* Invia un invito via email
|
||||
@@ -38,38 +71,37 @@ router.post('/invia-email', authenticate, async (req, res) => {
|
||||
|
||||
const dati = { messaggioPersonalizzato, emailAmico, usernameInvitante };
|
||||
|
||||
const userInvitante = await User.findOne({ idapp, username: usernameInvitante }, { username: 1 });
|
||||
const userInvitante = await User.findOne({ idapp, username: usernameInvitante }, { username: 1 }).lean();
|
||||
|
||||
const invitoesiste = await ListaInvitiEmail.findOne({ idapp, email });
|
||||
const invitoesiste = await ListaInvitiEmail.findOne({ idapp, email: emailAmico });
|
||||
if (invitoesiste) {
|
||||
const dateInvito = new Date(invitoesiste.date_Invited);
|
||||
const dateNow = new Date();
|
||||
const diffTime = Math.abs(dateNow - dateInvito);
|
||||
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24 * 7));
|
||||
|
||||
if (diffDays > 7) {
|
||||
if (diffDays > 1) {
|
||||
// Posso reinviare l'invito
|
||||
await ListaInvitiEmail.deleteOne({ _id: invitoesiste._id });
|
||||
invitoesiste = null;
|
||||
} else {
|
||||
return res.status(200).json({
|
||||
success: false,
|
||||
message: `L'invito a questa email è stato già inviato il ${dateInvito.toDateString()}`,
|
||||
message: 'L\'invito a questa email è stato già inviato il ' + tools.getstrDate_DD_MM_YYYY(dateInvito),
|
||||
emailInviata: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const token = crypto.createHash('sha256').update(JSON.stringify(dati)).digest('hex');
|
||||
|
||||
dati.token = token;
|
||||
dati.token = tools.getTokenRandom();
|
||||
|
||||
// aggiungi la email alla lista inviti
|
||||
const listainviti = new ListaInvitiEmail({
|
||||
idapp,
|
||||
email: emailAmico,
|
||||
userIdInvite: userInvitante.username,
|
||||
token,
|
||||
usernameInvitante: userInvitante.username,
|
||||
userIdInvite: userInvitante._id,
|
||||
token: dati.token,
|
||||
});
|
||||
|
||||
await listainviti.save();
|
||||
|
||||
@@ -3,6 +3,8 @@ const router = express.Router();
|
||||
|
||||
const { User } = require('../models/user');
|
||||
|
||||
const ListaInvitiEmail = require('../models/listainvitiemail');
|
||||
|
||||
// const { Nave } = require('../models/nave');
|
||||
const Hours = require('../models/hours');
|
||||
//const { NavePersistente } = require('../models/navepersistente');
|
||||
@@ -136,6 +138,17 @@ router.post('/', async (req, res) => {
|
||||
|
||||
user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username);
|
||||
user.verified_email = false;
|
||||
|
||||
// Se è parte di un invito allora verified_email = true
|
||||
const recinvito = await ListaInvitiEmail.findOne({ email: body.email });
|
||||
if (recinvito) {
|
||||
user.verified_email = true;
|
||||
|
||||
recinvito.registered = true;
|
||||
recinvito.userIdRegistered = user._id;
|
||||
await recinvito.save();
|
||||
}
|
||||
|
||||
user.lasttimeonline = new Date();
|
||||
user.date_reg = new Date();
|
||||
user.aportador_iniziale = user.aportador_solidario;
|
||||
|
||||
@@ -495,7 +495,7 @@ module.exports = {
|
||||
return strlinkreg;
|
||||
},
|
||||
getlinkInvitoReg: function (idapp, dati) {
|
||||
const strlinkreg = tools.getHostByIdApp(idapp) + process.env.LINK_INVITO_A_REG + `/?idapp=${idapp}&tok=${dati.token}`;
|
||||
const strlinkreg = tools.getHostByIdApp(idapp) + `/invitetoreg/${dati.token}`;
|
||||
return strlinkreg;
|
||||
},
|
||||
sendEmail_Registration: async function (lang, emailto, user, idapp, idreg) {
|
||||
@@ -510,6 +510,7 @@ module.exports = {
|
||||
strlinkreg: this.getlinkReg(idapp, idreg),
|
||||
forgetpwd: tools.getHostByIdApp(idapp) + '/requestresetpwd',
|
||||
emailto: emailto,
|
||||
verified_email: user.verified_email,
|
||||
user,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,61 +1,97 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const express = require('express');
|
||||
var app = express();
|
||||
|
||||
function parseDomains() {
|
||||
try {
|
||||
return {
|
||||
const ris = {
|
||||
domains: JSON.parse(process.env.DOMAINS || '[]'),
|
||||
domainsAllowed: JSON.parse(process.env.DOMAINS_ALLOWED || '[]'),
|
||||
};
|
||||
return ris;
|
||||
} catch {
|
||||
return { domains: [], domainsAllowed: [] };
|
||||
}
|
||||
}
|
||||
|
||||
function createCorsOptions(domains = [], domainsAllowed = [], isProduction = false) {
|
||||
// 1️⃣ Prepara la lista host ammessi (senza porta)
|
||||
const baseHosts = isProduction
|
||||
? domains.flatMap((d) => [d.hostname, `api.${d.hostname}`, `test.${d.hostname}`, `testapi.${d.hostname}`])
|
||||
: ['localhost', '127.0.0.1'];
|
||||
function buildAllowedOrigins(domains, domainsAllowed, isProduction) {
|
||||
if (!isProduction) {
|
||||
return [
|
||||
'https://localhost:3000',
|
||||
'https://localhost:8089',
|
||||
'https://localhost:8082',
|
||||
'https://localhost:8083',
|
||||
'https://localhost:8084',
|
||||
'https://localhost:8085',
|
||||
'https://localhost:8088',
|
||||
'https://localhost:8099',
|
||||
'https://localhost:8094',
|
||||
'https://192.168.8.182',
|
||||
'https://192.168.8.182:8084/',
|
||||
'http://192.168.8.182:8084/',
|
||||
];
|
||||
}
|
||||
|
||||
const extraHosts = domainsAllowed.map((d) => d.replace(/^https?:\/\//, '').split(':')[0]);
|
||||
const baseOrigins = domains.flatMap((domain) => [
|
||||
`https://${domain.hostname}`,
|
||||
`https://api.${domain.hostname}`,
|
||||
`https://test.${domain.hostname}`,
|
||||
`https://testapi.${domain.hostname}`,
|
||||
`http://${domain.hostname}`,
|
||||
`http://api.${domain.hostname}`,
|
||||
`http://test.${domain.hostname}`,
|
||||
`http://testapi.${domain.hostname}`,
|
||||
]);
|
||||
|
||||
const allowedHosts = [...new Set([...baseHosts, ...extraHosts])];
|
||||
console.log('baseOrigins:', baseOrigins.map((origin) => `'${origin}'`).join(', '));
|
||||
|
||||
// 2️⃣ Funzione di validazione origin (accetta qualsiasi porta)
|
||||
const originValidator = (origin, callback) => {
|
||||
if (!origin) return callback(null, true); // Postman, curl, ecc.
|
||||
const allowedExtra = domainsAllowed.flatMap((domain) => [`https://${domain}`, `http://${domain}`]);
|
||||
|
||||
try {
|
||||
const url = new URL(origin);
|
||||
const host = url.hostname.toLowerCase();
|
||||
return [...baseOrigins, ...allowedExtra];
|
||||
}
|
||||
|
||||
if (allowedHosts.includes(host)) {
|
||||
// if (!isProduction) console.log(`✅ [CORS OK] ${origin}`);
|
||||
return callback(null, true);
|
||||
}
|
||||
function createCorsOptions(domains, domainsAllowed, isProduction, noCors = false) {
|
||||
if (noCors) {
|
||||
console.log('NOCORS mode enabled');
|
||||
return {
|
||||
exposedHeaders: ['x-auth', 'x-refrtok'],
|
||||
};
|
||||
}
|
||||
|
||||
if (!isProduction) {
|
||||
console.warn(`⚠️ [CORS DEV] origin non ammessa: ${origin} (host: ${host})`);
|
||||
return callback(null, true); // in dev permetti tutto
|
||||
}
|
||||
const allowedOrigins = buildAllowedOrigins(domains, domainsAllowed, isProduction);
|
||||
|
||||
console.error(`❌ [CORS BLOCKED] ${origin}`);
|
||||
return callback(new Error(`CORS denied for origin ${origin}`), false);
|
||||
} catch (err) {
|
||||
console.error(`❌ [CORS ERROR] parsing origin: ${origin} -> ${err.message}`);
|
||||
return callback(new Error('CORS denied: invalid origin'), false);
|
||||
let originValidator = (origin, callback) => {
|
||||
if (!origin) {
|
||||
// console.log('✅ Origin undefined or empty — allowing');
|
||||
return callback(null, true);
|
||||
}
|
||||
|
||||
if (typeof origin !== 'string' || !/^https?:\/\/[^\s/$.?#].[^\s]*$/.test(origin)) {
|
||||
console.error('❌ Invalid origin:', origin);
|
||||
return callback(new Error('Origine non valida'), false);
|
||||
}
|
||||
|
||||
if (allowedOrigins.includes(origin)) {
|
||||
return callback(null, true);
|
||||
}
|
||||
|
||||
console.warn('❌ Origin blocked:', origin);
|
||||
return callback(new Error('CORS non permesso per questa origine'), false);
|
||||
};
|
||||
|
||||
// 3️⃣ Restituisce l’oggetto completo per il middleware cors()
|
||||
if (app.get('env') === 'development') {
|
||||
originValidator = (_origin, callback) => callback(null, true);
|
||||
}
|
||||
|
||||
return {
|
||||
origin: originValidator,
|
||||
credentials: true,
|
||||
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
|
||||
allowedHeaders: ['Origin', 'X-Requested-With', 'Content-Type', 'Accept', 'Authorization', 'x-auth', 'x-refrtok'],
|
||||
exposedHeaders: ['x-auth', 'x-refrtok'],
|
||||
maxAge: 86400, // 24 ore di caching per la preflight response
|
||||
maxAge: 86400,
|
||||
preflightContinue: false,
|
||||
optionsSuccessStatus: 204,
|
||||
};
|
||||
|
||||
@@ -26,9 +26,14 @@ async function startServer(app, port) {
|
||||
setupExpress(app, corsOptions);
|
||||
setupRouters(app);
|
||||
setupMailchimpRoutes(app);
|
||||
|
||||
console.log('DOMAINS:', domains)
|
||||
console.log(domains.map(({ hostname, port }) => `${hostname}:${port}`).join(', '));
|
||||
console.table(domains);
|
||||
|
||||
// 👇 logica migliorata per gestire HTTPS anche in dev
|
||||
if (isProduction) {
|
||||
server = await createHttpsServers(domains, app);
|
||||
await createHttpsServers(domains, app);
|
||||
} else if (process.env.HTTPS_LOCALHOST === 'true') {
|
||||
server = await createHttpsLocalServer(app, port);
|
||||
} else {
|
||||
@@ -42,11 +47,14 @@ async function startServer(app, port) {
|
||||
}
|
||||
|
||||
async function createHttpsServers(domains, app) {
|
||||
console.log('NUMERO DOMINI:', domains.length);
|
||||
for (const d of domains) {
|
||||
console.log('. DOMINIO: ', d.hostname + ' ...');
|
||||
const credentials = await getCredentials(d.hostname);
|
||||
const server = https.createServer(credentials, app);
|
||||
server.listen(d.port, () => console.log(`⭐️ HTTPS ${d.hostname}:${d.port}`));
|
||||
return server;
|
||||
server.listen(d.port, () => {
|
||||
console.log(`⭐️ HTTPS ${d.hostname} server running on port ${d.port}`)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -819,6 +819,8 @@ connectToDatabase(connectionUrl, options)
|
||||
`http://testapi.${domain.hostname}`,
|
||||
]);
|
||||
|
||||
console.log('baseOrigins:', baseOrigins.map(origin => `'${origin}'`).join(', '));
|
||||
|
||||
const allowedExtra = domainsAllowed.flatMap((domain) => [`https://${domain}`, `http://${domain}`]);
|
||||
|
||||
return [...baseOrigins, ...allowedExtra];
|
||||
@@ -1059,6 +1061,7 @@ connectToDatabase(connectionUrl, options)
|
||||
|
||||
const { domains, domainsAllowed } = parseDomains();
|
||||
|
||||
|
||||
console.log('domains:', domains);
|
||||
console.log('isProduction:', isProduction);
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ const axios = require('axios');
|
||||
|
||||
const CryptoJS = require('crypto-js');
|
||||
const Url = require('url-parse');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const { ObjectId } = require('mongodb');
|
||||
|
||||
@@ -6301,6 +6302,11 @@ module.exports = {
|
||||
return null;
|
||||
},
|
||||
|
||||
getTokenRandom() {
|
||||
return crypto.randomBytes(32).toString('hex');
|
||||
|
||||
},
|
||||
|
||||
async ensureDir(fullnamepath) {
|
||||
const dir = path.dirname(fullnamepath);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user