- risolto problema cors ?!?

- notifiche transazioni pendenti OK
This commit is contained in:
Surya Paolo
2024-10-29 02:33:29 +01:00
parent 5dac17d1d1
commit fa1a2a7cdb
15 changed files with 329 additions and 120 deletions

View File

@@ -61,7 +61,7 @@ let credentials = null;
if ((process.env.NODE_ENV === 'production')) {
console.log('*** AMBIENTE DI PRODUZIONE (Aprile 2024) !!!!')
console.log('*** AMBIENTE DI PRODUZIONE !!!!')
} else if (process.env.NODE_ENV === 'test') {
console.log('*** ### AMBIENTE DI TEST ')
}
@@ -175,9 +175,6 @@ myLoad().then(ris => {
// res.sendFile(path.join(__dirname, 'service-worker.js')); // Modifica il percorso secondo la tua struttura
});*/
app.use(cors({
exposedHeaders: ['x-auth', 'x-refrtok'],
}));
app.use(bodyParser.json());
@@ -187,39 +184,6 @@ myLoad().then(ris => {
console.log('Use Routes \...');
// Use Routes
app.use('/', index_router);
app.use('/subscribe', subscribe_router);
app.use('/sendmsg', sendmsg_router);
app.use('/sendnotif', sendnotif_router);
app.use('/push', push_router);
app.use('/news', newsletter_router);
app.use('/booking', booking_router);
app.use('/dashboard', dashboard_router);
app.use('/event', myevent_router);
app.use('/email', email_router);
app.use('/todos', todos_router);
app.use('/test', test_router);
app.use('/projects', projects_router);
app.use('/users', users_router);
app.use('/reactions', reactions_router);
app.use('/mygroup', mygroups_router);
app.use('/circuit', circuits_router);
app.use('/account', accounts_router);
app.use('/iscritti_conacreis', iscrittiConacreis_router);
app.use('/iscritti_arcadei', iscrittiArcadei_router);
app.use('/report', report_router);
app.use('/site', site_router);
app.use('/admin', admin_router);
app.use('/products', products_router);
app.use('/cart', cart_router);
app.use('/orders', orders_router);
app.use('/city', city_router);
app.use('/myskills', myskills_router);
app.use('/mygoods', mygoods_router);
app.use('/mygen', mygen_router);
app.use('/aitools', aitools_router);
// catch 404 and forward to error handler
// app.use(function (req, res, next) {
// var err = new Error('Not Found');
@@ -265,6 +229,40 @@ myLoad().then(ris => {
}
startServer(app, process.env.PORT);
// Use Routes
app.use('/', index_router);
app.use('/subscribe', subscribe_router);
app.use('/sendmsg', sendmsg_router);
app.use('/sendnotif', sendnotif_router);
app.use('/push', push_router);
app.use('/news', newsletter_router);
app.use('/booking', booking_router);
app.use('/dashboard', dashboard_router);
app.use('/event', myevent_router);
app.use('/email', email_router);
app.use('/todos', todos_router);
app.use('/test', test_router);
app.use('/projects', projects_router);
app.use('/users', users_router);
app.use('/reactions', reactions_router);
app.use('/mygroup', mygroups_router);
app.use('/circuit', circuits_router);
app.use('/account', accounts_router);
app.use('/iscritti_conacreis', iscrittiConacreis_router);
app.use('/iscritti_arcadei', iscrittiArcadei_router);
app.use('/report', report_router);
app.use('/site', site_router);
app.use('/admin', admin_router);
app.use('/products', products_router);
app.use('/cart', cart_router);
app.use('/orders', orders_router);
app.use('/city', city_router);
app.use('/myskills', myskills_router);
app.use('/mygoods', mygoods_router);
app.use('/mygen', mygen_router);
app.use('/aitools', aitools_router);
mystart();
});
@@ -272,15 +270,6 @@ myLoad().then(ris => {
// app.use(throttle(1024 * 128)); // throttling bandwidth
/*
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*')
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
*/
async function myLoad() {
return tools.loadApps();
@@ -366,8 +355,8 @@ async function mycron() {
const arr = await tools.getApps();
for (const app of arr) {
sendemail.checkifPendingNewsletter(app.idapp);
sendemail.checkifSentNewsletter(app.idapp);
await sendemail.checkifPendingNewsletter(app.idapp);
await sendemail.checkifSentNewsletter(app.idapp);
}
} catch (e) {
@@ -812,51 +801,140 @@ function startServer(app, port) {
console.log('isProduction', isProduction);
/*
const CORS_ENABLE_FOR_ALL_SITES = true;
const NOCORS = false;
const CORS_ENABLE_FOR_ALL_SITES = false;
const ISDEBUG = true;
let corsOptions = {};
if (CORS_ENABLE_FOR_ALL_SITES) {
if (NOCORS) {
corsOptions = {
exposedHeaders: ['x-auth', 'x-refrtok'], // Intestazioni da esporre al client
};
} else {
let myhosts = [];
for (let i = 0; i < domains.length; i++) {
myhosts.push('https://' + domains[i].hostname);
myhosts.push('https://' + 'api.' + domains[i].hostname);
myhosts.push('https://' + 'test.' + domains[i].hostname);
myhosts.push('https://' + 'testapi.' + domains[i].hostname);
}
console.log('myhosts', myhosts);
console.log('CORS');
corsOptions = {
origin: (origin, callback) => {
if (myhosts.indexOf(origin) !== -1 || !origin) {
// Configurazione CORS dettagliata
const corsOptions = {
origin: '*',
/*origin: function (origin, callback) {
// Array di domini consentiti
const allowedOrigins = [
'https://comunitanuovomondo.app',
'https://kolibrilab.it',
'https://riso.app',
'https://api.riso.app',
'https://test.riso.app',
'https://testapi.riso.app',
'http://localhost:8080', // per sviluppo locale
'http://localhost:3000',
'http://localhost:8084',
];
// Permetti richieste senza origin (es. mobile apps)
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
callback(new Error('❌ CORS non permesso per questa origine'));
}
},
},*/
credentials: false,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'x-auth', 'x-refrtok'], // Intestazioni consentite
exposedHeaders: ['x-auth', 'x-refrtok'], // Intestazioni da esporre al client
credentials: true, // Consenti l'invio di cookie
allowedHeaders: [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Authorization',
'x-auth',
'x-refrtok'
],
exposedHeaders: ['x-auth', 'x-refrtok'],
maxAge: 86400, // Preflight cache 24 ore
preflightContinue: false,
optionsSuccessStatus: 204,
optionsSuccessStatus: 204
};
app.use(cors(corsOptions));
// Applica CORS come primo middleware
app.use(cors(corsOptions));
}*/
app.use(express.json()); // Middleware per il parsing del corpo JSON
// Gestione specifica delle richieste OPTIONS
app.options('*', function (req, res) {
const origin = req.headers.origin;
if (corsOptions.origin === '*' ||
(typeof corsOptions.origin === 'function' &&
corsOptions.origin.toString().includes(origin))) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization, x-auth, x-refrtok');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Expose-Headers', 'x-auth, x-refrtok');
res.setHeader('Access-Control-Max-Age', '86400');
res.status(204).end();
} else {
res.status(403).end();
}
});
// Middleware per assicurarsi che gli headers CORS siano sempre presenti
app.use((req, res, next) => {
const origin = req.headers.origin;
if (corsOptions.origin === '*' ||
(typeof corsOptions.origin === 'function' &&
corsOptions.origin.toString().includes(origin))) {
//console.log('Access-Control-Allow-Origin')
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Expose-Headers', 'x-auth, x-refrtok');
}
next();
});
// Log middleware per debug
app.use((req, res, next) => {
if (ISDEBUG) {
console.log(`${new Date().toISOString()} - ${req.method} ${req.url}`);
console.log('Request Headers:', req.headers);
}
// Intercetta la risposta per loggare gli headers
const oldSend = res.send;
res.send = function (...args) {
if (ISDEBUG) {
console.log('Response Headers:', res.getHeaders());
}
return oldSend.apply(res, args);
};
next();
});
// Gestione errori CORS
app.use((err, req, res, next) => {
if (err.message === 'CORS non permesso per questa origine') {
console.error('❌ Errore CORS:', {
origin: req.headers.origin,
method: req.method,
path: req.path
});
res.status(403).json({
error: '❌ CORS non permesso per questa origine (' + req.headers.origin + ')',
origin: req.headers.origin
});
} else {
next(err);
}
});
}