Cataloghi...

This commit is contained in:
Surya Paolo
2025-02-05 12:13:27 +01:00
parent 41d5f562ec
commit 2f92dfe5b0
13 changed files with 498 additions and 458 deletions

View File

@@ -42,13 +42,13 @@ const CatalogSchema = new Schema({
type: String, type: String,
}, },
foto_collana: Foto, foto_collana: Foto,
idCollana: { idCollane: [{
type: String, type: Number,
}, }],
descr_introduttiva: { descr_introduttiva: {
type: String, type: String,
}, },
idTemplateScheda: { idPageAssigned: {
type: String, type: String,
}, },
referenti: [{ referenti: [{
@@ -92,9 +92,24 @@ CatalogSchema.statics.executeQueryTable = function (idapp, params, user) {
CatalogSchema.statics.findAllIdApp = async function (idapp) { CatalogSchema.statics.findAllIdApp = async function (idapp) {
const Catalog = this; const Catalog = this;
const myfind = { idapp }; const arrrec = await Catalog.aggregate([
// Filtra i documenti per idapp
{ $match: { idapp } },
const arrrec = await Catalog.find(myfind).lean().sort({ title: 1 }); // Ordina i risultati per titolo
{ $sort: { title: 1 } },
// Esegui il join con la collezione Collana
{
$lookup: {
from: "collanas", // Nome della collezione Collana
localField: "idCollane", // Campo in Catalog
foreignField: "idCollana", // Campo in Collana
as: "collana_info" // Nome del campo che conterrà i risultati del join
}
},
]);
return arrrec; return arrrec;
}; };

View File

@@ -18,10 +18,7 @@ const CollanaSchema = new Schema({
idCollana: { idCollana: {
type: Number, type: Number,
}, },
descrizione: { title: {
type: String,
},
descrizione_estesa: {
type: String, type: String,
}, },
dataOra: { dataOra: {

View File

@@ -60,7 +60,7 @@ const catalogo = new Schema(
excludeproductTypes: [{ type: Number }], excludeproductTypes: [{ type: Number }],
editore: [{ type: String }], editore: [{ type: String }],
argomenti: [{ type: String }], argomenti: [{ type: String }],
idCollana: { type: Number }, idCollane: [{ type: Number }],
sort_field: { type: String }, sort_field: { type: String },
sort_dir: { type: Number }, sort_dir: { type: Number },
pdf: { type: Boolean }, pdf: { type: Boolean },
@@ -361,7 +361,21 @@ MyElemSchema.statics.findAllIdApp = async function (idapp) {
const myfind = { idapp }; const myfind = { idapp };
const arrrec = await MyElem.find(myfind).lean().sort({ order: 1 }); const aggiorna = false;
let arrrec = null;
if (aggiorna) {
arrrec = await MyElem.find(myfind).sort({ order: 1 });
for (const elem of arrrec) {
if (elem.heightimg === 'NaNpx') {
elem.heightimg = '';
await elem.save();
}
}
} else {
arrrec = await MyElem.find(myfind).lean().sort({ order: 1 });
}
return arrrec; return arrrec;
}; };
@@ -374,13 +388,13 @@ MyElemSchema.statics.findallSchedeTemplate = async function (idapp) {
const ris = await MyElem.find({ idapp }).lean(); const ris = await MyElem.find({ idapp }).lean();
const schedeTemplate = ris.flatMap(elem => const schedeTemplate = ris.flatMap(elem =>
elem.catalogo && elem.catalogo.arrSchede ? elem.catalogo && elem.catalogo.arrSchede ?
elem.catalogo.arrSchede elem.catalogo.arrSchede
.filter(scheda => scheda.scheda?.isTemplate) .filter(scheda => scheda.scheda?.isTemplate)
.map(scheda => ({ .map(scheda => ({
...scheda, // mantieni i dati originali della scheda ...scheda, // mantieni i dati originali della scheda
idPageOrig: elem.idPage // aggiungi l'idPage idPageOrig: elem.idPage // aggiungi l'idPage
})) }))
: [] : []
); );

View File

@@ -130,7 +130,7 @@ const scheletroScheda = {
excludeproductTypes: [{ type: Number }], excludeproductTypes: [{ type: Number }],
editore: [{ type: String }], editore: [{ type: String }],
argomenti: [{ type: String }], argomenti: [{ type: String }],
idCollana: { type: Number }, idCollane: [{ type: Number }],
author: { type: String }, author: { type: String },
sort_field: { type: String }, sort_field: { type: String },
sort_dir: { type: Number }, sort_dir: { type: Number },

View File

@@ -870,6 +870,9 @@ UserSchema.statics.findByCredentials = function (idapp, username, password, pwdc
UserSchema.statics.findByUsername = async function (idapp, username, alsoemail, onlyifVerifiedByAportador) { UserSchema.statics.findByUsername = async function (idapp, username, alsoemail, onlyifVerifiedByAportador) {
const User = this; const User = this;
if (!username)
return null;
const myreg = ['^', username, '$'].join(''); const myreg = ['^', username, '$'].join('');
let regexusername = new RegExp(myreg, 'i'); let regexusername = new RegExp(myreg, 'i');

View File

@@ -1,189 +1,189 @@
const {ObjectId} = require('mongodb'); const { ObjectId } = require('mongodb');
module.exports = { module.exports = {
list: [ list: [
{ {
"_id" : ObjectId("615a353c002c8298f4495be7"), "_id": ObjectId("615a353c002c8298f4495be7"),
"idapp" : "1", "idapp": "1",
"label" : "Dono", "label": "Dono",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc466567de9a1f54b25494"), "_id": ObjectId("61bc466567de9a1f54b25494"),
"idapp" : "1", "idapp": "1",
"label" : "Offerta Libera", "label": "Offerta Libera",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc454867de9a1f54b25462"), "_id": ObjectId("61bc454867de9a1f54b25462"),
"idapp" : "1", "idapp": "1",
"label" : "Baratto (scambio Beni o Servizi)", "label": "Baratto (scambio Beni o Servizi)",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc482667de9a1f54b2549c"), "_id": ObjectId("61bc482667de9a1f54b2549c"),
"idapp" : "1", "idapp": "1",
"label" : "Scambio Lavoro", "label": "Scambio Lavoro",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc482667de9a1f54b2649c"), "_id": ObjectId("61bc482667de9a1f54b2649c"),
"idapp" : "1", "idapp": "1",
"label" : "Monete Alternative", "label": "Monete Alternative",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc482667de9a1f54b3549e"), "_id": ObjectId("61bc482667de9a1f54b3549e"),
"idapp" : "1", "idapp": "1",
"label" : "Euro", "label": "Euro",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("615a353c002c8298f4495bf7"), "_id": ObjectId("615a353c002c8298f4495bf7"),
"idapp" : "12", "idapp": "12",
"label" : "Dono", "label": "Dono",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc466567de9a1f54b254f4"), "_id": ObjectId("61bc466567de9a1f54b254f4"),
"idapp" : "12", "idapp": "12",
"label" : "Offerta Libera", "label": "Offerta Libera",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc454867de9a1f54b254f2"), "_id": ObjectId("61bc454867de9a1f54b254f2"),
"idapp" : "12", "idapp": "12",
"label" : "Baratto", "label": "Baratto",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc482667de9a1f54b25412"), "_id": ObjectId("61bc482667de9a1f54b25412"),
"idapp" : "12", "idapp": "12",
"label" : "Scambio Lavoro", "label": "Scambio Lavoro",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc482667de9a1f64b254ab"), "_id": ObjectId("61bc482667de9a1f64b254ab"),
"idapp" : "12", "idapp": "12",
"label" : "Monete Alternative", "label": "Monete Alternative",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("61bc482667de9a1f64b254fb"), "_id": ObjectId("61bc482667de9a1f64b254fb"),
"idapp" : "12", "idapp": "12",
"label" : "Euro", "label": "Euro",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("5dbc6b0801234f629f75e98d"), "_id": ObjectId("5dbc6b0801234f629f75e98d"),
"idapp" : "2", "idapp": "2",
"__v" : 0, "__v": 0,
"label" : "Offerta Libera" "label": "Offerta Libera"
}, },
/* 2 */ /* 2 */
{ {
"_id" : ObjectId("5dbc6b1001234f629f75e98e"), "_id": ObjectId("5dbc6b1001234f629f75e98e"),
"idapp" : "2", "idapp": "2",
"__v" : 0, "__v": 0,
"label" : "Ingresso Gratuito" "label": "Ingresso Gratuito"
}, },
/* 3 */ /* 3 */
{ {
"_id" : ObjectId("5dbc6b1801234f629f75e98f"), "_id": ObjectId("5dbc6b1801234f629f75e98f"),
"idapp" : "2", "idapp": "2",
"__v" : 0, "__v": 0,
"label" : "Contributo", "label": "Contributo",
"showprice" : true "showprice": true
}, },
/* 4 */ /* 4 */
{ {
"_id" : ObjectId("5dbc6b3001234f629f75e990"), "_id": ObjectId("5dbc6b3001234f629f75e990"),
"idapp" : "2", "idapp": "2",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("602c315137d9f0738ded312f"), "_id": ObjectId("602c315137d9f0738ded312f"),
"idapp" : "10", "idapp": "10",
"__v" : 0, "__v": 0,
"label" : "Contributo", "label": "Contributo",
"showprice" : true "showprice": true
}, },
/* 7 */ /* 7 */
{ {
"_id" : ObjectId("602c316037d9f0738ded3132"), "_id": ObjectId("602c316037d9f0738ded3132"),
"idapp" : "10", "idapp": "10",
"__v" : 0, "__v": 0,
"label" : "Gratuito" "label": "Gratuito"
}, },
/* 8 */ /* 8 */
{ {
"_id" : ObjectId("60514b3f733ce468d09366f2"), "_id": ObjectId("60514b3f733ce468d09366f2"),
"idapp" : "10", "idapp": "10",
"__v" : 0, "__v": 0,
"label" : "Evento ONLINE Gratuito" "label": "Evento ONLINE Gratuito"
}, },
{ {
"_id" : ObjectId("515a353c002c8298f4495bf7"), "_id": ObjectId("515a353c002c8298f4495bf7"),
"idapp" : "13", "idapp": "13",
"label" : "Dono", "label": "🎁 Dono",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("51bc466567de9a1f54b254f4"), "_id": ObjectId("51bc466567de9a1f54b254f4"),
"idapp" : "13", "idapp": "13",
"label" : "Offerta Libera", "label": "💸 Offerta Libera",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("51bc454867de9a1f54b254f2"), "_id": ObjectId("51bc454867de9a1f54b254f2"),
"idapp" : "13", "idapp": "13",
"label" : "Baratto", "label": "🤝 Baratto",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("51bc482667de9a1f54b25412"), "_id": ObjectId("51bc482667de9a1f54b25412"),
"idapp" : "13", "idapp": "13",
"label" : "Scambio Lavoro", "label": "💪 Scambio Lavoro",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("51bc482667de9a1f64b254ab"), "_id": ObjectId("51bc482667de9a1f64b254ab"),
"idapp" : "13", "idapp": "13",
"label" : "Monete Alternative", "label": "🪙 Monete Alternative",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("51bc482667de9a1f64b254ac"), "_id": ObjectId("51bc482667de9a1f64b254ac"),
"idapp" : "13", "idapp": "13",
"label" : "RIS", "label": "🍚 RIS",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("51bc482667de9a1f64b254fb"), "_id": ObjectId("51bc482667de9a1f64b254fb"),
"idapp" : "13", "idapp": "13",
"label" : "Euro", "label": "💶 Euro",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("51bc482667de9a1f64b254ff"), "_id": ObjectId("51bc482667de9a1f64b254ff"),
"idapp" : "13", "idapp": "13",
"label" : "Bitcoin", "label": "Bitcoin",
"__v" : 0 "__v": 0
}, },
{ {
"_id" : ObjectId("51bc482667de9a1f64b255ff"), "_id": ObjectId("51bc482667de9a1f64b255ff"),
"idapp" : "13", "idapp": "13",
"label" : "Banca del Tempo", "label": "Banca del Tempo",
"__v" : 0 "__v": 0
}, }
] ]
} }

View File

@@ -776,7 +776,6 @@ router.post('/import', authenticate, async (req, res) => {
let imported = 0; let imported = 0;
let errors = 0; let errors = 0;
const ripopola = true; const ripopola = true;
if (ripopola) { if (ripopola) {
@@ -901,7 +900,8 @@ router.post('/import', authenticate, async (req, res) => {
} }
// Aggiorna la collana solo se non è stata già impostata nel record attuale // Aggiorna la collana solo se non è stata già impostata nel record attuale
if (recproductInfoAttuale && !recproductInfoAttuale.idCollana && product.DescrizioneCollana) { //if (recproductInfoAttuale && !recproductInfoAttuale.idCollana && product.DescrizioneCollana) {
if (recproductInfoAttuale && product.DescrizioneCollana) {
const idCollanaNum = parseInt(product.IdCollana) const idCollanaNum = parseInt(product.IdCollana)
productInfo.idCollana = idCollanaNum; productInfo.idCollana = idCollanaNum;
@@ -909,7 +909,7 @@ router.post('/import', authenticate, async (req, res) => {
if (!reccollana) { if (!reccollana) {
try { try {
// Non esiste questa collana, quindi la creo ! // Non esiste questa collana, quindi la creo !
reccoll = new Collana({ idapp, idCollana: idCollanaNum, descrizione: product.DescrizioneCollana }); reccoll = new Collana({ idapp, idCollana: idCollanaNum, title: product.DescrizioneCollana });
ris = await reccoll.save(); ris = await reccoll.save();
} catch (e) { } catch (e) {
console.error('Err', e); console.error('Err', e);

View File

@@ -220,58 +220,65 @@ router.post(process.env.LINK_REQUEST_NEWPASSWORD, async (req, res) => {
// Invio la Nuova Password richiesta dal reset! // Invio la Nuova Password richiesta dal reset!
// Ritorna il token per poter effettuare le chiamate... // Ritorna il token per poter effettuare le chiamate...
router.post(process.env.LINK_UPDATE_PWD, async (req, res) => { router.post(process.env.LINK_UPDATE_PWD, async (req, res) => {
const body = _.pick(req.body, ['idapp', 'email', 'tokenforgot', 'tokenforgot_code', 'password']);
const idapp = body.idapp; try {
const email = body.email.toLowerCase().trim(); const body = _.pick(req.body, ['idapp', 'email', 'tokenforgot', 'tokenforgot_code', 'password']);
const tokenforgot = body.tokenforgot; const idapp = body.idapp;
const tokenforgot_code = body.tokenforgot_code; const email = body.email.toLowerCase().trim();
const password = body.password; const tokenforgot = body.tokenforgot;
const msg = 'Richiesta Nuova Password: idapp= ' + idapp + ' email = ' + email; const tokenforgot_code = body.tokenforgot_code;
console.log(msg); const password = body.password;
const msg = 'Richiesta Nuova Password: idapp= ' + idapp + ' email = ' + email;
console.log(msg);
// telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg); // telegrambot.sendMsgTelegramToTheManagers(body.idapp, msg);
let user = null; let user = null;
user = await User.findByLinkTokenforgot(idapp, email, tokenforgot) user = await User.findByLinkTokenforgot(idapp, email, tokenforgot)
.then((user) => {
return user;
}).catch((e) => {
console.log(process.env.LINK_UPDATE_PWD, e.message);
res.status(400).send();
});
if (!user) {
user = await User.findByLinkTokenforgotCode(idapp, email, tokenforgot_code)
.then((user) => { .then((user) => {
return user; return user;
}).catch((e) => { }).catch((e) => {
console.log(process.env.LINK_UPDATE_PWD, e.message); console.log(process.env.LINK_UPDATE_PWD, e.message);
res.status(400).send(); res.status(400).send();
}); });
}
if (!user) { if (!user) {
return res.send( user = await User.findByLinkTokenforgotCode(idapp, email, tokenforgot_code)
{ code: server_constants.RIS_CODE_TOKEN_RESETPASSWORD_NOT_FOUND }); .then((user) => {
} else { return user;
// aggiorna la nuova password }).catch((e) => {
user.password = password; console.log(process.env.LINK_UPDATE_PWD, e.message);
user.lasttimeonline = new Date(); res.status(400).send();
});
}
// Crea token if (!user) {
user.generateAuthToken(req).then(ris => { return res.send(
user.tokenforgot = ''; // Svuota il tokenforgot perché non ti servirà più... { code: server_constants.RIS_CODE_TOKEN_RESETPASSWORD_NOT_FOUND });
user.tokenforgot_code = ''; // Svuota il tokenforgot perché non ti servirà più... } else {
// aggiorna la nuova password
user.password = password;
user.lasttimeonline = new Date();
// Salva lo User // Crea token
user.save().then(() => { user.generateAuthToken(req).then(ris => {
res.header('x-auth', ris.token) user.tokenforgot = ''; // Svuota il tokenforgot perché non ti servirà più...
.header('x-refrtok', ris.refreshToken) user.tokenforgot_code = ''; // Svuota il tokenforgot perché non ti servirà più...
.send({ code: server_constants.RIS_CODE_OK }); // Ritorna il token di ritorno
// Salva lo User
user.save().then(() => {
res.header('x-auth', ris.token)
.header('x-refrtok', ris.refreshToken)
.send({ code: server_constants.RIS_CODE_OK }); // Ritorna il token di ritorno
});
}); });
}); }
} catch (e) {
console.error('Error: ', e);
} }
}); });
router.post('/testServer', authenticate_noerror, async (req, res) => { router.post('/testServer', authenticate_noerror, async (req, res) => {

View File

@@ -87,308 +87,313 @@ router.post('/test1', async (req, res) => {
// POST /users // POST /users
router.post('/', async (req, res) => { router.post('/', async (req, res) => {
tools.mylog('POST /users'); try {
const body = _.pick(req.body, [ tools.mylog('POST /users');
'email', const body = _.pick(req.body, [
'password', 'email',
'username', 'password',
'group', 'username',
'name', 'group',
'surname', 'name',
'idapp', 'surname',
'keyappid', 'idapp',
'lang', 'keyappid',
'profile', 'lang',
'aportador_solidario']); 'profile',
body.email = body.email.toLowerCase(); 'aportador_solidario']);
body.email = body.email.toLowerCase();
const user = new User(body); const user = new User(body);
user.ipaddr = tools.getiPAddressUser(req); user.ipaddr = tools.getiPAddressUser(req);
user.email = user.email.trim(); user.email = user.email.trim();
user.username = user.username.trim(); user.username = user.username.trim();
user.name = user.name.trim(); user.name = user.name.trim();
user.surname = user.surname.trim(); user.surname = user.surname.trim();
if ((user.aportador_solidario === 'tuo_username') || (user.aportador_solidario === '{username}')) { if ((user.aportador_solidario === 'tuo_username') || (user.aportador_solidario === '{username}')) {
user.aportador_solidario = 'paoloar77'; user.aportador_solidario = 'paoloar77';
}
// tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp);
if (!tools.isAlphaNumericAndSpecialCharacter(body.username) ||
body.email.length < 6 ||
body.username.length < 4 || body.password.length < 5) {
await tools.snooze(5000);
console.log('Username non valido in Registrazione: ' + body.username);
res.status(400).
send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' });
return 1;
}
if (tools.blockwords(body.username) || tools.blockwords(body.name) ||
tools.blockwords(body.surname)) {
// tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname);
await tools.snooze(5000);
return res.status(404).send();
}
user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username);
user.verified_email = false;
user.lasttimeonline = new Date();
user.date_reg = new Date();
user.aportador_iniziale = user.aportador_solidario;
let regexpire = req.body['regexpire'];
let nonchiedereverifica = false;
if (regexpire) {
nonchiedereverifica = await User.getifRegTokenIsValid(body.idapp, regexpire);
}
if (!nonchiedereverifica)
regexpire = '';
if (!tools.getAskToVerifyReg(body.idapp) || nonchiedereverifica) {
// Se non devo chiedere di verificare all'Invitato, allora lo verifico direttamente
user.verified_by_aportador = true;
}
/* if (user.idapp === tools.AYNI) {
user.profile.paymenttypes = ['paypal'];
} */
// Controlla se anche l'ultimo record era dallo stesso IP:
const lastrec = await User.getLastRec(body.idapp);
if (!!lastrec) {
if (process.env.LOCALE !== '1') {
if (lastrec.ipaddr === user.ipaddr) {
// Se l'ha fatto troppo ravvicinato
if (lastrec.date_reg) {
let ris = tools.isdiffSecDateLess(lastrec.date_reg, 3);
if (ris) {
const msg = user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' +
user.surname;
tools.writeIPToBan(msg);
await User.findOneAndUpdate({ _id: user._id }, { $set: { banIp: true } });
await telegrambot.sendMsgTelegramToTheAdmin(body.idapp, '‼️ BAN: ' + msg, true);
await tools.snooze(5000);
res.status(400).
send({ code: server_constants.RIS_CODE_BANIP, msg: '' });
return 1;
}
}
}
} }
}
// user.perm = 3; // tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp);
// if (tools.testing()) {
// user.verified_email = true;
// }
// if (user.profile.intcode_cell) { if (!tools.isAlphaNumericAndSpecialCharacter(body.username) ||
// if (user.profile.cell.substring(0, user.profile.intcode_cell.length) === user.profile.intcode_cell) { body.email.length < 6 ||
// user.profile.cell = user.profile.cell.substring(user.profile.intcode_cell.length) body.username.length < 4 || body.password.length < 5) {
// } await tools.snooze(5000);
// } console.log('Username non valido in Registrazione: ' + body.username);
let exit;
let utentenonancoraVerificato = false;
const trovarec = await User.findByCredentials(user.idapp, user.username, user.password, true);
// Check if already esist email or username
exit = await User.findByUsername(user.idapp, user.username).
then((useralreadyexist) => {
if (useralreadyexist) {
if (tools.getAskToVerifyReg(useralreadyexist.idapp)) {
if (!useralreadyexist.verified_by_aportador && useralreadyexist.profile.teleg_id > 0) {
if (trovarec) {
utentenonancoraVerificato = true;
}
}
}
if (!utentenonancoraVerificato) {
res.status(400).
send({
code: server_constants.RIS_CODE_USERNAME_ALREADY_EXIST,
msg: '',
});
return 1;
}
}
});
if (!utentenonancoraVerificato) {
if (exit === 1)
return;
exit = await User.findByEmail(user.idapp, user.email).
then((useralreadyexist) => {
if (useralreadyexist) {
res.status(400).
send({
code: server_constants.RIS_CODE_EMAIL_ALREADY_EXIST,
msg: '',
});
return 1;
}
});
if (exit === 1)
return;
let recuser = null;
recuser = await User.findByCellAndNameSurname(user.idapp, user.profile.cell,
user.name, user.surname);
if (recuser && user.name !== '' && user.surname !== '' &&
user.profile.cell !== '') {
console.log('UTENTE GIA ESISTENTE:\n');
console.log(user);
// User already registered!
res.status(400). res.status(400).
send({ code: server_constants.RIS_CODE_USER_ALREADY_EXIST, msg: '' }); send({ code: server_constants.RIS_CODE_USERNAME_NOT_VALID, msg: '' });
return 1; return 1;
} }
} if (tools.blockwords(body.username) || tools.blockwords(body.name) ||
tools.blockwords(body.surname)) {
let recextra = null; // tools.writeIPToBan(user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' + user.surname);
await tools.snooze(5000);
user.aportador_solidario = user.aportador_solidario.trim(); return res.status(404).send();
user.aportador_solidario = user.aportador_solidario.replace('@', '');
let id_aportador = await User.getIdByUsername(user.idapp, user.aportador_solidario);
if (!id_aportador) {
// Cerca se esiste l'aportador solidario con l'username Telegram
const useraportador = await User.getUserByUsernameTelegram(user.idapp, user.aportador_solidario);
if (useraportador) {
id_aportador = useraportador._id;
user.aportador_solidario = useraportador.username;
} }
}
user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username);
user.verified_email = false;
user.lasttimeonline = new Date();
user.date_reg = new Date();
user.aportador_iniziale = user.aportador_solidario;
let idMyGroupSite = tools.getidMyGroupBySite(body.idapp); let regexpire = req.body['regexpire'];
user.idMyGroup = idMyGroupSite ? idMyGroupSite : ''; let nonchiedereverifica = false;
if (regexpire) {
nonchiedereverifica = await User.getifRegTokenIsValid(body.idapp, regexpire);
}
if (id_aportador) { if (!nonchiedereverifica)
// Ottiene l'username "corretto" (senza maiuscole o minuscole) regexpire = '';
user.aportador_solidario = await User.getRealUsernameByUsername(user.idapp, user.aportador_solidario);
}
if (!id_aportador && tools.getAskToVerifyReg(body.idapp)) { if (!tools.getAskToVerifyReg(body.idapp) || nonchiedereverifica) {
// Si sta tentando di registrare una persona sotto che non corrisponde! // Se non devo chiedere di verificare all'Invitato, allora lo verifico direttamente
let msg = 'Il link di registrazione non sembra risultare valido.<br>invitante: ' + user.verified_by_aportador = true;
user.aportador_solidario + '<br>username: ' + user.username; }
await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg); /* if (user.idapp === tools.AYNI) {
res.status(400). user.profile.paymenttypes = ['paypal'];
send({ } */
code: server_constants.RIS_CODE_USER_APORTADOR_NOT_VALID,
msg: '',
});
return 1;
}
// Controlla se anche l'ultimo record era dallo stesso IP:
const lastrec = await User.getLastRec(body.idapp);
if (!!lastrec) {
if (process.env.LOCALE !== '1') {
if (lastrec.ipaddr === user.ipaddr) {
// Se l'ha fatto troppo ravvicinato
if (lastrec.date_reg) {
let ris = tools.isdiffSecDateLess(lastrec.date_reg, 3);
if (ris) {
const msg = user.ipaddr + ': [' + user.username + '] ' + user.name + ' ' +
user.surname;
tools.writeIPToBan(msg);
if (utentenonancoraVerificato) { await User.findOneAndUpdate({ _id: user._id }, { $set: { banIp: true } });
if (id_aportador) {
// Se mi sono registrato ma l'invitante non mi abilita, allora il posso registrarmi nuovamente, con lo stesso username e password,
// con un'altro link di un'altro invitante !
await User.setaportador_solidario(user.idapp, user.username,
user.aportador_solidario);
const myuser = await User.findOne({ _id: trovarec._id }); await telegrambot.sendMsgTelegramToTheAdmin(body.idapp, '‼️ BAN: ' + msg, true);
if (myuser) {
await telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser); await tools.snooze(5000);
res.status(400).
const { token, refreshToken } = await myuser.generateAuthToken(req); send({ code: server_constants.RIS_CODE_BANIP, msg: '' });
res return 1;
.header('x-auth', token) }
.header('x-refrtok', refreshToken) }
.send(myuser); }
return true;
} }
} }
}
// let already_registered = (recextra || user.aportador_solidario === tools.APORTADOR_NONE) && (user.idapp === tools.AYNI); // user.perm = 3;
// if (tools.testing()) {
// user.verified_email = true;
// }
// Check if is an other people aportador_solidario // if (user.profile.intcode_cell) {
// if (user.profile.cell.substring(0, user.profile.intcode_cell.length) === user.profile.intcode_cell) {
// user.profile.cell = user.profile.cell.substring(user.profile.intcode_cell.length)
// }
// }
let exit;
/*if (already_registered) { let utentenonancoraVerificato = false;
// Check in the extraList if is present!
const msg = 'Utente non trovato: ' + user.name + ' ' + user.surname + ' ' + user.profile.nationality + ' ' + user.profile.cell + ' email: ' + user.email + ' username: ' + user.username;
console.log('Utente non trovato; ', msg);
await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg);
res.status(400).send({
code: server_constants.RIS_CODE_USER_EXTRALIST_NOTFOUND,
msg: 'Controlla se il numero ' + user.profile.cell + ' è corretto.'
});
return 1;
} */
return user.save().then(async () => { const trovarec = await User.findByCredentials(user.idapp, user.username, user.password, true);
return User.findByUsername(user.idapp, user.username, false).
then((usertrovato) => {
// tools.mylog("TROVATO USERNAME ? ", user.username, usertrovato); // Check if already esist email or username
if (usertrovato !== null) { exit = await User.findByUsername(user.idapp, user.username).
return user.generateAuthToken(req); then((useralreadyexist) => {
} else { if (useralreadyexist) {
res.status(400).send();
return 0; if (tools.getAskToVerifyReg(useralreadyexist.idapp)) {
if (!useralreadyexist.verified_by_aportador && useralreadyexist.profile.teleg_id > 0) {
if (trovarec) {
utentenonancoraVerificato = true;
}
}
}
if (!utentenonancoraVerificato) {
res.status(400).
send({
code: server_constants.RIS_CODE_USERNAME_ALREADY_EXIST,
msg: '',
});
return 1;
}
} }
}).
then(async (ris) => {
// tools.mylog("passo il TOKEN: ", token);
if (recextra) {
recextra.registered = true;
recextra.username = user.username;
await recextra.save();
// await User.fixUsername(user.idapp, user.ind_order, user.username);
}
return ris;
}).
then(async (ris) => {
// tools.mylog("LINKREG = " + user.linkreg);
// Invia un'email all'utente
// tools.mylog('process.env.TESTING_ON', process.env.TESTING_ON);
console.log('res.locale', res.locale);
await telegrambot.askConfirmationUser(user.idapp, shared_consts.CallFunz.REGISTRATION, user, '', '', '', regexpire);
// if (!tools.testing()) {
await sendemail.sendEmail_Registration(user.lang, user.email, user,
user.idapp, user.linkreg);
// }
res
.header('x-auth', ris.token)
.header('x-refrtok', ris.refreshToken)
.send(user);
return true;
}); });
}).catch((e) => {
if (!utentenonancoraVerificato) {
if (exit === 1)
return;
exit = await User.findByEmail(user.idapp, user.email).
then((useralreadyexist) => {
if (useralreadyexist) {
res.status(400).
send({
code: server_constants.RIS_CODE_EMAIL_ALREADY_EXIST,
msg: '',
});
return 1;
}
});
if (exit === 1)
return;
let recuser = null;
recuser = await User.findByCellAndNameSurname(user.idapp, user.profile.cell,
user.name, user.surname);
if (recuser && user.name !== '' && user.surname !== '' &&
user.profile.cell !== '') {
console.log('UTENTE GIA ESISTENTE:\n');
console.log(user);
// User already registered!
res.status(400).
send({ code: server_constants.RIS_CODE_USER_ALREADY_EXIST, msg: '' });
return 1;
}
}
let recextra = null;
user.aportador_solidario = user.aportador_solidario.trim();
user.aportador_solidario = user.aportador_solidario.replace('@', '');
let id_aportador = await User.getIdByUsername(user.idapp, user.aportador_solidario);
if (!id_aportador) {
// Cerca se esiste l'aportador solidario con l'username Telegram
const useraportador = await User.getUserByUsernameTelegram(user.idapp, user.aportador_solidario);
if (useraportador) {
id_aportador = useraportador._id;
user.aportador_solidario = useraportador.username;
}
}
let idMyGroupSite = tools.getidMyGroupBySite(body.idapp);
user.idMyGroup = idMyGroupSite ? idMyGroupSite : '';
if (id_aportador) {
// Ottiene l'username "corretto" (senza maiuscole o minuscole)
user.aportador_solidario = await User.getRealUsernameByUsername(user.idapp, user.aportador_solidario);
}
if (!id_aportador && tools.getAskToVerifyReg(body.idapp)) {
// Si sta tentando di registrare una persona sotto che non corrisponde!
let msg = 'Il link di registrazione non sembra risultare valido.<br>invitante: ' +
user.aportador_solidario + '<br>username: ' + user.username;
await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg);
res.status(400).
send({
code: server_constants.RIS_CODE_USER_APORTADOR_NOT_VALID,
msg: '',
});
return 1;
}
if (utentenonancoraVerificato) {
if (id_aportador) {
// Se mi sono registrato ma l'invitante non mi abilita, allora il posso registrarmi nuovamente, con lo stesso username e password,
// con un'altro link di un'altro invitante !
await User.setaportador_solidario(user.idapp, user.username,
user.aportador_solidario);
const myuser = await User.findOne({ _id: trovarec._id });
if (myuser) {
await telegrambot.askConfirmationUser(myuser.idapp, shared_consts.CallFunz.REGISTRATION, myuser);
const { token, refreshToken } = await myuser.generateAuthToken(req);
res
.header('x-auth', token)
.header('x-refrtok', refreshToken)
.send(myuser);
return true;
}
}
}
// let already_registered = (recextra || user.aportador_solidario === tools.APORTADOR_NONE) && (user.idapp === tools.AYNI);
// Check if is an other people aportador_solidario
/*if (already_registered) {
// Check in the extraList if is present!
const msg = 'Utente non trovato: ' + user.name + ' ' + user.surname + ' ' + user.profile.nationality + ' ' + user.profile.cell + ' email: ' + user.email + ' username: ' + user.username;
console.log('Utente non trovato; ', msg);
await telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg);
res.status(400).send({
code: server_constants.RIS_CODE_USER_EXTRALIST_NOTFOUND,
msg: 'Controlla se il numero ' + user.profile.cell + ' è corretto.'
});
return 1;
} */
return user.save().then(async () => {
return User.findByUsername(user.idapp, user.username, false).
then((usertrovato) => {
// tools.mylog("TROVATO USERNAME ? ", user.username, usertrovato);
if (usertrovato !== null) {
return user.generateAuthToken(req);
} else {
res.status(400).send();
return 0;
}
}).
then(async (ris) => {
// tools.mylog("passo il TOKEN: ", token);
if (recextra) {
recextra.registered = true;
recextra.username = user.username;
await recextra.save();
// await User.fixUsername(user.idapp, user.ind_order, user.username);
}
return ris;
}).
then(async (ris) => {
// tools.mylog("LINKREG = " + user.linkreg);
// Invia un'email all'utente
// tools.mylog('process.env.TESTING_ON', process.env.TESTING_ON);
console.log('res.locale', res.locale);
await telegrambot.askConfirmationUser(user.idapp, shared_consts.CallFunz.REGISTRATION, user, '', '', '', regexpire);
// if (!tools.testing()) {
await sendemail.sendEmail_Registration(user.lang, user.email, user,
user.idapp, user.linkreg);
// }
res
.header('x-auth', ris.token)
.header('x-refrtok', ris.refreshToken)
.send(user);
return true;
});
}).catch((e) => {
console.error(e.message);
res.status(400).send(e);
});
} catch (e) {
console.error(e.message); console.error(e.message);
res.status(400).send(e); }
});
}); });
router.get('/:idapp/:username', async (req, res) => { router.get('/:idapp/:username', async (req, res) => {
@@ -1595,7 +1600,7 @@ async function eseguiDbOp(idapp, mydata, locale, req, res) {
const deleteCart = await Cart.deleteMany({ idapp }); const deleteCart = await Cart.deleteMany({ idapp });
ris = deleteCart; ris = deleteCart;
} catch (e) { } catch (e) {
console.error('Err:', e); console.error('Err:', e);
} }

View File

@@ -820,7 +820,7 @@ function startServer(app, port) {
// Configurazione CORS dettagliata // Configurazione CORS dettagliata
const corsOptions = { const corsOptions = {
origin: '*', origin: '*',
/*origin: function (origin, callback) { /*origin: function (origin, callback) {
// Array di domini consentiti // Array di domini consentiti
const allowedOrigins = [ const allowedOrigins = [
@@ -1043,11 +1043,11 @@ function startServer(app, port) {
ws.send(JSON.stringify({ type: 'output', data: data })); ws.send(JSON.stringify({ type: 'output', data: data }));
// Controlla se c'è una richiesta di input // Controlla se c'è una richiesta di input
if (buffer.endsWith(': ') || buffer.includes('? ') || if (buffer && (buffer.endsWith(': ') || buffer.includes('? ') ||
buffer.toLowerCase().includes('password') buffer.toLowerCase().includes('password')
|| buffer.includes('Inserisci') || buffer.includes('Inserisci')
|| buffer.includes('Inserted') || buffer.includes('Inserted')
|| buffer.includes('(Y') || buffer.includes('(Y'))
) { ) {
ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() })); ws.send(JSON.stringify({ type: 'input_required', prompt: data.trim() }));
buffer = ''; buffer = '';

View File

@@ -927,7 +927,7 @@ const MyTelegramBot = {
let useraportador = await User.getUserShortDataByUsername(idapp, userDest); let useraportador = await User.getUserShortDataByUsername(idapp, userDest);
if (useraportador && useraportador.tokenreg && (regexpire.toLowerCase() === useraportador.tokenreg.toLowerCase())) { if (useraportador && useraportador.tokenreg && useraportador.tokenreg && (regexpire && (regexpire?.toLowerCase() === useraportador.tokenreg?.toLowerCase()))) {
const nonchiedereverifica = await User.getifRegTokenIsValid(idapp, useraportador.tokenreg); const nonchiedereverifica = await User.getifRegTokenIsValid(idapp, useraportador.tokenreg);
if (nonchiedereverifica) if (nonchiedereverifica)
notask_verif = true; notask_verif = true;
@@ -2103,7 +2103,7 @@ class Telegram {
// await this.menumsg_to_Nave(msg, cmd2); // await this.menumsg_to_Nave(msg, cmd2);
// } else if (testo === Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI) { // } else if (testo === Menu.MSG_SI_INVITATI_NO_7REQ_INVITATI) {
// await this.menumsg_Si_Invitati_No_7Req(msg); // await this.menumsg_Si_Invitati_No_7Req(msg);
} else if (cmd1.toLowerCase() === Menu.MSG_TO_USER) { } else if (cmd1 && cmd1.toLowerCase() === Menu.MSG_TO_USER) {
await this.menumsg_A_Utente(msg); await this.menumsg_A_Utente(msg);
} else if (testo === Menu.SETPICPROFILE) { } else if (testo === Menu.SETPICPROFILE) {
await this.setPhotoProfile(rec.user, msg.from.id); await this.setPhotoProfile(rec.user, msg.from.id);
@@ -2838,7 +2838,7 @@ class Telegram {
async setUsernameInvitante(msg) { async setUsernameInvitante(msg) {
try { try {
let mymsg = msg.text.toString().trim().toLowerCase(); let mymsg = msg.text?.toString().trim().toLowerCase();
let nomeapp = tools.getNomeAppByIdApp(this.idapp); let nomeapp = tools.getNomeAppByIdApp(this.idapp);
@@ -3271,7 +3271,7 @@ class Telegram {
getInvitanteByMsg(msg) { getInvitanteByMsg(msg) {
try { try {
let mymsg = msg.text.toString().trim().toLowerCase(); let mymsg = msg.text?.toString().trim().toLowerCase();
let invitante = ''; let invitante = '';
let regexpire = ''; let regexpire = '';
const sep = '-' const sep = '-'
@@ -3324,8 +3324,7 @@ class Telegram {
} }
const rec = this.getRecInMem(msg); const rec = this.getRecInMem(msg);
let testo = msg.text.toLowerCase().trim(); let testo = msg.text?.toLowerCase().trim();
status = this.getstatus(rec); status = this.getstatus(rec);
if (testo === Menu.EXIT_TELEGRAM) { if (testo === Menu.EXIT_TELEGRAM) {
@@ -3389,7 +3388,7 @@ class Telegram {
rec.chatId = msg.chat.id; rec.chatId = msg.chat.id;
rec.messageId = msg.message_id; rec.messageId = msg.message_id;
rec.msgall_status = StatusMSGALL.CONFIRM; rec.msgall_status = StatusMSGALL.CONFIRM;
const cmd = rec.msgtosent.toLowerCase(); const cmd = rec?.msgtosent?.toString().toLowerCase() ?? '';
let achi = this.getDestinStr(msg, rec.msgall_achi, rec); let achi = this.getDestinStr(msg, rec.msgall_achi, rec);
let domanda = ''; let domanda = '';
if (rec.msgall_domanda) { if (rec.msgall_domanda) {
@@ -3716,7 +3715,7 @@ class Telegram {
for (const rec of recuser.menuDb) { for (const rec of recuser.menuDb) {
if (rec.active_mem) { if (rec.active_mem) {
if (rec.idapp === idapp && rec.lang === lang && if (rec.idapp === idapp && rec.lang === lang &&
rec.label.toLowerCase() === testo) { rec.label?.toLowerCase() === testo) {
return true; return true;
} }
} }
@@ -3800,7 +3799,7 @@ class Telegram {
for (const recdb of recuser.menuDb) { for (const recdb of recuser.menuDb) {
if (recdb.active_mem) { if (recdb.active_mem) {
if (recdb.idapp === idapp && recdb.lang === lang && if (recdb.idapp === idapp && recdb.lang === lang &&
recdb.label.toLowerCase() === testo) { recdb.label?.toLowerCase() === testo) {
if (recdb.type === shared_consts.BOTTYPE_BOTTONI_INLINE) { if (recdb.type === shared_consts.BOTTYPE_BOTTONI_INLINE) {
const jsonString = '[{"text": "primo", "callback_data": "1"}, {"text": "sec", "callback_data": "2"}]'; const jsonString = '[{"text": "primo", "callback_data": "1"}, {"text": "sec", "callback_data": "2"}]';
const jsonObject = JSON.parse(jsonString); const jsonObject = JSON.parse(jsonString);

View File

@@ -5396,7 +5396,7 @@ module.exports = {
contatto = ''; contatto = '';
} }
} }
if ((myrec.contact_telegram && myrec.contact_telegram.toLowerCase() !== contatto_telegram.toLowerCase()) || !contatto) { if ((myrec.contact_telegram && myrec.contact_telegram?.toLowerCase() !== contatto_telegram?.toLowerCase()) || !contatto) {
contatto += '\n' + myrec.contact_telegram; contatto += '\n' + myrec.contact_telegram;
} }
/*if (myrec.contact_phone) { /*if (myrec.contact_phone) {
@@ -5709,7 +5709,7 @@ module.exports = {
const allElements = document.body.querySelectorAll('*'); const allElements = document.body.querySelectorAll('*');
allElements.forEach(element => { allElements.forEach(element => {
const tagName = element.tagName.toLowerCase(); const tagName = element.tagName?.toLowerCase();
if (!allowedTags.includes(tagName)) { if (!allowedTags.includes(tagName)) {
// Crea un nodo di testo e sostituisci l'elemento con quel nodo di testo // Crea un nodo di testo e sostituisci l'elemento con quel nodo di testo

View File

@@ -274,7 +274,7 @@ module.exports = {
{ table: 'catgrps', key: 'descr' }, { table: 'catgrps', key: 'descr' },
{ {
table: 'contribtypes', table: 'contribtypes',
key: 'descr', keyOLD: 'descr',
}, },
{ table: 'goods', key: 'descr', key2: 'idSectorGood' }, { table: 'goods', key: 'descr', key2: 'idSectorGood' },
{ table: 'levels', key: 'descr' }, { table: 'levels', key: 'descr' },