From fe4a67c9f19e1c191d4d31d13b25d312d4c38c01 Mon Sep 17 00:00:00 2001 From: Surya Paolo Date: Fri, 6 Sep 2024 19:57:09 +0200 Subject: [PATCH] - AbitaregliIblei.it - Server aggiornamenti agli script. - Editor HTML corretto un po'. - Record Mysql per server (appena iniziato) --- .env.dev.pcb | 3 +- .env.development | 3 +- .env.prod.pcb | 9 +- .env.test.pcb | 9 +- .env.test.risosrv | 7 +- admin_scripts/1_GENERALE/inputTest.sh | 1 + .../5_UPGRADE/01_export_FreePlanet_to_pcb.sh | 16 + .../02_importa_db_Test_Freeplanet_SuDocker.sh | 28 ++ admin_scripts/5_UPGRADE/backup_sito_web.sh | 30 ++ .../6_CERTIFICATI/create_new_cert.sh | 20 + deploynode_on_prod_pcb.sh | 4 +- deploynode_on_test_pcb.sh | 22 +- deploynodejs_on_risosrv_test.sh | 80 +++- .../50_ssl_test.abitaregliiblei.it.conf | 39 ++ ...ominioinclude_test.abitaregliiblei.it.conf | 4 + .../ssl_vhost_api.abitaregliiblei.it.conf | 51 +++ .../ssl_vhost_api.gruppomacro.app.conf | 11 - docs/apache2/vhost.ssl_abitaregliiblei.conf | 22 -- mongodb/Diffusori.mongodb | 354 ------------------ src/server/models/sectoractivities.js | 87 +++++ src/server/models/user.js | 16 +- src/server/modules/cloudflare.js | 136 ++++--- src/server/router/admin_router.js | 43 +++ src/server/router/index_router.js | 9 +- src/server/server.js | 144 +++---- src/server/telegram/telegrambot.js | 9 +- src/server/tools/general.js | 47 ++- src/server/version.txt | 1 + 28 files changed, 638 insertions(+), 567 deletions(-) create mode 100644 admin_scripts/5_UPGRADE/01_export_FreePlanet_to_pcb.sh create mode 100644 admin_scripts/5_UPGRADE/02_importa_db_Test_Freeplanet_SuDocker.sh create mode 100644 admin_scripts/5_UPGRADE/backup_sito_web.sh create mode 100755 admin_scripts/6_CERTIFICATI/create_new_cert.sh create mode 100644 docs/apache2/sites-available/50_ssl_test.abitaregliiblei.it.conf create mode 100644 docs/apache2/sites-available/dominioinclude_test.abitaregliiblei.it.conf create mode 100644 docs/apache2/ssl_vhost_api.abitaregliiblei.it.conf delete mode 100644 docs/apache2/vhost.ssl_abitaregliiblei.conf delete mode 100644 mongodb/Diffusori.mongodb create mode 100755 src/server/models/sectoractivities.js create mode 100644 src/server/version.txt diff --git a/.env.dev.pcb b/.env.dev.pcb index 745eee4..4ebffcd 100644 --- a/.env.dev.pcb +++ b/.env.dev.pcb @@ -39,4 +39,5 @@ FTPSERVER_PORT=21 FTPSERVER_USER=ftpusrsrv_ FTPSERVER_PWD=ftpmypwd@1A_ AUTH_NEW_SITES=123123123 -SCRIPTS_DIR=admin_scripts \ No newline at end of file +SCRIPTS_DIR=admin_scripts +CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] diff --git a/.env.development b/.env.development index b85e237..49a7e92 100644 --- a/.env.development +++ b/.env.development @@ -38,4 +38,5 @@ FTPSERVER_HOST=139.162.166.31 FTPSERVER_PORT=21 FTPSERVER_USER=ftpusrsrv_ FTPSERVER_PWD=ftpmypwd@1A_ -AUTH_NEW_SITES=123123123 \ No newline at end of file +AUTH_NEW_SITES=123123123 +CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] diff --git a/.env.prod.pcb b/.env.prod.pcb index 5afc249..0417593 100644 --- a/.env.prod.pcb +++ b/.env.prod.pcb @@ -7,8 +7,8 @@ PORT=3000 appTelegram_TEST=["17","18"] appTelegram=["17","18"] ENABLE_PUSHNOTIFICATION=1 -DIRECTORY_SERVER=freeplanet_serverside -SERVERDIR_WEBSITE=www.freeplanet_server +DIRECTORY_SERVER=/var/www/www.freeplanet_server +SERVERDIR_WEBSITE= PORT_APP1="0" DOMAIN=mongodb://localhost:32001/ AUTH_MONGODB=1 @@ -33,5 +33,6 @@ SECRTK=jAxKm02emx5SeJvz2IGmtRf6YqCgope TOKEN_LIFE=2h REFRESH_TOKEN_LIFE=14d AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNVZZ -DOMAINS=[{"hostname": "piuchebuono.app","port": 3000 },{"hostname":"gruppomacro.app","port": 3010}] -SCRIPTS_DIR=admin_scripts \ No newline at end of file +DOMAINS=[{"hostname":"piuchebuono.app","port":"3000"},{"hostname":"gruppomacro.app","port":"3010"}] +SCRIPTS_DIR=admin_scripts +CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] diff --git a/.env.test.pcb b/.env.test.pcb index fac2e91..0187d4a 100644 --- a/.env.test.pcb +++ b/.env.test.pcb @@ -7,8 +7,8 @@ PORT=3001 appTelegram_TEST=["17","18"] appTelegram=["17","18"] ENABLE_PUSHNOTIFICATION=1 -DIRECTORY_SERVER=freeplanet_serverside -SERVERDIR_WEBSITE=test.freeplanet_server +DIRECTORY_SERVER=/var/www/test.freeplanet_serverside +SERVERDIR_WEBSITE=test.piuchebuono.app PORT_APP1="0" DOMAIN=mongodb://localhost:32002/ AUTH_MONGODB=1 @@ -31,4 +31,7 @@ PROJECT_DESCR_MAIN='__PROJECTS' SECRK=iUUb38v23jjDFaosWj92axkBOXCQ TOKEN_LIFE=2h REFRESH_TOKEN_LIFE=14d -AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV \ No newline at end of file +AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV +DOMAINS=[{"hostname":"test.piuchebuono.app","port":"3002"},{"hostname":"test.gruppomacro.app","port":"3012"},{"hostname":"test.abitaregliiblei.it","port":"3022"}] +SCRIPTS_DIR=admin_scripts +CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] diff --git a/.env.test.risosrv b/.env.test.risosrv index bc8a768..8452225 100644 --- a/.env.test.risosrv +++ b/.env.test.risosrv @@ -5,7 +5,7 @@ SEND_EMAIL=1 PORT=3001 ENABLE_PUSHNOTIFICATION=1 DIRECTORY_SERVER=/var/www/testriso.freeplanet_serverside -SERVERDIR_WEBSITE=testriso.piuchebuono.app +SERVERDIR_WEBSITE=test.riso.app PORT_APP1="0" DOMAIN=mongodb://localhost:32002/ AUTH_MONGODB=1 @@ -28,4 +28,7 @@ PROJECT_DESCR_MAIN='__PROJECTS' SECRK=iUUb38v23jjDFaosWj92axkBOXCQ TOKEN_LIFE=2h REFRESH_TOKEN_LIFE=14d -AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV \ No newline at end of file +AUTH_NEW_SITES=B234HDSAOJ734ndcsdKWNV +DOMAINS=[{"hostname":"test.abitaregliiblei.it","port":"3021"}] +SCRIPTS_DIR=admin_scripts +CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] diff --git a/admin_scripts/1_GENERALE/inputTest.sh b/admin_scripts/1_GENERALE/inputTest.sh index 6206b4c..74c4b43 100755 --- a/admin_scripts/1_GENERALE/inputTest.sh +++ b/admin_scripts/1_GENERALE/inputTest.sh @@ -1,6 +1,7 @@ #!/bin/bash #DATA|TITLE|Input Test #DATA|DESCRIZ|Input Test +#DATA|SOCK|true echo "Inizio dello Script... " echo ".............................................." diff --git a/admin_scripts/5_UPGRADE/01_export_FreePlanet_to_pcb.sh b/admin_scripts/5_UPGRADE/01_export_FreePlanet_to_pcb.sh new file mode 100644 index 0000000..4b6467f --- /dev/null +++ b/admin_scripts/5_UPGRADE/01_export_FreePlanet_to_pcb.sh @@ -0,0 +1,16 @@ +#!/bin/bash +#DATA|TITLE|Esporta FreePlanet sul Server PCB +#DATA|DESCRIZ|Esporta FreePlanet in "exp_db_test.tar.gz" e lo invia sul Server PCB +#DATA|SOCK|false + +DATABASE="FreePlanet" +FILEMONGODB="export_database_$DATABASE" +FILEZIP="exp_db_test.tar.gz" + +source .my_cfg.ini + +mongodump --db $DATABASE --authenticationDatabase admin -u admin -p $PWDDB --out $FILEMONGODB + +tar cvfz $FILEZIP $FILEMONGODB + +scp -P 8822 $FILEZIP pcbuser@pcb:~ \ No newline at end of file diff --git a/admin_scripts/5_UPGRADE/02_importa_db_Test_Freeplanet_SuDocker.sh b/admin_scripts/5_UPGRADE/02_importa_db_Test_Freeplanet_SuDocker.sh new file mode 100644 index 0000000..ea2c1ff --- /dev/null +++ b/admin_scripts/5_UPGRADE/02_importa_db_Test_Freeplanet_SuDocker.sh @@ -0,0 +1,28 @@ +#!/bin/bash +#DATA|TITLE|Importa FreePlanet su test_FreePlanet +#DATA|DESCRIZ|Importa FreePlanet (su test_FreePlanet) dal file inviato dal server mail.freeplanet.app +#DATA|SOCK|false + +FILEZIP="exp_db_test.tar.gz" +DATABASEIN="FreePlanet" +DATABASEOUT="test_FreePlanet" +FILEMONGODBIN="export_database_$DATABASEIN" +FILEMONGODBOUT="export_database_$DATABASEOUT" + +source .my_cfg.ini + +# Copia il file .tar.gz nel container +docker cp /home/pcbuser/$FILEZIP mongodbtest:/home/test/ + +# Notifica l'intenzione di estrarre il contenuto del file tar.gz +echo "Estrazione di $FILEZIP in /home/test/ all'interno del container..." +echo "" + +# Estrai il contenuto del file tar.gz nel container +docker exec -it mongodbtest tar -xvzf /home/test/$FILEZIP -C /home/test/ + +# Rinomina la directory contenente il database esportato +docker exec -i mongodbtest mv /home/test/$FILEMONGODBIN /home/test/$FILEMONGODBOUT + +# Ripristina il database MongoDB dal dump +docker exec -i mongodbtest mongorestore --username admin --password $PWDDB_TEST --authenticationDatabase admin --nsFrom='FreePlanet.*' --nsTo='test_FreePlanet.*' /home/test/> \ No newline at end of file diff --git a/admin_scripts/5_UPGRADE/backup_sito_web.sh b/admin_scripts/5_UPGRADE/backup_sito_web.sh new file mode 100644 index 0000000..e80739f --- /dev/null +++ b/admin_scripts/5_UPGRADE/backup_sito_web.sh @@ -0,0 +1,30 @@ +#!/bin/bash +#DATA|TITLE|Copia sito Web +#DATA|DESCRIZ|Fai una copia di Backup del sito web +#DATA|SOCK|false + +if [ "$1" = "" ]; then + read -p "Inserisci il Sito Web (pippo.it)" WEBSITE +else + WEBSITE=$1 +fi + +FILEBACKUP_SITE="BACKUP_$WEBSITE_$(date +"%Y-%m-%d").tar.gz" + +echo "********************************" + +msg="*** COPIA SITO WEB di $WEBSITE (Y/N) ? " + +if [ "$1" = "" ]; then + read -p "$msg" risposta +else + echo $msg + risposta=$1 +fi + +if [[ $risposta == "Y" || $risposta == "y" ]]; then + tar cvfz $FILEBACKUP_SITE /var/www/$WEBSITE/ + + echo "*** COPIA TERMINATA *** + echo "***********************" +fi diff --git a/admin_scripts/6_CERTIFICATI/create_new_cert.sh b/admin_scripts/6_CERTIFICATI/create_new_cert.sh new file mode 100755 index 0000000..883a255 --- /dev/null +++ b/admin_scripts/6_CERTIFICATI/create_new_cert.sh @@ -0,0 +1,20 @@ +#!/bin/bash +#DATA|TITLE|Creazione Certificato +#DATA|DESCRIZ|Crea un Certificato utilizzando cloudflare per dominio e *.dominio +#DATA|SOCK|true + +if [ "$1" = "" ]; then + read -p "Inserisci il nome del Dominio " DOMINIO +else + DOMINIO=$1 +fi + +echo sudo certbot certonly --dns-cloudflare --dns-cloudflare-credentials /root/.secrets/certbot/cloudflare.ini -d $DOMINIO,*.$DOMINIO --preferred-challenges dns-01 + +read -p "CONTINUARE ed Eseguirlo ? (Y/N) ? " risposta + +if [[ $risposta == "Y" || $risposta == "y" ]]; then + + sudo certbot certonly --dns-cloudflare --dns-cloudflare-credentials /root/.secrets/certbot/cloudflare.ini -d $DOMINIO,*.$DOMINIO --preferred-challenges dns-01 + +fi diff --git a/deploynode_on_prod_pcb.sh b/deploynode_on_prod_pcb.sh index 3858ac8..6c6c9bb 100755 --- a/deploynode_on_prod_pcb.sh +++ b/deploynode_on_prod_pcb.sh @@ -2,7 +2,7 @@ source ./.env.prod.pcb -echo "Sincronizzazione in corso PCB PRODUZIONE ... /var/www/$SERVERDIR_WEBSITE/" +echo "Sincronizzazione in corso PCB PRODUZIONE ... $DIRECTORY_SERVER/" echo "" #!/bin/bash @@ -11,7 +11,7 @@ echo "" REMOTE_USER="pcbuser" REMOTE_HOST="pcb" REMOTE_PORT="8822" -REMOTE_DIR="/var/www/$SERVERDIR_WEBSITE" +REMOTE_DIR="$DIRECTORY_SERVER" SSH_OPTIONS="-p $REMOTE_PORT" # Array di cartelle e file da sincronizzare diff --git a/deploynode_on_test_pcb.sh b/deploynode_on_test_pcb.sh index fc0485f..f3407b5 100755 --- a/deploynode_on_test_pcb.sh +++ b/deploynode_on_test_pcb.sh @@ -2,18 +2,18 @@ source ./.env.test.pcb -echo "Sincronizzazione in corso PCB TEST ... /var/www/$SERVERDIR_WEBSITE/" +echo "Sincronizzazione in corso PCB TEST ... /var/www/$DIRECTORY_SERVER/" echo "" -rsync -avz -e 'ssh -p 8822' css pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/ -rsync -avz -e 'ssh -p 8822' docs pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/ -rsync -avz -e 'ssh -p 8822' emails pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/ -rsync -avz -e 'ssh -p 8822' images pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/ -rsync -avz -e 'ssh -p 8822' plugins pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/ -rsync -avz -e 'ssh -p 8822' sass pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/ -rsync -avz -e 'ssh -p 8822' src pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/ -rsync -avz -e 'ssh -p 8822' .env.test.pcb pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/.env.test -rsync -avz -e 'ssh -p 8822' .env.test.pcb pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/ -rsync -avz -e 'ssh -p 8822' package.json pcbuser@pcb:/var/www/$SERVERDIR_WEBSITE/package.json +rsync -avz -e 'ssh -p 8822' css pcbuser@pcb:/var/www/$DIRECTORY_SERVER/ +rsync -avz -e 'ssh -p 8822' docs pcbuser@pcb:/var/www/$DIRECTORY_SERVER/ +rsync -avz -e 'ssh -p 8822' emails pcbuser@pcb:/var/www/$DIRECTORY_SERVER/ +rsync -avz -e 'ssh -p 8822' images pcbuser@pcb:/var/www/$DIRECTORY_SERVER/ +rsync -avz -e 'ssh -p 8822' plugins pcbuser@pcb:/var/www/$DIRECTORY_SERVER/ +rsync -avz -e 'ssh -p 8822' sass pcbuser@pcb:/var/www/$DIRECTORY_SERVER/ +rsync -avz -e 'ssh -p 8822' src pcbuser@pcb:/var/www/$DIRECTORY_SERVER/ +rsync -avz -e 'ssh -p 8822' .env.test.pcb pcbuser@pcb:/var/www/$DIRECTORY_SERVER/.env.test +rsync -avz -e 'ssh -p 8822' .env.test.pcb pcbuser@pcb:/var/www/$DIRECTORY_SERVER/ +rsync -avz -e 'ssh -p 8822' package.json pcbuser@pcb:/var/www/$DIRECTORY_SERVER/package.json echo "Sincronizzazione TERMINATA! - SERVER PCB!" diff --git a/deploynodejs_on_risosrv_test.sh b/deploynodejs_on_risosrv_test.sh index 1216382..50857c0 100755 --- a/deploynodejs_on_risosrv_test.sh +++ b/deploynodejs_on_risosrv_test.sh @@ -2,20 +2,68 @@ source ./.env.test.risosrv -echo "Sincronizzazione in corso... $DIRECTORY_SERVER" -rsync -avz -e 'scp -p 8822' .env.test.risosrv pcbuser@pcb:$DIRECTORY_SERVER/.env.test -rsync -avz -e 'ssh -p 8822' ecosystem.config.testriso.js pcbuser@pcb:$DIRECTORY_SERVER/ecosystem.config.js -rsync -avz -e 'ssh -p 8822' css pcbuser@pcb:$DIRECTORY_SERVER/ -rsync -avz -e 'ssh -p 8822' docs pcbuser@pcb:$DIRECTORY_SERVER/ -rsync -avz -e 'ssh -p 8822' emails pcbuser@pcb:$DIRECTORY_SERVER/ -rsync -avz -e 'ssh -p 8822' images pcbuser@pcb:$DIRECTORY_SERVER/ -rsync -avz -e 'ssh -p 8822' plugins pcbuser@pcb:$DIRECTORY_SERVER/ -rsync -avz -e 'ssh -p 8822' sass pcbuser@pcb:$DIRECTORY_SERVER/ -rsync -avz -e 'ssh -p 8822' src --exclude 'server/router/upload' pcbuser@pcb:$DIRECTORY_SERVER/ -rsync -avz -e 'ssh -p 8822' ecosystem.config.testriso.js pcbuser@pcb:$DIRECTORY_SERVER/ecosystem.config.js -rsync -avz -e 'ssh -p 8822' package.json pcbuser@pcb:$DIRECTORY_SERVER/package.json +echo "Sincronizzazione in corso ... $DIRECTORY_SERVER/" +echo "" + +#!/bin/bash + +# Configurazione +REMOTE_USER="pcbuser" +REMOTE_HOST="pcb" +REMOTE_PORT="8822" +REMOTE_DIR="$DIRECTORY_SERVER" +SSH_OPTIONS="-p $REMOTE_PORT" +CONFIG_JS="ecosystem.config.testriso.js" +ENV_FILE=".env.test.risosrv" +ENV_OUT=".env.test" + +#ENV_FILE=".env.prod.pcb" +#ENV_OUT=".env.production" + +# Array di cartelle e file da sincronizzare +SYNC_ITEMS=( + "css" + "docs" + "emails" + "plugins" + "sass" + "src" +) + +echo $REMOTE_DIR + +echo "" +echo "*** Copia Cartelle ... " + + +# Esegui rsync per le cartelle +rsync -avz --delete \ + --exclude='src/server/router/upload/' \ + -e "ssh $SSH_OPTIONS" \ + "${SYNC_ITEMS[@]}" \ + "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/" + +echo "" +echo "*** Copia del file $ENV_FILE su $ENV_OUT ... " + +# Sincronizza i file specifici +rsync -avz -e "ssh $SSH_OPTIONS" \ + $ENV_FILE "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/$ENV_OUT" + +echo "" +echo "*** Copia del file package.json ... " +rsync -avz -e "ssh $SSH_OPTIONS" \ + package.json "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/package.json" + +echo "" +echo "*** Copia del file ecosystem.config.js ... " +rsync -avz -e "ssh $SSH_OPTIONS" \ + "$CONFIG_JS" "$REMOTE_USER@$REMOTE_HOST:$REMOTE_DIR/ecosystem.config.js" + +# Verifica il risultato +if [ $? -eq 0 ]; then + echo "Sincronizzazione completata con successo. SERVER $REMOTE_DIR! " +else + echo "Errore durante la sincronizzazione. Controlla l'output per i dettagli." +fi -echo "**************************" -echo "Sincronizzazione TERMINATA! - TESTSRISO.FREEPLANET_SERVER!" -echo "https://testriso.piuchebuono.app" -echo "**************************" diff --git a/docs/apache2/sites-available/50_ssl_test.abitaregliiblei.it.conf b/docs/apache2/sites-available/50_ssl_test.abitaregliiblei.it.conf new file mode 100644 index 0000000..c78834d --- /dev/null +++ b/docs/apache2/sites-available/50_ssl_test.abitaregliiblei.it.conf @@ -0,0 +1,39 @@ +Include /etc/apache2/sites-available/dominioinclude_test.abitaregliiblei.it.conf + +# Configurazione per HTTP + + ServerName ${MIODOMINIO_COMPLETO} + DocumentRoot /var/www/${MIODOMINIO_COMPLETO} + + RewriteEngine on + # Redirigi tutto il traffico HTTP verso HTTPS + RewriteCond %{SERVER_NAME} =${MIODOMINIO_COMPLETO} [OR] + RewriteCond %{SERVER_NAME} =www.${MIODOMINIO_COMPLETO} + RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] + + ErrorLog /var/www/${MIODOMINIO_COMPLETO}/logs/error.log + CustomLog /var/www/${MIODOMINIO_COMPLETO}/logs/access.log combined + + + +# Configurazione per HTTPS + + + ServerName ${MIODOMINIO_COMPLETO} + DocumentRoot /var/www/${MIODOMINIO_COMPLETO} + + ErrorLog /var/www/${MIODOMINIO_COMPLETO}/logs/error.log + CustomLog /var/www/${MIODOMINIO_COMPLETO}/logs/access.log combined + + + Options -Indexes +IncludesNOEXEC +SymLinksIfOwnerMatch +ExecCGI + AllowOverride All + Require all granted + + + RewriteEngine on + Include /etc/letsencrypt/options-ssl-apache.conf + SSLCertificateFile /etc/letsencrypt/live/${MIODOMINIO}/fullchain.pem + SSLCertificateKeyFile /etc/letsencrypt/live/${MIODOMINIO}/privkey.pem + + \ No newline at end of file diff --git a/docs/apache2/sites-available/dominioinclude_test.abitaregliiblei.it.conf b/docs/apache2/sites-available/dominioinclude_test.abitaregliiblei.it.conf new file mode 100644 index 0000000..0dcfb7c --- /dev/null +++ b/docs/apache2/sites-available/dominioinclude_test.abitaregliiblei.it.conf @@ -0,0 +1,4 @@ +Define MIODOMINIO abitaregliiblei.it +Define MIODOMINIO_COMPLETO test.abitaregliiblei.it +Define MIOURL_TESTAPI testapi.abitaregliiblei.it +Define PORTA 3022 \ No newline at end of file diff --git a/docs/apache2/ssl_vhost_api.abitaregliiblei.it.conf b/docs/apache2/ssl_vhost_api.abitaregliiblei.it.conf new file mode 100644 index 0000000..bd48c60 --- /dev/null +++ b/docs/apache2/ssl_vhost_api.abitaregliiblei.it.conf @@ -0,0 +1,51 @@ +Include /etc/apache2/sites-available/dominioinclude_test.abitaregliiblei.it.conf + +# Configurazione per HTTP + + ServerName ${MIODOMINIO_COMPLETO} + DocumentRoot /var/www/${MIODOMINIO_COMPLETO} + + RewriteEngine on + # Redirigi tutto il traffico HTTP verso HTTPS + RewriteCond %{SERVER_NAME} =${MIODOMINIO_COMPLETO} [OR] + RewriteCond %{SERVER_NAME} =www.${MIODOMINIO_COMPLETO} + RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] + + ErrorLog /var/www/${MIODOMINIO_COMPLETO}/logs/error.log + CustomLog /var/www/${MIODOMINIO_COMPLETO}/logs/access.log combined + + + + + ServerName ${MIOURL_TESTAPI} + ServerAdmin surya@riso.app + + SSLEngine On + SSLProtocol -ALL +TLSv1.2 +TLSv1.3 + SSLCompression Off + SSLHonorCipherOrder off + SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:E> + SSLVerifyDepth 10 + SSLCertificateFile /etc/letsencrypt/live/${MIODOMINIO}/cert.pem + SSLCertificateKeyFile /etc/letsencrypt/live/${MIODOMINIO}/privkey.pem + + ProxyPreserveHost On + SSLProxyEngine On + SSLProxyVerify None + SSLProxyCheckPeerCN Off + SSLProxyCheckPeerName Off + ProxyPass / https://localhost:${PORTA}/ retry=0 timeout=5 connectiontimeout=2 + ProxyPassReverse / https://localhost:${PORTA}/ + + ProxyTimeout 5 + + LogLevel debug proxy:trace5 + ErrorLog /var/www/${MIODOMINIO_COMPLETO}/logs/error.log + CustomLog /var/www/${MIODOMINIO_COMPLETO}/logs/access.log combined + + + ProxyPassReverse / + SetEnv force-proxy-request-1.0 1 + SetEnv proxy-nokeepalive 1 + + \ No newline at end of file diff --git a/docs/apache2/ssl_vhost_api.gruppomacro.app.conf b/docs/apache2/ssl_vhost_api.gruppomacro.app.conf index 7067dc4..d4fa7ea 100644 --- a/docs/apache2/ssl_vhost_api.gruppomacro.app.conf +++ b/docs/apache2/ssl_vhost_api.gruppomacro.app.conf @@ -1,22 +1,11 @@ ServerName api.gruppomacro.app - ServerAlias www.api.gruppomacro.app ServerAdmin surya@riso.app SSLEngine On - SSLProtocol -ALL +TLSv1.2 +TLSv1.3 - SSLCompression Off - SSLHonorCipherOrder off - SSLCipherSuite ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:E> - SSLVerifyDepth 10 SSLCertificateFile /etc/letsencrypt/live/gruppomacro.app/cert.pem SSLCertificateKeyFile /etc/letsencrypt/live/gruppomacro.app/privkey.pem - ProxyPreserveHost On - SSLProxyEngine On - SSLProxyVerify None - SSLProxyCheckPeerCN Off - SSLProxyCheckPeerName Off ProxyPass / https://localhost:3010/ retry=0 timeout=5 connectiontimeout=2 ProxyPassReverse / https://localhost:3010/ diff --git a/docs/apache2/vhost.ssl_abitaregliiblei.conf b/docs/apache2/vhost.ssl_abitaregliiblei.conf deleted file mode 100644 index 9a7c1df..0000000 --- a/docs/apache2/vhost.ssl_abitaregliiblei.conf +++ /dev/null @@ -1,22 +0,0 @@ - - ServerName abitaregliiblei.it - ServerAlias *.abitaregliiblei.it - ServerAdmin surya@riso.app - SSLEngine On - SSLProtocol -ALL +TLSv1.2 - SSLCompression Off - SSLHonorCipherOrder off - SSLCipherSuite ECDH+AESGCM:ECDH+AES256:!aNULL:!MD5:!DSS:!DH:!AES128 - SSLVerifyDepth 10 - SSLCertificateFile /etc/letsencrypt/live/abitaregliiblei.it/cert.pem - SSLCertificateKeyFile /etc/letsencrypt/live/abitaregliiblei.it/privkey.pem - DocumentRoot "/var/customers/webs/paolouser/abitaregliiblei.it" - - CGIPassAuth On - Require all granted - AllowOverride All - - LogLevel warn - ErrorLog "/var/customers/logs/paolouser-error.log" - CustomLog "/var/customers/logs/paolouser-access.log" combined - \ No newline at end of file diff --git a/mongodb/Diffusori.mongodb b/mongodb/Diffusori.mongodb deleted file mode 100644 index 89d2bd9..0000000 --- a/mongodb/Diffusori.mongodb +++ /dev/null @@ -1,354 +0,0 @@ -// MongoDB Playground -// To disable this template go to Settings | MongoDB | Use Default Template For Playground. -// Make sure you are connected to enable completions and to be able to run a playground. -// Use Ctrl+Space inside a snippet or a string literal to trigger completions. - -// Select the database to use. -use('test_FreePlanet'); - -let aggregation = [ - { - $match: { - idapp: "13", - }, - }, - { - $sort: { - date_updated: -1, - }, - }, - { - $addFields: { - myId1: { - $toObjectId: "$userId", - }, - }, - }, - { - $lookup: { - from: "users", - localField: "myId1", - foreignField: "_id", - as: "user", - }, - }, - { - $replaceRoot: { - newRoot: { - $mergeObjects: [ - { - $arrayElemAt: [ - "$user", - 0, - ], - }, - "$$ROOT", - ], - }, - }, - }, - { - $project: { - recGood: 1, - sectorGood: 1, - idSectorGood: 1, - idGood: 1, - mygood: 1, - idStatusSkill: 1, - idContribType: 1, - "profile.username_telegram": 1, - "profile.favorite": 1, - "profile.bookmark": 1, - idCity: 1, - pub_to_share: 1, - numLevel: 1, - adType: 1, - photos: 1, - note: 1, - website: 1, - descr: 1, - date_created: 1, - date_updated: 1, - userId: 1, - username: 1, - name: 1, - surname: 1, - lasttimeonline: 1, - comune: 1, - mycities: 1, - "profile.img": 1, - "profile.mygroups": 1, - "profile.qualifica": 1, - "profile.resid_province": 1, - "profile.resid_card": 1, - reported: 1, - date_report: 1, - username_who_report: 1, - }, - }, - { - $lookup: { - from: "goods", - localField: "idGood", - foreignField: "_id", - as: "recGood", - }, - }, - { - $replaceRoot: { - newRoot: { - $mergeObjects: [ - { - $arrayElemAt: [ - "$recGood", - 0, - ], - }, - "$$ROOT", - ], - }, - }, - }, - { - $project: { - recGood: 1, - sectorGood: 1, - idSectorGood: 1, - idGood: 1, - mygood: 1, - idStatusSkill: 1, - idContribType: 1, - "profile.username_telegram": 1, - "profile.favorite": 1, - "profile.bookmark": 1, - idCity: 1, - pub_to_share: 1, - numLevel: 1, - adType: 1, - photos: 1, - note: 1, - website: 1, - descr: 1, - date_created: 1, - date_updated: 1, - userId: 1, - username: 1, - name: 1, - surname: 1, - lasttimeonline: 1, - comune: 1, - mycities: 1, - "profile.img": 1, - "profile.mygroups": 1, - "profile.qualifica": 1, - "profile.resid_province": 1, - "profile.resid_card": 1, - reported: 1, - date_report: 1, - username_who_report: 1, - }, - }, - { - $lookup: { - from: "sectorgoods", - localField: "idSectorGood", - foreignField: "_id", - as: "sectorGood", - }, - }, - { - $replaceRoot: { - newRoot: { - $mergeObjects: [ - { - $arrayElemAt: [ - "$sectorGood", - 0, - ], - }, - "$$ROOT", - ], - }, - }, - }, - { - $project: { - recGood: 1, - sectorGood: 1, - idSectorGood: 1, - idGood: 1, - mygood: 1, - idStatusSkill: 1, - idContribType: 1, - "profile.username_telegram": 1, - "profile.favorite": 1, - "profile.bookmark": 1, - idCity: 1, - pub_to_share: 1, - numLevel: 1, - adType: 1, - photos: 1, - note: 1, - website: 1, - descr: 1, - date_created: 1, - date_updated: 1, - userId: 1, - username: 1, - name: 1, - surname: 1, - lasttimeonline: 1, - comune: 1, - mycities: 1, - "profile.img": 1, - "profile.mygroups": 1, - "profile.qualifica": 1, - "profile.resid_province": 1, - reported: 1, - date_report: 1, - username_who_report: 1, - }, - }, - { - $lookup: { - from: "cities", - localField: "idCity", - foreignField: "_id", - as: "mycities", - }, - }, - { - $replaceRoot: { - newRoot: { - $mergeObjects: [ - { - $arrayElemAt: [ - "$mycities", - 0, - ], - }, - "$$ROOT", - ], - }, - }, - }, - { - $project: { - recGood: 1, - sectorGood: 1, - idSectorGood: 1, - idGood: 1, - mygood: 1, - idStatusSkill: 1, - idContribType: 1, - "profile.username_telegram": 1, - "profile.favorite": 1, - "profile.bookmark": 1, - idCity: 1, - pub_to_share: 1, - numLevel: 1, - adType: 1, - photos: 1, - note: 1, - website: 1, - descr: 1, - date_created: 1, - date_updated: 1, - userId: 1, - username: 1, - name: 1, - surname: 1, - lasttimeonline: 1, - comune: 1, - mycities: 1, - "profile.img": 1, - "profile.mygroups": 1, - "profile.qualifica": 1, - "profile.resid_province": 1, - reported: 1, - date_report: 1, - username_who_report: 1, - }, - }, - { - $match: { - $or: [ - { - $and: [ - { - "profile.mygroups": { - $elemMatch: { - groupname: { - $in: [ - "000017", - "risoprova", - "VillaggiamoItalia", - "Terraw", - "RisoBenevento", - "111", - "gruppodefaultriso", - "pontiUmani", - ], - }, - }, - }, - }, - { - pub_to_share: 1, - }, - ], - }, - { - $or: [ - { - pub_to_share: { - $exists: false, - }, - }, - { - pub_to_share: { - $exists: true, - $eq: 0, - }, - }, - ], - }, - ], - }, - }, - { - $match: { - $and: [ - { - "mycities.reg": "EMR", - }, - ], - }, - }, - { - $group: { - _id: null, - count: { - $sum: 1, - }, - results: { - $push: "$$ROOT", - }, - }, - }, - { - $project: { - count: 1, - rows: { - $slice: [ - "$results", - 0, - 10, - ], - }, - }, - }, -]; - -db.myskills.aggregate(aggregation); - diff --git a/src/server/models/sectoractivities.js b/src/server/models/sectoractivities.js new file mode 100755 index 0000000..d2e0b03 --- /dev/null +++ b/src/server/models/sectoractivities.js @@ -0,0 +1,87 @@ +const mongoose = require('mongoose').set('debug', false) +const Schema = mongoose.Schema; + +mongoose.Promise = global.Promise; +mongoose.level = "F"; + +const tools = require('../tools/general'); + +const { ObjectID } = require('mongodb'); + +// Resolving error Unknown modifier: $pushAll +mongoose.plugin(schema => { + schema.options.usePushEach = true +}); + +const SectorActivitiesSchema = new Schema({ + _id: { + type: Number, + }, + descr: { + type: String, + }, + idSectorActivities: { + type: Number + }, + icon: { + type: String, + }, + img: { + type: String, + }, + color: { + type: String, + }, + theme: { + type: String, + }, +}); + +SectorActivitiesSchema.pre('save', async function (next) { + if (this.isNew) { + const myrec = await SectorActivities.findOne().limit(1).sort({ _id: -1 }); + if (!!myrec) { + if (myrec._doc._id === 0) + this._id = 1; + else + this._id = myrec._doc._id + 1; + } else { + this._id = 1; + } + } + + next(); +}); + +SectorActivitiesSchema.statics.findAllIdApp = async function (idapp) { + const SectorActivities = this; + + const query = [ + { $sort: { descr: 1 } } + ]; + + return await SectorActivities + .aggregate(query) + .then((arrrec) => { + return arrrec + }) + +}; + +SectorActivitiesSchema.statics.getFieldsForSearch = function () { + return [{ field: 'descr', type: tools.FieldType.string }] +}; + +SectorActivitiesSchema.statics.executeQueryTable = function (idapp, params) { + params.fieldsearch = this.getFieldsForSearch(); + return tools.executeQueryTable(this, 0, params); +}; + + +const SectorActivities = mongoose.model('SectorActivities', SectorActivitiesSchema); + +SectorActivities.createIndexes((err) => { + if (err) throw err; +}); + +module.exports = { SectorActivities }; diff --git a/src/server/models/user.js b/src/server/models/user.js index 1be3eba..0ead141 100755 --- a/src/server/models/user.js +++ b/src/server/models/user.js @@ -672,6 +672,16 @@ UserSchema.statics.isManagerById = async function (id) { } }; +UserSchema.statics.isAdminById = async function (id) { + try { + const ris = await User.findOne({ _id: id }, { perm: 1 }).lean(); + return ((ris.perm & shared_consts.Permissions.Admin) === + shared_consts.Permissions.Admin); + } catch (e) { + return false; + } +}; + UserSchema.statics.isEditor = function (perm) { try { return ((perm & shared_consts.Permissions.Editor) === @@ -3237,7 +3247,7 @@ UserSchema.statics.setCircuitCmd = async function (idapp, usernameOrig, circuitn } ris = true; - // } else if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) { + // } else if ((cmd === shared_consts.CIRCUITCMD.SENDCOINS_ACCEPT) || (cmd === shared_consts.CIRCUITCMD.SENDCOINS_REFUSE)) { // Before to accept, I see if it's already set ! /*outres = { @@ -5742,10 +5752,10 @@ UserSchema.statics.tooManyLoginWrong = async function (idapp, username, set) { await User.findOneAndUpdate({ _id: user._id }, { $set: { retry_pwd: user.retry_pwd } }); } - return {troppilogin: user.retry_pwd > maxnum, retry_pwd: user.retry_pwd}; + return { troppilogin: user.retry_pwd > maxnum, retry_pwd: user.retry_pwd }; } - return {troppilogin: false, retry_pwd: 0}; + return { troppilogin: false, retry_pwd: 0 }; }; UserSchema.statics.setLastCircuitOpened = async function (idapp, username, circuitpath) { diff --git a/src/server/modules/cloudflare.js b/src/server/modules/cloudflare.js index b82582b..561c084 100644 --- a/src/server/modules/cloudflare.js +++ b/src/server/modules/cloudflare.js @@ -1,66 +1,90 @@ - const axios = require('axios'); const apiUrl = 'https://api.cloudflare.com/client/v4'; // Endpoint -async function fetchCloudflareZones(apiToken) { - try { +class CloudFlare { + constructor(config) { + this.config = config ? config : {}; - // Effettua una richiesta GET all'API di Cloudflare - const response = await axios.get(apiUrl + '/zones', { - headers: { - 'Authorization': `Bearer ${apiToken}`, // Autenticazione con token - 'Content-Type': 'application/json' // Tipo di contenuto - } - }); + if (!this.config.arrTokens) { + this.config.arrTokens = process.env.CLOUDFLARE_TOKENS; + } + } - // Estrai i dati dalla risposta - const zones = response.data.result; + init() { + if (this.config.arrTokens) { + // this.zones = this.fetchCloudflareZones(this.config.apiToken); + this.zones = []; + this.dnsRecords = null; + } + } - // Stampa le zone - // console.log('Zone di Cloudflare:', zones); - } catch (error) { - console.error('Errore durante il recupero delle zone di Cloudflare:', error.message); + async fetchCloudflareZones(apiToken) { + try { + + // Effettua una richiesta GET all'API di Cloudflare + const response = await axios.get(apiUrl + '/zones', { + headers: { + 'Authorization': `Bearer ${apiToken}`, // Autenticazione con token + 'Content-Type': 'application/json' // Tipo di contenuto + } + }); + + // Estrai i dati dalla risposta + this.zones = response.data.result; + + return this.zones; + + // Stampa le zone + // console.log('Zone di Cloudflare:', zones); + } catch (error) { + console.error('Errore durante il recupero delle zone di Cloudflare:', error.message); + } + } + + // Funzione per estrarre i record DNS + async fetchDNSRecords(apiToken, zoneId) { + const apiUrlDNS = apiUrl + `/zones/${zoneId}/dns_records`; + + try { + const response = await axios.get(apiUrlDNS, { + headers: { + 'Authorization': `Bearer ${apiToken}`, // Autenticazione con token + 'Content-Type': 'application/json' // Tipo di contenuto + } + }); + + this.dnsRecords = response.data.result; + + return this.dnsRecords; + } catch (error) { + console.error('Errore durante il recupero dei record DNS di Cloudflare:', error.message); + } + } + + // Funzione per aggiornare un record DNS + async updateDNSRecord(apiToken, zoneId, dnsRecordId, newDnsRecordData) { + const apiUrlDNS = apiUrl + `/zones/${zoneId}/dns_records/${dnsRecordId}`; + + try { + + const response = await axios.put(apiUrlDNS, newDnsRecordData, { + headers: { + 'Authorization': `Bearer ${apiToken}`, // Autenticazione con token + 'Content-Type': 'application/json' // Tipo di contenuto + } + }); + + const updatedRecord = response.data.result; + + // Stampa il record DNS aggiornato + console.log('Record DNS aggiornato:', updatedRecord); + + return updatedRecord; + } catch (error) { + console.error('Errore durante l\'aggiornamento del record DNS:', error.message); + } } } -// Funzione per estrarre i record DNS -async function fetchDNSRecords(apiToken, zoneId) { - const apiUrlDNS = apiUrl + `/zones/${zoneId}/dns_records`; - - try { - const response = await axios.get(apiUrlDNS, { - headers: { - 'Authorization': `Bearer ${apiToken}`, // Autenticazione con token - 'Content-Type': 'application/json' // Tipo di contenuto - } - }); - - const dnsRecords = response.data.result; - - return dnsRecords; - } catch (error) { - console.error('Errore durante il recupero dei record DNS di Cloudflare:', error.message); - } -} - -// Funzione per aggiornare un record DNS -async function updateDNSRecord(apiToken, zoneId, dnsRecordId, newDnsRecordData) { - const apiUrlDNS = apiUrl + `/zones/${zoneId}/dns_records/${dnsRecordId}`; - - try { - const response = await axios.put(apiUrlDNS, newDnsRecordData, { - headers: { - 'Authorization': `Bearer ${apiToken}`, // Autenticazione con token - 'Content-Type': 'application/json' // Tipo di contenuto - } - }); - - const updatedRecord = response.data.result; - - // Stampa il record DNS aggiornato - console.log('Record DNS aggiornato:', updatedRecord); - } catch (error) { - console.error('Errore durante l\'aggiornamento del record DNS:', error.message); - } -} \ No newline at end of file +module.exports = CloudFlare \ No newline at end of file diff --git a/src/server/router/admin_router.js b/src/server/router/admin_router.js index 4d89251..fcba8ba 100755 --- a/src/server/router/admin_router.js +++ b/src/server/router/admin_router.js @@ -1193,4 +1193,47 @@ router.post('/exec', authenticate, async (req, res) => { }); +router.post('/cloudflare', authenticate, async (req, res) => { + try { + idapp = req.body.idapp; + cmd = req.body.cmd; + tok = req.body.tok; + zoneId = req.body.zoneId; + tokcheck = req.body.tokcheck; + dnsRecordId = req.body.dnsRecordId; + record = req.body.record; + console.log('/cloudflare idapp=', idapp, req.body.script); + + const CloudFlareClass = require('../modules/Cloudflare.js'); + + const TOKCHECK = 'php8.1_version_762321HSD121nJDokq@?!aFS.tar.gz' + + if (!User.isAdmin(req.user.perm) || (tokcheck !== TOKCHECK)) { + // If without permissions, exit + return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' }); + } + + let result = ''; + + let cf = new CloudFlareClass(null); + cf.init(); + + if (cmd === "getzones") { + result = await cf.fetchCloudflareZones(tok); + } else if (cmd === "getDNS") { + result = await cf.fetchDNSRecords(tok, zoneId); + } else if (cmd === "setRecordDNS") { + result = await cf.updateDNSRecord(tok, zoneId, dnsRecordId, record); + } else if (cmd === "gettok") { + result = JSON.parse(process.env.CLOUDFLARE_TOKENS); + } + + return res.send(result); + } catch (e) { + console.error('e', e); + return res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: '' }); + } + +}); + module.exports = router; diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js index 669a2b9..407cb6e 100755 --- a/src/server/router/index_router.js +++ b/src/server/router/index_router.js @@ -662,7 +662,7 @@ router.post('/gettable', authenticate, (req, res) => { let params = req.body; params.table = sanitizeHtml(params.table); - + let idapp = req.user ? req.user.idapp : sanitizeHtml(params.idapp); const mytable = globalTables.getTableByTableName(params.table); //console.log('mytable', mytable); @@ -1402,7 +1402,7 @@ router.get('/loadsite/:userId/:idapp/:vers', authenticate_noerror, }); function load(req, res, version) { - + const userId = req.params.userId; const idapp = req.params.idapp; @@ -1410,7 +1410,7 @@ function load(req, res, version) { if (req.code === server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED) { status = server_constants.RIS_CODE_HTTP_FORBIDDEN_TOKEN_EXPIRED } - + if (!version) { version = '0'; @@ -1890,9 +1890,10 @@ function uploadFile(req, res, version) { // console.log('fromfile', fromfile) // console.log('tofile', tofile); + if (!tools.sulServer()) { console.log('Dovresti copiare fromfile', fromfile, 'tofile', tofile); - console.log('cp ', fromfile, tofile); + await tools.execScriptNoOutput('sudo cp -R ' + fromfile + ' ' + tofile) res.end(); return; } diff --git a/src/server/server.js b/src/server/server.js index 5581277..db671be 100755 --- a/src/server/server.js +++ b/src/server/server.js @@ -17,8 +17,6 @@ var http = require('http'); const WebSocket = require('ws'); const { spawn } = require('child_process'); -const pty = require('node-pty'); - const NUOVO_METODO_TEST = true; const METODO_MULTI_CORS = false; @@ -283,6 +281,9 @@ async function mystart() { // await estraiTutteLeImmagini(); + console.log('Versione Server: ' + await tools.getVersServer()); + + await tools.getApps(); if (process.env.PROD !== 1) { @@ -716,11 +717,6 @@ async function faitest() { } } -/*const domains = [ - { hostname: 'piuchebuono.app', port: 3000 }, - { hostname: 'gruppomacro.app', port: 3010 }, -];*/ - function getCredentials(hostname) { if (NUOVO_METODO_TEST) { @@ -801,6 +797,8 @@ function startServer(app, port) { let httpsServer = null; let httpServer = null; + console.log('isProduction', isProduction); + if (isProduction) { for (let i = 0; i < domains.length; i++) { const credentials = getCredentials(domains[i].hostname); @@ -859,82 +857,98 @@ function startServer(app, port) { // process.exit(1); } - wss.on('connection', (ws) => { - // console.log('Client connected'); - let scriptProcess = null; + if (wss) { - ws.on('message', (message) => { - const parsedMessage = JSON.parse(message); + wss.on('connection', (ws) => { + console.log('Client socket connected...'); - if (parsedMessage.type === 'start_script') { - if (scriptProcess) { - scriptProcess.kill(); - } + const { User } = require('./models/user'); - const scriptPath = path.join(__dirname, '..', '..', '', parsedMessage.scriptName); + let scriptProcess = null; - // 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 - }); + try { - let buffer = ''; - scriptProcess.on('data', (data) => { - buffer += data; + const pty = require('node-pty'); - // Invia l'output al client - ws.send(JSON.stringify({ type: 'output', data: data })); + ws.on('message', (message) => { + const parsedMessage = JSON.parse(message); - // Controlla se c'è una richiesta di input - if (buffer.endsWith(': ') || buffer.includes('? ') || - buffer.toLowerCase().includes('password') - || buffer.includes('Inserisci') - || buffer.includes('Inserted') - || buffer.includes('(Y') - ) { - ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() })); - buffer = ''; + if ((parsedMessage.type === 'start_script') && (User.isAdminById(parsedMessage.user_id))) { + if (scriptProcess) { + scriptProcess.kill(); } - // Pulisci il buffer se diventa troppo grande - if (buffer.length > 5024) { - buffer = buffer.slice(-500); - } - }); + const scriptPath = path.join(__dirname, '..', '..', '', parsedMessage.scriptName); - scriptProcess.on('exit', (code) => { - if (code === 0) { - ws.send(JSON.stringify({ type: 'close', data: `*** FINE SCRIPT ***` })); + // 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 + }); + + 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.endsWith(': ') || buffer.includes('? ') || + buffer.toLowerCase().includes('password') + || buffer.includes('Inserisci') + || buffer.includes('Inserted') + || buffer.includes('(Y') + ) { + 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 { - ws.send(JSON.stringify({ type: 'close', data: `Script terminato con codice ${code}` })); + ws.send(JSON.stringify({ type: 'error', data: 'Script non trovato o non autorizzato' })); } - }); - } else { - ws.send(JSON.stringify({ type: 'error', data: 'Script non trovato o non autorizzato' })); - } - } else if (parsedMessage.type === 'input') { - if (scriptProcess) { - scriptProcess.write(parsedMessage.data + '\n'); - } + } else if (parsedMessage.type === 'input') { + if (scriptProcess) { + scriptProcess.write(parsedMessage.data + '\n'); + } + } + }); + + ws.on('close', () => { + console.log('*** Client socket disconnected'); + if (scriptProcess) { + scriptProcess.kill(); + } + }); + } catch (error) { + console.error('connection: Errore durante l\'inizializzazione del WebSocket, error:', error.message); } }); - ws.on('close', () => { - console.log('Client disconnected'); - if (scriptProcess) { - scriptProcess.kill(); - } - }); - }); + } else { + console.error('Nessuna Socket Aperta con WebSocket !!'); + } } catch (e) { - console.log('error ' + e); + console.log('error startServer: ' + e); } } diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js index f370690..bb6ba8a 100755 --- a/src/server/telegram/telegrambot.js +++ b/src/server/telegram/telegrambot.js @@ -2486,8 +2486,13 @@ class Telegram { file = '~/batch/test_restart_server.sh'; } - const ris = await tools.execScriptByTelegram(this.idapp, msg, file, - this.chisono(rec) + ' Restart il Server (Node.Js) : ' + process.version); + let messaggio = this.chisono(rec) + ' Restart il Server (Node.Js) : ' + process.version; + + messaggio += '\nVersione Server: ' + await tools.getVersServer(); + + const ris = await tools.execScriptByTelegram(this.idapp, msg, file, messaggio); + + } else { this.nonAbilitato(msg); } diff --git a/src/server/tools/general.js b/src/server/tools/general.js index 9c55dc0..eb3ebf8 100755 --- a/src/server/tools/general.js +++ b/src/server/tools/general.js @@ -1861,9 +1861,9 @@ module.exports = { this.MYAPPS.find(item => item.idapp === idapp); if (myapp) { if (process.env.NODE_ENV === 'test') - mypath = (myapp) ? myapp.dir_test : ''; + mypath = (myapp && myapp.dir_test) ? myapp.dir_test : ''; else - mypath = (myapp) ? myapp.dir : ''; + mypath = (myapp && myapp.dir) ? myapp.dir : ''; if (dirmain) { if (!this.sulServer()) { @@ -3812,15 +3812,30 @@ module.exports = { }, - readlogfile(idapp, filename) { + async readlogfile(idapp, filename) { try { - return fs.readFileSync(idapp + '/' + filename, 'utf8'); + return await fs.readFileSync(idapp + '/' + filename, 'utf8'); } catch (e) { return ''; } }, + async readfilecontent(filename) { + + try { + const cont = await fs.readFileSync(filename, 'utf8'); + return cont; + } catch (e) { + return ''; + } + }, + + async getVersServer() { + return await this.readfilecontent(__dirname + '/../version.txt'); + }, + + writelog(mystr) { this.writelogfile(mystr, FILELOG); }, @@ -3852,11 +3867,6 @@ module.exports = { this.writelogfile(mystr, idapp + '/' + riga + '_' + col + '.txt'); }, - readFlottaLog(idapp, riga, col) { - const nomefile = riga + '_' + col + '.txt'; - return this.readlogfile(idapp, nomefile); - }, - writeNaveLog(mystr) { this.writelogfile(mystr, FILENAVE); }, @@ -4507,6 +4517,7 @@ module.exports = { for (let i = 0; i < arrscripts.length; i++) { let label = arrscripts[i]; + let sock = false; let description = ''; if (listafiles) { if (arrscripts[i].endsWith('.sh')) { @@ -4537,6 +4548,8 @@ module.exports = { label = value; } else if (paramstr === 'DESCRIZ') { description = value; + } else if (paramstr === 'SOCK') { + sock = (value.toLowerCase() === 'true'); } } @@ -4551,7 +4564,7 @@ module.exports = { } if ((label) && (!extfiles || (extfiles && arrscripts[i].endsWith('.' + extfiles)))) { - arrout.push({ label, value: arrscripts[i], description }); + arrout.push({ label, value: arrscripts[i], description, sock }); } } @@ -4559,6 +4572,20 @@ module.exports = { }); }); }, + execScriptNoOutput: async function (script) { + return new Promise(async (resolve, reject) => { + console.log('execScriptNoOutput:', script); + exec(script, async (error, stdout, stderr) => { // Aggiunto async qui + if (error) { + console.error(`error: ${error}`); + } + if (stderr) { + console.error(`stderr: ${stderr}`); + } + resolve(!error && !stderr); + }); + }); + }, execScriptWithInputOnServer: async function (idapp, script) { return new Promise((resolve, reject) => { diff --git a/src/server/version.txt b/src/server/version.txt new file mode 100644 index 0000000..3c79fcb --- /dev/null +++ b/src/server/version.txt @@ -0,0 +1 @@ +1.0.56 \ No newline at end of file