Files
freeplanet_serverside/src/server/server.js

1060 lines
35 KiB
JavaScript
Raw Normal View History

2018-12-24 20:31:02 +01:00
require('./config/config');
2021-06-04 10:07:57 +02:00
// console.log(" lodash");
console.log('VERSIONE NODE.JS :', process.versions.node);
if (process.env.AUTH_MONGODB === undefined) {
console.error("AUTH_MONGODB non presente. VARIABILI D'AMBIENTE NON SETTATI!");
process.exit(1);
}
2018-12-24 20:31:02 +01:00
const _ = require('lodash');
2021-06-04 10:07:57 +02:00
// console.log(" cors");
2018-12-24 20:31:02 +01:00
const cors = require('cors');
2018-12-27 20:09:40 +01:00
2021-06-04 10:07:57 +02:00
// console.log(" 2) fs");
const fs = require('fs');
var https = require('https');
var http = require('http');
const WebSocket = require('ws');
const { spawn } = require('child_process');
2023-02-20 02:19:53 +01:00
const NUOVO_METODO_TEST = true;
const METODO_MULTI_CORS = true;
const server_constants = require('./tools/server_constants');
//const throttle = require('express-throttle-bandwidth');
2022-01-23 23:25:34 +01:00
// app.use(throttle(1024 * 128)) // throttling bandwidth
2018-12-27 20:09:40 +01:00
// var cookieParser = require('cookie-parser')
// var csrf = require('csurf')
2019-02-05 03:40:22 +01:00
const express = require('express');
const vhost = require('vhost');
2019-02-05 03:40:22 +01:00
const bodyParser = require('body-parser');
const path = require('path');
const cron = require('node-cron');
2023-02-15 21:40:19 +01:00
console.log('Starting mongoose...');
2023-02-15 21:40:19 +01:00
// console.log('Starting pem...');
// const pem = require('pem')
const { Settings } = require('./models/settings');
const Site = require('./models/site');
2022-11-10 19:33:23 +01:00
// test
const i18n = require('i18n');
const readline = require('readline');
2023-02-20 02:19:53 +01:00
let credentials = null;
console.log('DB: ' + process.env.DATABASE);
2021-06-04 10:07:57 +02:00
// console.log("PORT: " + port);
// console.log("MONGODB_URI: " + process.env.MONGODB_URI);
2018-12-24 20:31:02 +01:00
var app = express();
2021-12-29 18:26:08 +01:00
let telegrambot = null;
const tools = require('./tools/general');
const shared_consts = require('./tools/shared_nodejs');
2025-03-04 20:20:26 +01:00
const { connectToDatabase, connectionUrl, options } = require('./db/mongoose');
// Avvia la connessione
connectToDatabase(connectionUrl, options)
.then(() => {
console.log('------------------------------------------------------------------');
console.log('--------------- CONNESSIONE AL DB EFFETTUATA ! -----------------');
console.log('------------------------------------------------------------------');
2025-03-04 20:20:26 +01:00
const { CfgServer } = require('./models/cfgserver');
const { ObjectId } = require('mongodb');
const populate = require('./populate/populate');
const { Circuit } = require('./models/circuit');
const printf = require('util').format;
myLoad().then((ris) => {
2025-03-04 20:20:26 +01:00
const { User } = require('./models/user');
require('./models/todo');
require('./models/project');
require('./models/subscribers');
require('./models/booking');
require('./models/sendmsg');
require('./models/sendnotif');
require('./models/mailinglist');
require('./models/newstosent');
require('./models/mypage');
require('./models/myelem');
require('./models/myscheda');
require('./models/bot');
require('./models/calzoom');
const mysql_func = require('./mysql/mysql_func');
const index_router = require('./router/index_router');
const push_router = require('./router/push_router');
const newsletter_router = require('./router/newsletter_router');
const booking_router = require('./router/booking_router');
const dashboard_router = require('./router/dashboard_router');
const myevent_router = require('./router/myevent_router');
const subscribe_router = require('./router/subscribe_router');
const sendmsg_router = require('./router/sendmsg_router');
const sendnotif_router = require('./router/sendnotif_router');
const email_router = require('./router/email_router');
const todos_router = require('./router/todos_router');
const test_router = require('./router/test_router');
const projects_router = require('./router/projects_router');
const report_router = require('./router/report_router');
const users_router = require('./router/users_router');
const reactions_router = require('./router/reactions_router');
const mygroups_router = require('./router/mygroups_router');
const circuits_router = require('./router/circuits_router');
const accounts_router = require('./router/accounts_router');
const iscrittiConacreis_router = require('./router/iscrittiConacreis_router');
const iscrittiArcadei_router = require('./router/iscrittiArcadei_router');
const site_router = require('./router/site_router');
const admin_router = require('./router/admin_router');
const products_router = require('./router/products_router');
const cart_router = require('./router/cart_router');
const orders_router = require('./router/orders_router');
const city_router = require('./router/city_router');
const myskills_router = require('./router/myskills_router');
const mygoods_router = require('./router/mygoods_router');
const mygen_router = require('./router/mygen_router');
const aitools_router = require('./router/aitools_router');
const article_router = require('./router/articleRoutes');
const { MyEvent } = require('./models/myevent');
app.use(bodyParser.json({ limit: '50mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(express.static('views'));
app.use(express.json({ limit: '100mb' }));
app.use(express.urlencoded({ extended: true, limit: '100mb' }));
2025-03-04 20:20:26 +01:00
// app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
// app.set('view engine', 'pug');
// Set static folder
// app.use(express.static(path.join(__dirname, 'public')));
i18n.configure({
locales: ['it', 'enUs', 'es', 'fr', 'pt', 'si'],
defaultLocale: 'it',
// cookie: 'cook',
directory: __dirname + '/locales',
api: {
__: 'translate',
__n: 'translateN',
2025-03-04 20:20:26 +01:00
},
});
2018-12-24 20:31:02 +01:00
2025-03-04 20:20:26 +01:00
// Serve il tuo service worker da una certa directory
/*app.get('/service-worker.js', (req, res) => {
res.set('Cache-Control', 'no-cache'); // Aggiunge l'intestazione
// res.sendFile(path.join(__dirname, 'service-worker.js')); // Modifica il percorso secondo la tua struttura
});*/
2018-12-24 20:31:02 +01:00
2025-03-04 20:20:26 +01:00
app.use(bodyParser.json());
2023-02-15 21:40:19 +01:00
2025-03-04 20:20:26 +01:00
// app.use(express.cookieParser());
app.use(i18n.init);
2018-12-24 20:31:02 +01:00
console.log('Use Routes ...');
2025-03-04 20:20:26 +01:00
// catch 404 and forward to error handler
// app.use(function (req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
2020-01-03 22:02:18 +01:00
2025-03-04 20:20:26 +01:00
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug');
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
console.log('Server Error: ', err.message);
// console.trace();
res.status(err.status || 500).send({ error: err.message });
// res.render('error', {
// message: err.message,
// error: err
// });
});
}
2025-03-04 20:20:26 +01:00
if (process.env.NODE_ENV === 'production') {
console.log('*** PRODUCTION! ');
}
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'test') {
2025-03-04 20:20:26 +01:00
}
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);
app.use('/apisqlsrv', article_router);
mystart();
});
2025-03-04 20:20:26 +01:00
// app.use(throttle(1024 * 128)); // throttling bandwidth
2021-03-17 02:24:11 +01:00
2025-03-04 20:20:26 +01:00
async function myLoad() {
return tools.loadApps();
}
2020-04-24 10:29:25 +02:00
2025-03-04 20:20:26 +01:00
async function mystart() {
// await estraiTutteLeImmagini();
console.log('Versione Server: ' + (await tools.getVersServer()));
2025-03-04 20:20:26 +01:00
await tools.getApps();
2025-03-04 20:20:26 +01:00
if (process.env.PROD !== 1) {
testmsgwebpush();
2025-03-04 20:20:26 +01:00
// tools.sendNotifToAdmin('Riparti', 'Riparti');
2022-01-23 23:25:34 +01:00
2025-03-04 20:20:26 +01:00
let miapass = '';
2021-12-29 18:26:08 +01:00
2025-03-04 20:20:26 +01:00
if (miapass !== '') {
let crypt = tools.cryptdata(miapass);
let decrypt = tools.decryptdata(crypt);
2025-03-04 20:20:26 +01:00
console.log('crypted:', crypt);
console.log('decrypted:', decrypt);
}
2025-03-04 20:20:26 +01:00
mycron();
}
2025-03-04 20:20:26 +01:00
telegrambot = require('./telegram/telegrambot');
2025-03-04 20:20:26 +01:00
await inizia();
2025-03-04 20:20:26 +01:00
await resetProcessingJob();
2025-03-04 20:20:26 +01:00
populate.popolaTabelleNuove();
2025-03-04 20:20:26 +01:00
faitest();
2025-03-04 20:20:26 +01:00
// ----------------- MAILCHIMP -----
const querystring = require('querystring');
const mailchimpClientId = 'xxxxxxxxxxxxxxxx';
app.get('/mailchimp/auth/authorize', function (req, res) {
res.redirect(
'https://login.mailchimp.com/oauth2/authorize?' +
querystring.stringify({
response_type: 'code',
client_id: mailchimpClientId,
redirect_uri: 'http://127.0.0.1:3000/mailchimp/auth/callback',
})
);
2025-03-04 20:20:26 +01:00
});
}
2025-03-04 20:20:26 +01:00
// -----------------
2025-03-04 20:20:26 +01:00
function populateDBadmin() {
const cfgserv = [
{
_id: new ObjectId(),
idapp: '9',
chiave: 'vers',
userId: 'ALL',
valore: '0.1.2',
},
];
2025-03-04 20:20:26 +01:00
let cfg = new CfgServer(cfgserv[0]).save();
}
2025-03-04 20:20:26 +01:00
async function mycron() {
try {
const sendemail = require('./sendemail');
const { Cron } = require('./models/cron');
const arr = await tools.getApps();
2025-03-04 20:20:26 +01:00
for (const app of arr) {
await sendemail.checkifPendingNewsletter(app.idapp);
await sendemail.checkifSentNewsletter(app.idapp);
await Cron.startJobCron(app.idapp);
2025-03-04 20:20:26 +01:00
}
} catch (e) {
console.error('Err mycron', e);
}
}
2025-03-04 20:20:26 +01:00
async function mycron_30min() {
for (const app of await tools.getApps()) {
let enablecrontab = false;
enablecrontab = await Settings.getValDbSettings(app.idapp, tools.ENABLE_CRONTAB, false);
2025-03-04 20:20:26 +01:00
if (enablecrontab) {
// ...
}
}
}
2025-03-04 20:20:26 +01:00
async function mycron_everyday() {
try {
const { User } = require('./models/user');
2025-03-04 20:20:26 +01:00
const arrapps = await tools.getApps();
for (const app of arrapps) {
// Azzera le richieste di password:
const usersblocked = await User.find({ idapp: app.idapp, retry_pwd: { $exists: true, $gte: 29 } }).lean();
for (const user of usersblocked) {
await User.findOneAndUpdate({ _id: user._id }, { $set: { retry_pwd: 20 } });
let text = `⚠️⚠️⚠️ L\'utente ${user.username} (${user.name} ${user.surname}) viene sbloccato dal numero massimo di tentativi di richiesta password!\nTelerlo d\'occhio !\n@${user.profile.username_telegram}`;
await telegrambot.sendMsgTelegramToTheAdminAllSites(text, false);
}
}
} catch (e) {
console.error('mycron_everyday: ', e);
}
}
2025-03-04 20:20:26 +01:00
function testmsgwebpush() {
const { User } = require('./models/user');
2025-03-04 20:20:26 +01:00
// console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1));
// console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2));
2025-03-04 20:20:26 +01:00
User.find({ username: 'paoloar77', idapp: '1' }).then(async (arrusers) => {
if (arrusers !== null) {
for (const user of arrusers) {
await tools
.sendNotificationToUser(user._id, 'Server', 'Il Server è Ripartito', '/', '', 'server', [])
.then((ris) => {
2025-03-04 20:20:26 +01:00
if (ris) {
} else {
// already sent the error on calling sendNotificationToUser
}
});
}
}
2023-02-15 21:40:19 +01:00
});
2025-03-04 20:20:26 +01:00
}
2018-12-27 20:09:40 +01:00
// Esecuzione ogni 1 minuto (*/1 * * * *)
// La sintassi di cron è:
// 0 12 * * * comando
// che significa: esegui il comando ogni giorno alle 12:00
// La sintassi di node-cron è:
// cron.schedule('0 12 * * *', () => {
// che significa: esegui il comando ogni giorno alle 12:00
// La sintassi di node-cron con */1 esegue il comando ogni 1 minuto
2025-03-04 20:20:26 +01:00
cron.schedule('*/1 * * * *', () => {
// console.log('Running Cron Job');
// if (!process.env.VITE_DEBUG) {
mycron();
// }
});
// Cron every 1 HOUR
2025-03-04 20:20:26 +01:00
cron.schedule('*/60 * * * *', async () => {
if (!process.env.VITE_DEBUG) {
mycron_30min();
}
});
2025-03-04 20:20:26 +01:00
// Cron every 21:00 (1 volta al giorno)
cron.schedule('0 21 * * *', async () => {
mycron_everyday();
});
// mycron_30min();
2025-03-04 20:20:26 +01:00
// tools.writelogfile('test', 'prova.txt');
2020-01-03 22:02:18 +01:00
2025-03-04 20:20:26 +01:00
async function resetProcessingJob() {
const { Newstosent } = require('./models/newstosent');
2022-03-12 21:38:19 +01:00
2025-03-04 20:20:26 +01:00
arrrec = await Newstosent.find({});
2022-03-12 21:38:19 +01:00
2025-03-04 20:20:26 +01:00
for (const rec of arrrec) {
rec.processing_job = false;
await Newstosent.findOneAndUpdate({ _id: rec.id }, { $set: rec }, { new: false }).then((item) => {});
2025-03-04 20:20:26 +01:00
}
2022-03-12 21:38:19 +01:00
}
2022-11-06 13:39:01 +01:00
2025-03-04 20:20:26 +01:00
//app.listen(port, () => {
// console.log(`Server started at port ${port}`);
//});
2025-03-04 20:20:26 +01:00
async function inizia() {
try {
if (true) {
const url = 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json';
const outputPath = './comuni_italia_geojson.json';
downloadGeoJSON(url, outputPath);
}
2024-07-03 14:21:02 +02:00
2025-03-04 20:20:26 +01:00
mycron_everyday();
2022-11-10 19:33:23 +01:00
2025-03-04 20:20:26 +01:00
if (process.env.NODE_ENV === 'development') {
await telegrambot.sendMsgTelegram(
tools.FREEPLANET,
2025-03-04 20:20:26 +01:00
shared_consts.ADMIN_USER_SERVER,
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}!`
);
2023-02-20 02:19:53 +01:00
await telegrambot.sendMsgTelegramByIdTelegram(
tools.FREEPLANET,
2025-03-04 20:20:26 +01:00
telegrambot.ADMIN_IDTELEGRAM_SERVER,
`Ciao ${telegrambot.ADMIN_USER_NAME_SERVER}\n` + `🔅 Il Server ${process.env.DATABASE} è appena ripartito!`
);
2025-03-04 20:20:26 +01:00
} else {
await telegrambot.sendMsgTelegramToTheAdminAllSites(
`Ciao Admin\n` + `🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito!`,
false
);
2025-03-04 20:20:26 +01:00
}
2025-03-04 20:20:26 +01:00
await Site.createFirstUserAdmin();
2025-03-04 20:20:26 +01:00
/*const {Circuit} = require('./models/circuit');
await Circuit.setDeperimentoOff();
*/
} catch (e) {}
2025-03-04 20:20:26 +01:00
}
2025-03-04 20:20:26 +01:00
//
2025-03-04 20:20:26 +01:00
// telegrambot.sendMsgTelegramToTheManagers('7', 'PROVAAA!');
2025-03-04 20:20:26 +01:00
// if (process.env.PROD !== 1) {
// const reg = require('./reg/registration');
// const link = reg.getlinkregByEmail('7', 'tomasihelen@dasdasgmail.comAAAA' , 'HelenTomasidasdasd');
// const link2 = reg.getlinkregByEmail('7', 'tomasihelen@gmail.com' , 'HelenTomasi');
// //const link2 = reg.getlinkregByEmail('7', 'elenaliubicich@gmail.com' , 'Elenaliu');
//
// console.log(link);
// console.log(link2);
// }
2025-03-04 20:20:26 +01:00
async function estraiImmagini(table) {
const { User } = require('./models/user');
2025-03-04 20:20:26 +01:00
let idapp = '13';
2025-03-04 20:20:26 +01:00
let arrlist;
2025-03-04 20:20:26 +01:00
const globalTables = require('./tools/globalTables');
2025-03-04 20:20:26 +01:00
const mytable = globalTables.getTableByTableName(table);
if (!mytable) return;
2025-03-04 20:20:26 +01:00
console.log('INIZIO - estraiImmagini', table);
2025-03-04 20:20:26 +01:00
arrlist = await mytable.find({ idapp }).lean();
2025-03-04 20:20:26 +01:00
let file = '';
let filetocheck = '';
let dirmain = '';
let filefrom = '';
let filefrom2 = '';
2025-03-04 20:20:26 +01:00
try {
if (!tools.sulServer()) {
dirmain = server_constants.DIR_PUBLIC_LOCALE;
2025-03-04 20:20:26 +01:00
}
2025-05-11 21:59:25 +02:00
let dir = tools.getdirByIdApp(idapp) + dirmain + '/upload/';
2025-03-04 20:20:26 +01:00
for (const rec of arrlist) {
const myuser = await User.findOne({ idapp, _id: rec.userId }).lean();
if (myuser) {
const myphotos = rec.photos;
if (myphotos.length > 0) {
let folderprof = dir + 'profile/' + myuser.username;
try {
// console.log('checkdir', folderprof);
if (!fs.existsSync(folderprof)) {
console.log('*** Creadir', folderprof);
fs.mkdirSync(folderprof);
}
folderprof = dir + 'profile/' + myuser.username + '/' + table;
// console.log('checkdir', folderprof);
if (!fs.existsSync(folderprof)) {
console.log('creadir', folderprof);
fs.mkdirSync(folderprof);
}
} catch (e) {}
}
2025-03-04 20:20:26 +01:00
for (const photo of myphotos) {
if (photo.imagefile) {
file = dir + 'profile/' + myuser.username + '/' + table + '/' + photo.imagefile;
2025-03-04 20:20:26 +01:00
filefrom = dir + 'profile/undefined/' + table + '/' + photo.imagefile;
filefrom2 = dir + 'profile/' + myuser.username + '/' + photo.imagefile;
// console.log('file', file);
// console.log('filefrom', filefrom);
if (!tools.isFileExists(file)) {
// non esiste
console.log('non esiste', file);
console.log(' filefrom', filefrom);
console.log(' filefrom2', filefrom2);
}
if (!tools.isFileExists(file) && tools.isFileExists(filefrom)) {
console.log('@@@@@@ copia file:', filefrom, 'a', file);
tools.copy(filefrom, file);
}
if (!tools.isFileExists(file) && tools.isFileExists(filefrom2)) {
console.log('@@@@@@ copia file 2:', filefrom2, 'a', file);
tools.copy(filefrom2, file);
}
}
}
}
}
2025-03-04 20:20:26 +01:00
console.log('FINE - estraiImmagini', table);
} catch (e) {
console.error('e', e);
}
}
2025-03-04 20:20:26 +01:00
async function estraiTutteLeImmagini() {
await estraiImmagini('myskills');
await estraiImmagini('mygoods');
await estraiImmagini('mybachecas');
}
2025-03-04 20:20:26 +01:00
async function faitest() {
// console.log('Fai Test:')
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
const testfind = false;
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
// const $vers = tools.getVersionint('1.92.45');
2021-10-28 00:38:10 +02:00
2025-03-04 20:20:26 +01:00
if (true) {
// tools.execScript("ls -la");
}
2022-03-12 21:38:19 +01:00
2025-03-04 20:20:26 +01:00
if (false) {
prova = tools.removeAtChar('@prova');
}
2025-03-04 20:20:26 +01:00
if (false) {
const prova = tools.getConfSiteOptionEnabledByIdApp('13', shared_consts.ConfSite.Notif_Reg_Push_Admin);
console.log('prova', prova);
}
2025-03-04 20:20:26 +01:00
if (testfind) {
const { City } = require('./models/city');
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
let miacity = 'roma';
const ris = await City.findByCity(miacity);
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
console.log('ris', ris);
}
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
const { User } = require('./models/user');
2025-03-04 20:20:26 +01:00
if (false) {
let myuser = await User.findOne({
idapp: '1',
username: 'paoloar77',
});
const langdest = 'it';
2025-03-04 20:20:26 +01:00
telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);
}
2025-03-04 20:20:26 +01:00
if (false) {
const user = await User.findOne({
idapp: 12,
username: 'paolotest1',
});
await sendemail.sendEmail_Registration('it', 'paolo@arcodiluce.it', user, '12', '');
2025-03-04 20:20:26 +01:00
}
2025-03-04 20:20:26 +01:00
if (false) {
const { User } = require('./models/user');
2021-12-29 18:26:08 +01:00
2025-03-04 20:20:26 +01:00
const idapp = tools.FREEPLANET;
const idreg = 0;
2021-12-29 18:26:08 +01:00
2025-03-04 20:20:26 +01:00
try {
const user = await User.findOne({
idapp,
username: 'paoloar773',
});
2021-12-29 18:26:08 +01:00
2025-03-04 20:20:26 +01:00
user.aportador_solidario = 'paoloar77';
let mylocalsconf = {
idapp,
dataemail: null,
locale: user.lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
strlinksito: tools.getHostByIdApp(idapp),
strlinkreg: '',
username: user.username,
name: user.name,
surname: user.surname,
forgetpwd: tools.getHostByIdApp(idapp) + '/requestresetpwd',
emailto: '',
user,
};
2021-10-08 00:38:35 +02:00
await telegrambot.notifyToTelegram(telegrambot.phase.REGISTRATION, mylocalsconf);
2025-03-04 20:20:26 +01:00
} catch (e) {
console.log('error ' + e);
}
}
}
2025-03-04 20:20:26 +01:00
function getCredentials(hostname) {
if (NUOVO_METODO_TEST) {
if (METODO_MULTI_CORS) {
const fileprivkey = `/etc/letsencrypt/live/${hostname}/` + process.env.PATH_CERT_KEY;
const filecert = `/etc/letsencrypt/live/${hostname}/` + process.env.PATH_SERVER_CRT;
console.log('fileprivkey: ', fileprivkey, ' filecert: ', filecert);
/* return {
SNICallback: function (hostname, callback) {
console.log('hostname: ', hostname);
if (domains.includes(hostname)) {
const fileprivkey = `/etc/letsencrypt/live/${hostname}/privkey.pem`;
const filecert = `/etc/letsencrypt/live/${hostname}/fullchain.pem`;
// console.log('fileprivkey: ', fileprivkey, ' filecert: ', filecert);
const domainCert = {
key: fs.readFileSync(fileprivkey, "utf8"),
cert: fs.readFileSync(filecert, "utf8"),
};
callback(null, domainCert);
} else {
callback(null, { key: privateKey, cert: certificate });
}
}
};*/
2025-03-04 20:20:26 +01:00
try {
const key = fs.readFileSync(fileprivkey, 'utf8');
const cert = fs.readFileSync(filecert, 'utf8');
2025-03-04 20:20:26 +01:00
return { key, cert };
} catch (error) {
console.error(`Errore nel caricamento delle credenziali per ${hostname}:`, error);
// Gestisci l'errore, per esempio ritorna null o lancia un'eccezione
}
} else {
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
const privateKey = fs.readFileSync(keyStream, 'utf8');
const certificate = fs.readFileSync(certificateStream, 'utf8');
2025-03-04 20:20:26 +01:00
return { key: privateKey, cert: certificate };
}
}
2025-03-04 20:20:26 +01:00
// Caso di default non specificato, potrebbe essere necessario aggiungere una gestione degli errori qui
}
2025-03-04 20:20:26 +01:00
function startServer(app, port) {
try {
const isProduction = ['production', 'test'].includes(process.env.NODE_ENV);
2025-03-04 20:20:26 +01:00
let domains = [];
2025-03-26 23:23:48 +01:00
let domains_allowed = [];
2025-03-04 20:20:26 +01:00
try {
if (process.env.DOMAINS) domains = JSON.parse(process.env.DOMAINS);
if (process.env.DOMAINS_ALLOWED) domains_allowed = JSON.parse(process.env.DOMAINS_ALLOWED);
2025-03-04 20:20:26 +01:00
} catch (error) {
console.error('Errore durante la conversione della stringa DOMAINS:', error);
2025-03-04 20:20:26 +01:00
}
2025-03-04 20:20:26 +01:00
console.log('domains', domains);
2025-03-04 20:20:26 +01:00
let httpsServer = null;
let httpServer = null;
2025-03-04 20:20:26 +01:00
console.log('isProduction', isProduction);
2025-03-04 20:20:26 +01:00
const NOCORS = false;
2025-03-04 20:20:26 +01:00
const ISDEBUG = false;
2025-03-04 20:20:26 +01:00
let corsOptions = {};
2025-03-04 20:20:26 +01:00
if (NOCORS) {
console.log('NOCORS');
2025-03-04 20:20:26 +01:00
corsOptions = {
exposedHeaders: ['x-auth', 'x-refrtok'], // Intestazioni da esporre al client
};
} else {
console.log('WITH CORS');
let credentials = true;
let allowedOrigins = null;
if (!isProduction) {
allowedOrigins = 'https://localhost:3000';
} else {
allowedOrigins = 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}`,
]);
2025-03-26 23:23:48 +01:00
// Aggiungi i domini da DOMAINS_ALLOWED
allowedOrigins = allowedOrigins.concat(
domains_allowed.map((domain) => [`https://${domain}`, `http://${domain}`]).flat()
2025-03-26 23:23:48 +01:00
);
}
console.log('allowedOrigins', allowedOrigins);
2025-03-04 20:20:26 +01:00
let myorigin = '*';
if (domains.length > 0) {
myorigin = (origin, callback) => {
try {
// Validazione dell'input
2025-03-26 23:23:48 +01:00
if (origin === undefined) {
console.log('✅ Origin UNDEFINED... vado avanti lo stesso !');
return callback(null, true);
}
if (!origin || typeof origin !== 'string' || !/^https?:\/\/[^\s/$.?#].[^\s]*$/.test(origin)) {
2025-03-21 19:52:01 +01:00
console.error('❌ Origine non valida:', origin);
return callback(new Error('Origine non valida'), false);
}
2025-03-04 20:20:26 +01:00
// Controllo delle origini consentite
2025-03-21 19:52:01 +01:00
if (allowedOrigins.includes(origin)) {
2025-03-26 23:23:48 +01:00
// console.log('✅ Origine consentita:', origin);
return callback(null, true);
}
// Blocco delle origini non autorizzate
console.warn('❌ Origine bloccata:', origin);
2025-03-21 19:52:01 +01:00
return callback(new Error('CORS non permesso per questa origine'), false);
} catch (error) {
console.error("Errore durante la verifica dell'origine:", error.message);
2025-03-21 19:52:01 +01:00
return callback(error, false);
2025-03-04 20:20:26 +01:00
}
};
2025-03-04 20:20:26 +01:00
}
2025-03-04 20:20:26 +01:00
// Configurazione CORS dettagliata
const corsOptions = {
origin: myorigin,
credentials,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
allowedHeaders: [
'Origin',
'X-Requested-With',
'Content-Type',
'Accept',
'Authorization',
'x-auth',
'x-refrtok',
2025-03-04 20:20:26 +01:00
],
exposedHeaders: ['x-auth', 'x-refrtok'],
maxAge: 86400, // Preflight cache 24 ore
preflightContinue: false,
optionsSuccessStatus: 204,
2025-03-04 20:20:26 +01:00
};
2025-03-04 20:20:26 +01:00
// Applica CORS come primo middleware
app.use(cors(corsOptions));
// HO AGGIUNTO QUESTA RIGA PER IL CORS !!!!!!!
app.use(express.json()); // Middleware per il parsing del corpo JSON
app.options('*', cors(corsOptions)); // Gestisce tutte le richieste OPTIONS
// Middleware personalizzato per assicurare gli headers CORS
2025-03-21 19:52:01 +01:00
/*app.use((req, res, next) => {
const origin = req.headers.origin || '*';
if (allowedOrigins.includes(origin) || corsOptions.origin === '*') {
// console.log(' ... ORIGIN', origin);
2025-03-04 20:20:26 +01:00
res.setHeader('Access-Control-Allow-Origin', origin);
2025-03-21 19:52:01 +01:00
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
2025-03-04 20:20:26 +01:00
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Expose-Headers', 'x-auth, x-refrtok');
}
next();
2025-03-21 19:52:01 +01:00
});*/
2025-02-05 12:13:27 +01:00
2025-03-04 20:20:26 +01:00
// 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);
}
2025-03-04 20:20:26 +01:00
// 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);
};
2025-03-04 20:20:26 +01:00
next();
});
2025-03-04 20:20:26 +01:00
// 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,
2025-03-04 20:20:26 +01:00
});
res.status(403).json({
error: '❌ CORS non permesso per questa origine (' + req.headers.origin + ')',
origin: req.headers.origin,
2025-03-04 20:20:26 +01:00
});
} else {
next(err);
}
});
}
2025-03-04 20:20:26 +01:00
if (isProduction) {
for (let i = 0; i < domains.length; i++) {
const mycredentials = getCredentials(domains[i].hostname);
2025-03-04 20:20:26 +01:00
// console.log('credentials: ', credentials);
httpsServer = https.createServer(mycredentials, app);
console.log(
'⭐️⭐️⭐️⭐️⭐️ HTTPS server: ' + domains[i].hostname + ' Port:',
domains[i].port + (domains[i].website ? 'WebSite = ' + domains[i].website : '')
);
2025-03-04 20:20:26 +01:00
httpsServer.listen(domains[i].port);
}
} else {
if (process.env.HTTPS_LOCALHOST === 'true') {
let mycredentials = null;
2025-03-04 20:20:26 +01:00
try {
2025-03-21 19:52:01 +01:00
const keyStream = path.resolve(`./${process.env.PATH_CERT_KEY}`);
const certificateStream = path.resolve(`./${process.env.PATH_SERVER_CRT}`);
2025-03-26 23:23:48 +01:00
const privateKey = fs.readFileSync(keyStream, 'utf8');
const certificate = fs.readFileSync(certificateStream, 'utf8');
2025-03-26 23:23:48 +01:00
mycredentials = {
2025-03-21 19:52:01 +01:00
key: privateKey,
cert: certificate,
ciphers:
'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384',
2025-03-04 20:20:26 +01:00
honorCipherOrder: true,
secureProtocol: 'TLSv1_2_method',
2025-03-04 20:20:26 +01:00
};
} catch (error) {
console.error('Errore durante la lettura dei file di certificazione, error:', error.message);
throw error;
}
if (mycredentials) {
httpsServer = https.createServer(mycredentials, app);
2025-03-04 20:20:26 +01:00
console.log('⭐️⭐️⭐️ HTTPS server IN LOCALE : port', port);
httpsServer.listen(port);
} else {
httpServer = http.createServer(app);
if (httpServer) {
console.log('⭐️⭐️⭐️ HTTP server IN LOCALE : port', port);
httpServer.listen(port);
}
}
2025-03-04 20:20:26 +01:00
// console.log('credentials', credentials);
} else {
httpServer = http.createServer(app);
if (httpServer) {
console.log('⭐️⭐️⭐️ HTTP server IN LOCALE : port', port);
httpServer.listen(port);
}
}
}
2025-03-04 20:20:26 +01:00
let wss = null;
2025-03-04 20:20:26 +01:00
if (httpsServer) {
wss = new WebSocket.Server({ server: httpsServer });
} else if (httpServer) {
wss = new WebSocket.Server({ server: httpServer });
} else {
// console.error('Nessun server HTTP o HTTPS disponibile per WebSocket');
// process.exit(1);
}
2025-03-04 20:20:26 +01:00
if (wss) {
wss.on('connection', (ws) => {
console.log('Client socket connected...');
2025-03-04 20:20:26 +01:00
const { User } = require('./models/user');
2025-03-04 20:20:26 +01:00
let scriptProcess = null;
2025-03-04 20:20:26 +01:00
const pty = require('node-pty');
2025-03-04 20:20:26 +01:00
ws.on('message', (message) => {
const parsedMessage = JSON.parse(message);
2025-03-04 20:20:26 +01:00
try {
if (parsedMessage.type === 'start_script' && User.isAdminById(parsedMessage.user_id)) {
2025-03-04 20:20:26 +01:00
if (scriptProcess) {
scriptProcess.kill();
}
2025-03-04 20:20:26 +01:00
const scriptPath = path.join(__dirname, '..', '..', '', parsedMessage.scriptName);
// Verifica che lo script esista e sia all'interno della directory consentita
if (fs.existsSync(scriptPath)) {
scriptProcess = pty.spawn('bash', [scriptPath], {
name: 'xterm-color',
cols: 80,
rows: 40,
cwd: process.cwd(),
env: process.env,
2025-03-04 20:20:26 +01:00
});
let buffer = '';
scriptProcess.on('data', (data) => {
buffer += data;
// Invia l'output al client
ws.send(JSON.stringify({ type: 'output', data: data }));
// Controlla se c'è una richiesta di input
if (
buffer &&
(buffer.endsWith(': ') ||
buffer.includes('? ') ||
buffer.toLowerCase().includes('password') ||
buffer.includes('Inserisci') ||
buffer.includes('Inserted') ||
buffer.includes('(Y'))
2025-03-04 20:20:26 +01:00
) {
ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() }));
buffer = '';
}
// Pulisci il buffer se diventa troppo grande
if (buffer.length > 5024) {
buffer = buffer.slice(-500);
}
});
scriptProcess.on('exit', (code) => {
if (code === 0) {
ws.send(JSON.stringify({ type: 'close', data: `*** FINE SCRIPT ***` }));
} else {
ws.send(JSON.stringify({ type: 'close', data: `Script terminato con codice ${code}` }));
}
});
} else {
2025-03-04 20:20:26 +01:00
ws.send(JSON.stringify({ type: 'error', data: 'Script non trovato o non autorizzato' }));
}
2025-03-04 20:20:26 +01:00
} else if (parsedMessage.type === 'input') {
if (scriptProcess) {
scriptProcess.write(parsedMessage.data + '\n');
}
}
} catch (error) {
console.error("Errore durante l'elaborazione del messaggio:", error.message);
}
2025-03-04 20:20:26 +01:00
});
ws.on('close', () => {
console.log('*** Client socket disconnected');
if (scriptProcess) {
2025-03-04 20:20:26 +01:00
scriptProcess.kill();
}
2025-03-04 20:20:26 +01:00
});
});
} else {
console.error('Nessuna Socket Aperta con WebSocket !!');
}
} catch (e) {
console.log('error startServer: ' + e);
}
}
2025-03-04 20:20:26 +01:00
})
.catch((err) => {
console.error('Impossibile connettersi al database dopo diversi tentativi:', err);
2025-03-04 20:20:26 +01:00
process.exit(1); // Termina il processo se non riesce a connettersi
});
2023-02-15 21:40:19 +01:00
module.exports = { app };