fix Registrazione data

fix linkref
fix controllo login
This commit is contained in:
Paolo Arena
2020-01-20 01:48:25 +01:00
parent e23a3a792e
commit 6dcaea5f1c
21 changed files with 779 additions and 171 deletions

View File

@@ -1,4 +1,4 @@
p Hi #{user},
p Hi #{name},
p #{nomeapp} recently received a request for a forgotten password.
p To change your #{nomeapp} password, please click on this <a href=#{strlinksetpassword} target="_blank">Click Here</a>.

View File

@@ -1,9 +1,8 @@
p Ciao #{user},
p Ciao #{name},
p #{nomeapp} recentemente ha ricevuto una richiesta per una password dimenticata.
p Per
strong cambiare la tua password
span di #{nomeapp}, <a href=#{strlinksetpassword} target="_blank">Clicca qui</a>.
p Per cambiare la tua password di #{nomeapp}
p <a href=#{strlinksetpassword} target="_blank">Clicca QUI</a>
p Se non sei stato tu a richiedere questo cambiamento, non hai bisogno di fare niente.
p Questo link scadrà tra 4 ore.<br>

View File

@@ -28,7 +28,7 @@
"email-templates": "^6.1.1",
"express": "^4.17.1",
"formidable": "^1.2.1",
"i18n": "^0.8.3",
"i18n": "^0.8.4",
"jade": "^1.11.0",
"jsonwebtoken": "^8.5.1",
"lodash": "^4.17.15",

View File

@@ -91,17 +91,17 @@ if (process.env.NODE_ENV === 'production') {
},
{
idapp: '7',
name: 'Notevole',
adminemail: 'notevole.ayni@gmail.com',
name: 'Ayni',
adminemail: 'ayni.gifteconomy@gmail.com',
manageremail: '',
replyTo: '',
host: 'https://notevole.freeplanet.app',
host: 'https://ayni.gifteconomy.app',
portapp: '0',
dir: '/var/www/notevole.freeplanet.app',
email_from: 'notevole.ayni@gmail.com',
email_pwd: '2e6ed34db0ef8fdc98e8a6872ec09a64350235c1ad7b756aa94047dec441d363xNvZnACxWSqSGu3lXcVyTuQiPR2ixYYf/HoY3agbNYU=',
dir: '/var/www/ayni.gifteconomy.app',
email_from: 'ayni.gifteconomy@gmail.com',
email_pwd: '4a16f0c93b28cd53cb2b6d9b6698ad20c5514f1c91de8161b2789274d15617bb20Ecne0RP3aNDl8NhJj5Uw==',
telegram_key:'1037577457:AAGQbdIuYoB838v61ewJ0Hearx9UPpTBhMI',
telegram_bot_name: 'notevoleaynibot',
telegram_bot_name: 'aynibot',
},
{
idapp: '8',
@@ -190,12 +190,12 @@ if (process.env.NODE_ENV === 'production') {
},
{
idapp: '7',
name: 'Notevole (Server Test)',
name: 'Ayni (Server Test)',
adminemail: 'pao.loarena77@gmail.com',
manageremail: '',
host: 'https://testnotevole.freeplanet.app',
host: 'https://test.gifteconomy.app',
portapp: '0',
dir: '/var/www/testnotevole.freeplanet.app',
dir: '/var/www/test.gifteconomy.app',
email_from: 'info.pianetalibero@gmail.com',
email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
telegram_key:'1011893908:AAEThZB3fVPw8P5gTCFgTEsDmY21DdbV1Cw',
@@ -286,7 +286,7 @@ if (process.env.NODE_ENV === 'production') {
},
{
idapp: '7',
name: 'Notevole',
name: 'Ayni',
adminemail: 'paolo.arena77@gmail.com',
manageremail: '',
host: 'http://localhost',

View File

@@ -1,5 +1,7 @@
{
"Email Verificata!": "Email Verificata!",
"partecipanti": "partecipanti",
"L'Email è già stata Verificata.": "L'Email è già stata Verificata."
}
"L'Email è già stata Verificata": "L'Email è già stata Verificata"
"Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.",
"Nuova Registrazione": "Nuevo Registro",
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro",
"partecipanti": "participantes"
}

View File

@@ -1,8 +1,7 @@
{
"L'Email è già stata Verificata": "El email ya ha sido verificado",
"Email Verificata!": "Email Verificada!",
"a": "a",
"Email Verificata!": "Email Verificada! Cierre esta ventana y regrese a la otra.",
"Nuova Registrazione": "Nuevo Registro",
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro"
"partecipanti": "participantes"
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro",
"partecipanti": "participantes",
}

View File

@@ -1,8 +1,2 @@
{
"L'Email è già stata Verificata": "L'Email è già stata Verificata",
"Email Verificata!": "Email Verificata!",
"a": "a",
"Nuova Registrazione": "Nuova Registrazione",
"Effettuata una Nuova Registrazione": "Effettuata una Nuova Registrazione",
"partecipanti": "partecipanti"
}

View File

@@ -54,12 +54,18 @@ var ExtraListSchema = new mongoose.Schema({
is_in_telegram: {
type: Boolean,
},
is_staff: {
type: Boolean,
},
cell_complete: {
type: String
},
nationality: {
type: String
},
saw_zoom_presentation: {
type: Boolean
},
aportador_solidario_name_surname: {
type: String,
},
@@ -86,26 +92,42 @@ var ExtraListSchema = new mongoose.Schema({
});
ExtraListSchema.methods.toJSON = function () {
var user = this;
var userObject = user.toObject();
const extralist = this;
const userObject = extralist.toObject();
return _.pick(userObject, ['_id', ...shared_consts.fieldsUserToChange()]);
};
ExtraListSchema.statics.findByUsername = function (idapp, username) {
const User = this;
const ExtraList = this;
return User.findOne({
return ExtraList.findOne({
'idapp': idapp,
'username': username,
});
};
ExtraListSchema.statics.getTotInLista = async function (idapp) {
const ExtraList = this;
const myfind = { idapp };
return await ExtraList.count(myfind);
};
ExtraListSchema.statics.getRegDellaLista = async function (idapp) {
const ExtraList = this;
const myfind = { idapp, registered: true };
return await ExtraList.count(myfind);
};
ExtraListSchema.statics.findByCellAndNameSurname = function (idapp, cell_complete, name, surname) {
var User = this;
const ExtraList = this;
return User.findOne({
return ExtraList.findOne({
'idapp': idapp,
'cell_complete': cell_complete,
'name': name,
@@ -187,24 +209,26 @@ ExtraListSchema.statics.ImportData = async function (locale, idapp, strdata) {
if (sep !== '' && row !== '') {
let col = row.split(sep);
if (col) {
if (col.length > 0) {
if (col.length > 11) {
let user = null;
try {
user = new ExtraList({
idapp: idapp,
ind_order: col[0],
name_complete: col[2],
num_invitati: col[3],
is_in_whatsapp: col[4] !== '',
is_in_telegram: col[5] !== '',
cell_complete: col[6],
nationality: col[7],
aportador_solidario_name_surname: col[8],
aportador_solidario_ind_order: col[9],
aportador_solidario_originale_name_surname: col[10],
note: col[11],
col_b: col[12],
col_h: col[13]
name_complete: col[2].trim(),
num_invitati: col[3].trim(),
is_in_whatsapp: col[4].trim() !== '',
is_in_telegram: col[5].trim() !== '',
is_staff: col[5].trim() === 'VV',
saw_zoom_presentation: col[6].trim() !== '',
cell_complete: col[7].trim(),
nationality: col[8].trim(),
aportador_solidario_name_surname: col[9].trim(),
aportador_solidario_ind_order: col[10].trim(),
aportador_solidario_originale_name_surname: col[11].trim(),
note: col[12].trim(),
col_b: col[13].trim(),
col_h: col[14].trim()
});
try {
@@ -213,6 +237,9 @@ ExtraListSchema.statics.ImportData = async function (locale, idapp, strdata) {
console.log('error ', e);
}
if (user.cell_complete[0] !== '+')
user.cell_complete = '+' + user.cell_complete;
namesurname = tools.extractNameAndSurnameByComplete(user.name_complete);
user.name = namesurname.name;
user.surname = namesurname.surname;
@@ -235,7 +262,7 @@ ExtraListSchema.statics.ImportData = async function (locale, idapp, strdata) {
}
} catch (e) {
console.log('error ', e);
}
ris = { numadded, numtot, numalreadyexisted };

View File

@@ -72,7 +72,7 @@ MailingListSchema.statics.getnumSent = async function (idapp, idmailinglist) {
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return await MailingList.countDocuments(myfind);
return await MailingList.count(myfind);
};
MailingListSchema.statics.isOk = async function (idapp, iduser, idmailinglist) {
@@ -82,7 +82,7 @@ MailingListSchema.statics.isOk = async function (idapp, iduser, idmailinglist) {
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return await MailingList.countDocuments(myfind) > 0;
return await MailingList.count(myfind) > 0;
};
MailingListSchema.statics.findAllIdApp = async function (idapp) {

View File

@@ -44,6 +44,9 @@ const MyPageSchema = new Schema({
heightimg: {
type: Number,
},
onlyif_logged: {
type: Boolean,
},
imgback: {
type: String,
},

View File

@@ -6,6 +6,8 @@ const _ = require('lodash');
const tools = require('../tools/general');
const { Settings } = require('../models/settings');
const shared_consts = require('../tools/shared_nodejs');
const queryclass = require('../classes/queryclass');
@@ -23,9 +25,6 @@ const UserSchema = new mongoose.Schema({
userId: {
type: String,
},
already_registered: {
type: Boolean,
},
email: {
type: String,
required: true,
@@ -103,7 +102,9 @@ const UserSchema = new mongoose.Schema({
},
date_reg: {
type: Date,
default: Date.now()
},
date_temp_reg: {
type: Date,
},
date_tokenforgot: {
type: Date
@@ -126,6 +127,9 @@ const UserSchema = new mongoose.Schema({
aportador_solidario_ind_order: {
type: Number,
},
note: {
type: String,
},
profile: {
img: {
type: String
@@ -164,6 +168,12 @@ const UserSchema = new mongoose.Schema({
dateofbirth: {
type: Date,
},
my_dream: {
type: String,
},
saw_zoom_presentation: {
type: Boolean
},
sex: {
type: Number,
},
@@ -347,7 +357,7 @@ UserSchema.statics.getDownlineByUsername = function (idapp, username) {
name: 1,
surname: 1,
verified_email: 1,
made_gift: 11,
made_gift: 1,
email: 1,
date_reg: 1,
img: 1
@@ -356,6 +366,26 @@ UserSchema.statics.getDownlineByUsername = function (idapp, username) {
});
};
UserSchema.statics.getnumInvitatiAttivi = function (idapp, username) {
const User = this;
return User.count({
idapp,
aportador_solidario: username,
teleg_id: { $gt: 1 },
saw_zoom_presentation: true,
});
};
UserSchema.statics.getnumInvitati = function (idapp, username) {
const User = this;
return User.count({
idapp,
aportador_solidario: username,
});
};
UserSchema.statics.findByLinkreg = function (idapp, linkreg) {
const User = this;
@@ -440,7 +470,7 @@ UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) {
UserSchema.statics.TelegIdByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, {'profile.teleg_id': 1})
return await User.findOne({ idapp, username }, { 'profile.teleg_id': 1 })
.then((rec) => {
return (!!rec) ? rec.profile.teleg_id : null;
}).catch((e) => {
@@ -484,7 +514,7 @@ UserSchema.statics.SetTelegramIdSuccess = async function (idapp, username, teleg
UserSchema.statics.getNameSurnameByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, {name: 1, surname: 1})
return await User.findOne({ idapp, username }, { name: 1, surname: 1 })
.then((rec) => {
return (!!rec) ? `${rec.name} ${rec.surname}` : '';
}).catch((e) => {
@@ -493,11 +523,10 @@ UserSchema.statics.getNameSurnameByUsername = async function (idapp, username) {
};
UserSchema.statics.getusersManagers = async function (idapp) {
const User = this;
return await User.find({ idapp, 'profile.manage_telegram': true }, {'profile.teleg_id': 1})
return await User.find({ idapp, 'profile.manage_telegram': true }, { 'profile.teleg_id': 1 })
.then((arrrec) => {
return (!!arrrec) ? arrrec : null;
}).catch((e) => {
@@ -505,6 +534,29 @@ UserSchema.statics.getusersManagers = async function (idapp) {
});
};
UserSchema.statics.getUsersTelegALL = async function (idapp) {
const User = this;
return await User.find({ idapp, 'profile.teleg_id': { $gt: 0 } }, { 'profile.teleg_id': 1 })
.then((arrrec) => {
return (!!arrrec) ? arrrec : null;
}).catch((e) => {
console.error('getusersManagers', e);
});
};
UserSchema.statics.isManagerByIdTeleg = async function (idapp, idtelegram) {
const User = this;
return await User.findOne({ idapp, 'profile.manage_telegram': true, 'profile.teleg_id': idtelegram }, { 'profile.teleg_id': 1 })
.then((rec) => {
return (!!rec && rec.profile.teleg_id === idtelegram);
}).catch((e) => {
console.error('getusersManagers', e);
return false
});
};
UserSchema.statics.getUsersList = function (idapp) {
const User = this;
@@ -523,7 +575,6 @@ UserSchema.statics.getUsersList = function (idapp) {
};
UserSchema.statics.getUsersListByParams = function (params) {
const User = this;
@@ -623,6 +674,46 @@ UserSchema.statics.fixUsername = async function (idapp, aportador_solidario_ind_
};
UserSchema.statics.getUsersRegistered = async function (idapp) {
const User = this;
const myfind = { idapp };
return await User.count(myfind);
};
UserSchema.statics.getLastUsers = async function (idapp) {
const User = this;
const lastn = await Settings.getValDbSettings(idapp, 'SHOW_LAST_N_USERS', 5);
return await User.find({ idapp }).sort({ date_temp_reg: -1 }).limit(lastn);
};
UserSchema.statics.checkUser = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username }, {
verified_email: 1,
'profile.teleg_id': 1,
'profile.teleg_checkcode': 1,
});
};
UserSchema.statics.calculateStat = async function (idapp, username) {
const User = this;
return calcstat = {
numinvitati: await User.getnumInvitati(idapp, username),
numinvitati_attivi: await User.getnumInvitatiAttivi(idapp, username),
};
};
if (tools.INITDB_FIRSTIME) {
console.log(' createIndex User Index...');

View File

@@ -9,8 +9,12 @@ function toHexString(bytes) {
module.exports = {
getlinkregByEmail: function (idapp, email, username) {
try{
mystr = idapp + email + username;
return jwt.sign(toHexString(mystr), process.env.SIGNCODE).toString();
myobj = {
idapp,
email,
username
};
return jwt.sign(myobj, process.env.SIGNCODE).toString().substring(0, 180);
} catch (e) {
console.error(e);
}

View File

@@ -3,6 +3,9 @@ const router = express.Router(),
fs = require('fs'),
path = require('path');
const jwt = require('jsonwebtoken');
const sendemail = require('../sendemail');
const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
@@ -51,7 +54,7 @@ router.post(process.env.LINKVERIF_REG, (req, res) => {
const body = _.pick(req.body, ['idapp', 'idlink']);
const idapp = body.idapp;
const idlink = body.idlink;
console.log("LINKVERIF_REG POST " + process.env.LINKVERIF_REG + " idapp= " + idapp + " idlink = " + idlink);
// console.log("LINKVERIF_REG POST " + process.env.LINKVERIF_REG + " idapp= " + idapp + " idlink = " + idlink);
// Cerco l'idlink se è ancora da Verificare
@@ -60,17 +63,18 @@ router.post(process.env.LINKVERIF_REG, (req, res) => {
//console.log("NON TROVATO!");
return res.status(404).send();
} else {
console.log('user', user);
if (user.verified_email) {
res.send({
code: server_constants.RIS_CODE_EMAIL_ALREADY_VERIFIED,
msg: res.__("L'Email è già stata Verificata.")
msg: tools.getres__("L'Email è già stata Verificata", res)
});
} else {
user.verified_email = true;
user.lasttimeonline = new Date();
user.save().then(() => {
//console.log("TROVATOOOOOO!");
res.send({ code: server_constants.RIS_CODE_EMAIL_VERIFIED, msg: res.__('Email Verificata!') });
res.send({ code: server_constants.RIS_CODE_EMAIL_VERIFIED, msg: tools.getres__('EMAIL_VERIF', res) });
});
}
}
@@ -91,14 +95,14 @@ router.post(process.env.LINK_REQUEST_NEWPASSWORD, (req, res) => {
User.findByEmail(idapp, email).then((user) => {
if (!user) {
return res.status(404).send();
return res.status(200).send({ code: server_constants.RIS_CODE_EMAIL_NOT_EXIST, msg: '' });
} else {
// Creo il tokenforgot
user.tokenforgot = jwt.sign(user._id.toHexString(), process.env.SIGNCODE).toString();
user.date_tokenforgot = new Date();
user.lasttimeonline = new Date();
user.save().then(async () => {
await sendemail.sendEmail_RequestNewPassword(res.locale, user.email, user.idapp, user.tokenforgot);
await sendemail.sendEmail_RequestNewPassword(res.locale, user, user.email, user.idapp, user.tokenforgot);
res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
});
}
@@ -426,12 +430,18 @@ router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) =>
newstosent = Newstosent.findAllIdApp(idapp);
}
return Promise.all([bookedevent, eventlist, operators, wheres, contribtype, settings, permissions, disciplines, newstosent, mailinglist, mypage, gallery, paymenttype])
let calcstat = null;
if (req.user)
calcstat = User.calculateStat(idapp, req.user.username);
return Promise.all([bookedevent, eventlist, operators, wheres, contribtype, settings, permissions, disciplines, newstosent, mailinglist, mypage, gallery, paymenttype, calcstat])
.then((arrdata) => {
// console.table(arrdata);
const myuser = req.user;
if (myuser) {
myuser.password = '';
myuser._doc.calcstat = arrdata[13];
}
res.send({

View File

@@ -0,0 +1,53 @@
const express = require('express');
const router = express.Router();
const tools = require('../tools/general');
const server_constants = require('../tools/server_constants');
const { authenticate } = require('../middleware/authenticate');
const mongoose = require('mongoose');
const { User } = require('../models/user');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
const { ExtraList } = require('../models/extralist');
router.post('/load', async (req, res) => {
const idapp = req.body.idapp;
const username = req.body.username;
let datastat = {
num_tot_lista: await ExtraList.getTotInLista(idapp),
num_reg_lista: await ExtraList.getRegDellaLista(idapp),
num_reg: await User.getUsersRegistered(idapp),
lastsreg: await User.getLastUsers(idapp),
checkuser: await User.checkUser(idapp, username),
};
// console.table(datastat.lastsreg);
/*
let datastat = {
num_tot_lista: 80,
num_reg: 40,
lastsreg: [
{ username: 'prova3', name: 'Datti', surname: 'Una Mossa', nationality: 'gb', date_reg: new Date()},
{ username: 'prova2', name: 'Pinco', surname: 'Pallino', nationality: 'de', date_reg: new Date()},
{ username: 'paoloar77', name: 'Paolo', surname: 'Arena', nationality: 'it', date_reg: new Date()},
{ username: 'mariorossi', name: 'Mario', surname: 'Rossi', nationality: 'es', date_reg: new Date()},
{ username: 'prova4', name: 'Quanto', surname: 'Siamo Fighi', nationality: 'uk', date_reg: new Date()},
{ username: 'prova5', name: 'Secondo', surname: 'PPP', nationality: 'sl', date_reg: new Date()},
]
};
*/
res.send({ datastat });
});
module.exports = router;

View File

@@ -11,6 +11,8 @@ const shared_consts = require('../tools/shared_nodejs');
const server_constants = require('../tools/server_constants');
const telegrambot = require('../telegram/telegrambot');
const _ = require('lodash');
const reg = require('../reg/registration');
@@ -44,7 +46,7 @@ function getMobileComplete(user) {
// POST /users
router.post('/', async (req, res) => {
tools.mylog("POST /users");
const body = _.pick(req.body, ['email', 'password', 'username', 'name', 'surname', 'idapp', 'keyappid', 'lang', 'profile', 'aportador_solidario', 'already_registered']);
const body = _.pick(req.body, ['email', 'password', 'username', 'name', 'surname', 'idapp', 'keyappid', 'lang', 'profile', 'aportador_solidario']);
const user = new User(body);
// tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp);
@@ -53,6 +55,8 @@ router.post('/', async (req, res) => {
user.verified_email = false;
user.ipaddr = reg.getiPAddressUser(req);
user.lasttimeonline = new Date();
user.date_reg = new Date();
user.date_temp_reg = new Date();
// user.perm = 3;
if (tools.testing()) {
user.verified_email = true;
@@ -86,9 +90,34 @@ router.post('/', async (req, res) => {
let recextra = null;
if (user.already_registered) {
recextra = await ExtraList.findByCellAndNameSurname(user.idapp, getMobileComplete(user), user.name, user.surname);
let nomeaportador_corretto = "";
if (recextra) {
nomeaportador_corretto = recextra.aportador_solidario_name_surname;
if (nomeaportador_corretto === '')
nomeaportador_corretto = recextra.aportador_solidario_originale_name_surname;
}
namesurname_aportador_reg = await User.getNameSurnameByUsername(user.idapp, user.aportador_solidario);
if (namesurname_aportador_reg !== '' && namesurname_aportador_reg !== nomeaportador_corretto) {
// Si sta tentando di registrare una persona sotto che non corrisponde!
let msg = 'L\'utente ' + user.name + ' ' + user.surname + ' si sta registrando con il link di ' + user.aportador_solidario + ' (' + namesurname_aportador_reg + ') ' +
'invece è assegnato a ' + nomeaportador_corretto;
telegrambot.sendMsgTelegramToTheManagers(user.idapp, msg);
res.status(400).send({ code: server_constants.RIS_CODE_USER_NOT_THIS_APORTADOR, msg: '' });
return 1;
}
const already_registered = recextra;
// Check if is an other people aportador_solidario
if (already_registered) {
// Check in the extraList if is present!
recextra = await ExtraList.findByCellAndNameSurname(user.idapp, getMobileComplete(user), user.name, user.surname);
if (!recextra) {
res.status(400).send({ code: server_constants.RIS_CODE_USER_EXTRALIST_NOTFOUND, msg: '' });
return 1;
@@ -102,6 +131,15 @@ router.post('/', async (req, res) => {
user.aportador_solidario_ind_order = recextra.aportador_solidario_ind_order;
user.note = recextra.note;
if (recextra.is_staff) {
user.perm = shared_consts.Permissions.Manager;
}
if (recextra.username === 'paoloar77') {
user.perm = shared_consts.Permissions.Manager + shared_consts.Permissions.Admin;
}
const useraportador = await ExtraList.findByIndOrder(user.idapp, user.aportador_solidario_ind_order);
if (useraportador)
user.aportador_solidario = useraportador.username;

View File

@@ -5,7 +5,7 @@ require('./config/config');
const Email = require('email-templates');
var i18n = require("i18n");
const i18n = require("i18n");
const { ObjectID } = require('mongodb');
const { Settings } = require('./models/settings');
@@ -145,13 +145,13 @@ module.exports = {
strlinkreg = tools.getHostByIdApp(idapp) + process.env.LINKVERIF_REG + `?idapp=${idapp}&idlink=${idreg}`;
return strlinkreg;
},
getlinkRequestNewPassword: function (idapp, user, tokenforgot) {
strlinkreg = tools.getHostByIdApp(idapp) + "/#" + process.env.LINK_REQUEST_NEWPASSWORD + `?idapp=${idapp}&username=${user}&=tokenforgot=${tokenforgot}`;
getlinkRequestNewPassword: function (idapp, username, tokenforgot) {
strlinkreg = tools.getHostByIdApp(idapp) + "/#" + process.env.LINK_REQUEST_NEWPASSWORD + `?idapp=${idapp}&username=${username}&=tokenforgot=${tokenforgot}`;
return strlinkreg;
},
sendEmail_Registration: async function (lang, emailto, user, idapp, idreg) {
console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
// console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
mylocalsconf = {
idapp,
@@ -178,7 +178,7 @@ module.exports = {
this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
},
sendEmail_RequestNewPassword: async function (lang, emailto, idapp, tokenforgot) {
sendEmail_RequestNewPassword: async function (lang, user, emailto, idapp, tokenforgot) {
mylocalsconf = {
idapp,
@@ -186,7 +186,10 @@ module.exports = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
user: user,
strlinksetpassword: this.getlinkRequestNewPassword(idapp, user, tokenforgot),
name: user.name,
username: user.username,
surname: user.surname,
strlinksetpassword: this.getlinkRequestNewPassword(idapp, user.username, tokenforgot),
emailto: emailto,
};
@@ -216,7 +219,7 @@ module.exports = {
mylocalsconf.msgreply_after_booking = ris;
if (recbooking.numpeople > 1)
mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + res.__("partecipanti");
mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + tools.getres__('partecipanti', res);
let texthtml = '';
if (recbooking.modified) {
@@ -256,7 +259,7 @@ module.exports = {
};
if (recbooking.numpeople > 1)
mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + res.__("partecipanti");
mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + tools.getres__('partecipanti', res);
this.sendEmail_base('booking/cancelbooking/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));

View File

@@ -55,6 +55,7 @@ const todos_router = require('./router/todos_router');
const test_router = require('./router/test_router');
const projects_router = require('./router/projects_router');
const users_router = require('./router/users_router');
const notevole_router = require('./router/notevole_router');
const admin_router = require('./router/admin_router');
const { MyEvent } = require('./models/myevent');
@@ -90,6 +91,7 @@ app.use(bodyParser.json());
i18n.configure({
locales: ['it', 'en', 'es'],
// cookie: 'cook',
directory: __dirname + '/locales'
});
@@ -99,6 +101,7 @@ app.use(cors({
app.use(bodyParser.json());
// app.use(express.cookieParser());
app.use(i18n.init);
@@ -116,6 +119,7 @@ app.use('/todos', todos_router);
app.use('/test', test_router);
app.use('/projects', projects_router);
app.use('/users', users_router);
app.use('/ayni', notevole_router);
app.use('/admin', admin_router);
// catch 404 and forward to error handler
@@ -178,11 +182,13 @@ if (process.env.PROD !== 1) {
// testmsgwebpush();
// sendemail.testemail('2', 'it');
// let crypt = tools.cryptdata('');
// let decrypt = tools.decryptdata(crypt);
/*
let crypt = tools.cryptdata('');
let decrypt = tools.decryptdata(crypt);
// console.log('crypted:', crypt);
// console.log('decrypted:', decrypt);
console.log('crypted:', crypt);
console.log('decrypted:', decrypt);
*/
mycron();
}
@@ -221,11 +227,13 @@ function startserv() {
// Check if is Empty (new Server Data)
/*
cfgserver.countDocuments(function (err, count) {
if (!err && count === 0) {
populateDBadmin();
}
});
*/
}
@@ -273,4 +281,14 @@ telegrambot.sendMsgTelegramByIdTelegram('7', telegrambot.ADMIN_IDTELEGRAM_SERVER
// telegrambot.sendMsgTelegramToTheManagers('7', 'PROVAAA!');
// 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);
// }
module.exports = { app };

View File

@@ -8,18 +8,79 @@ const { User } = require('../models/user');
const emoji = require('node-emoji');
const i18n = require("i18n");
const Benvenuto = emoji.get('heartbeat') + emoji.get('heartbeat') + emoji.get('heartbeat') + ' Benvenuto!';
const emo = {
DREAM: emoji.get('beach_with_umbrella'),
EYES: emoji.get('eyes'),
DIZZY: emoji.get('dizzy'),
ONE_HUNDRED: emoji.get('100'),
SMILE_STAR: emoji.get('star-struck'),
CHECK_VERDE: emoji.get('white_check_mark'),
CHECK_GRIGIA: emoji.get('ballot_box_with_check'),
CROSS_ROSSA: emoji.get('x'),
ENVELOPE: emoji.get('envelope'),
EXCLAMATION_MARK: emoji.get('exclamation'),
QUESTION_MARK: emoji.get('question'),
ARROW_RIGHT: emoji.get('arrow_right'),
INVITATI: emoji.get('man_and_woman_holding_hands'),
HEART: emoji.get('heart'),
BLUE_HEART: emoji.get('blue_heart'),
GREEN_HEART: emoji.get('green_heart'),
YELLOW_HEART: emoji.get('yellow_heart'),
PURPLE_HEART: emoji.get('purple_heart'),
GIFT_HEART: emoji.get('gift_heart'),
};
function getemojibynumber(number) {
if (number === 0) {
return emoji.get('zero')
} else if (number === 1) {
return emoji.get('one')
} else if (number === 2) {
return emoji.get('two')
} else if (number === 3) {
return emoji.get('three')
} else if (number === 4) {
return emoji.get('four')
} else if (number === 5) {
return emoji.get('five')
} else if (number === 6) {
return emoji.get('six')
} else if (number === 7) {
return emoji.get('seven')
} else if (number === 8) {
return emoji.get('height')
} else if (number === 9) {
return emoji.get('nine')
}
}
const Menu = {
LAVAGNA: emoji.get('om_symbol') + ' La tua Lavagna',
LINK_CONDIVIDERE: emoji.get('link') + ' Link da condividere',
INFO: emoji.get('information_source') + ' Informazioni',
ASSISTENZA: emoji.get('open_hands') + ' Assistenza',
ADMIN: emoji.get('information_desk_person') + ' Admin',
ALTRO: emoji.get('newspaper') + ' Altro',
MSGATUTTI: emoji.get('incoming_envelope') + ' Invia a TUTTI',
INDIETRO: emoji.get('back') + ' Indietro',
SI: emoji.get('thumbsup') + ' SI',
NO: emoji.get('thumbsdown') + ' NO',
EXIT_TELEGRAM: 'exittotelegram',
};
const MenuStandard = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.INFO, Menu.ASSISTENZA]];
const MenuPerAdmin = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.INFO, Menu.ASSISTENZA], [Menu.ADMIN, Menu.ALTRO]];
const MenuYesNo = [[Menu.SI, Menu.NO]];
const MenuAdmin = [[Menu.MSGATUTTI, Menu.INDIETRO], ['', '']];
const MenuYes = [[Menu.MSGATUTTI, Menu.INDIETRO], ['', '']];
const Status = {
NONE: 0,
@@ -28,19 +89,27 @@ const Status = {
WAITFOR_VERIFY_CODE: 103,
};
const StatusMSGALL = {
NONE: 0,
ASK: 1,
CONFIRM: 2,
};
const txt = {
MSG_SCEGLI_MENU: emoji.get('dizzy') + ' Scegli una voce di menu:' + emoji.get('dizzy'),
MSG_ASK_USERNAME_BO: 'Inserire lo username con cui ti sei registrato sul sito:',
MSG_ERRORE_USERNAME: 'Attenzione! Devi inserire solo lo username (20 caratteri massimo)',
MSG_ERRORE_USERNAME_NOT_FOUND: 'Attenzione! Username non trovato in archivio. Verifica che sia corretto.',
MSG_ERRORE_USERNAME_ANNULLA: 'Inserimento Annullato.',
MSG_ERRORE_USERNAME_ANNULLA: 'Inserimento Annullato. Riprovare',
MSG_OPERAZ_ANNULLATA: 'Operazione Annullata',
MSG_ERRORE_VERIFY_CODE_MAXLEN: 'Attenzione! Devi inserire solo il codice a 6 cifre',
MSG_VERIFY_CODE: 'Vai sul sito e aggiorna la pagina (REFRESH) e scrivi qui il Codice di Autenticazione che vedrai visualizzato',
MSG_VERIFY_CODE: 'Vai sul sito e scrivi qui il Codice di Autenticazione che vedrai visualizzato',
MSG_ERR_VERIFY_CODE: 'Codice di Verifica Errato! Controllare sul Sito e reinserire il nuovo codice di 6 cifre.',
MSG_VERIFY_OK: emoji.get('grinning') + ' Benvenuto %s. Ora sei correttamente verificato!',
MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi',
MSG_EXIT_TELEGRAM: 'L\'account è stato ora scollegato da questo Telegram BOT.',
MSG_APORTADOR_USER_REGISTERED: emoji.get('heart_eyes') + ' Si è appena Registrato con il tuo link:\n%s',
MSG_MSG_SENT: emoji.get('envelope') + ' Messaggi Inviati !',
};
const TelegramBot = require('node-telegram-bot-api');
@@ -57,15 +126,23 @@ module.exports = {
notifyToTelegram: async function (phase, mylocalsconf) {
let userdest = mylocalsconf.user.aportador_solidario;
let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${userdest})`;
let NameFrom = `${mylocalsconf.user.name} ${mylocalsconf.user.surname}`;
let aportador = '';
if (userdest)
aportador = ` (${userdest})`;
NameFrom += aportador;
let text = '';
if (phase === this.phase.REGISTRATION) {
NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, userdest) + ` (${userdest})`;
if (!!mylocalsconf.user.aportador_solidario)
text = printf(txt.MSG_APORTADOR_USER_REGISTERED, `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${mylocalsconf.user.username})`);
if (userdest) {
NameFrom = await User.getNameSurnameByUsername(mylocalsconf.idapp, userdest) + aportador;
}
text = printf(txt.MSG_APORTADOR_USER_REGISTERED, `${mylocalsconf.user.name} ${mylocalsconf.user.surname} (${mylocalsconf.user.username})`);
}
await this.sendMsgTelegram(mylocalsconf.idapp, userdest, text);
if (!!mylocalsconf.user.aportador_solidario)
await this.sendMsgTelegram(mylocalsconf.idapp, userdest, text);
await this.sendMsgTelegramToTheManagers(mylocalsconf.idapp, '[Inviato a ' + NameFrom + ']:' + '\n' + text);
},
@@ -83,19 +160,33 @@ module.exports = {
},
sendMsgTelegram: async function (idapp, username, text) {
const teleg_id = await User.TelegIdByUsername(idapp, username);
const cl = getclTelegByidapp(idapp);
if (cl && teleg_id) {
cl.sendMsg(teleg_id, text)
sendMsgTelegramToALL: async function (idapp, text) {
const usersall = await User.getUsersTelegALL(idapp);
if (usersall) {
usersall.forEach((rec) => {
this.sendMsgTelegramByIdTelegram(idapp, rec.profile.teleg_id, text)
});
}
},
sendMsgTelegramByIdTelegram: function (idapp, idtelegram, text) {
sendMsgTelegram: async function (idapp, username, text) {
const teleg_id = await User.TelegIdByUsername(idapp, username);
const cl = getclTelegByidapp(idapp);
if (cl && teleg_id) {
await cl.sendMsg(teleg_id, text)
}
},
sendMsgTelegramByIdTelegram: async function (idapp, idtelegram, text) {
if (!idtelegram)
return;
const cl = getclTelegByidapp(idapp);
if (cl && idtelegram) {
cl.sendMsg(idtelegram, text)
await cl.sendMsg(idtelegram, text)
}
}
@@ -115,38 +206,85 @@ class Telegram {
this.arrUsers = [];
}
async createIfNotExist(msg) {
if (!await this.alreadyExist(msg)) {
if (this.insertIntoDB(msg)) {
let rec = this.getRecInMem(msg);
if (rec.user)
rec.status = Status.VERIFIED
}
return true
} else {
return false
}
}
async start(msg) {
// this.msgBenvenuto(msg.chat.id);
// Check if Present to the DB
if (!await this.alreadyExist(msg)) {
this.insertIntoDB(msg);
} else {
if (!await this.createIfNotExist(msg)) {
let rec = this.getRecInMem(msg);
if (!rec)
rec = this.addUser(msg);
rec.status = Status.VERIFIED
if (rec.user)
rec.status = Status.VERIFIED
}
}
isMenu(msg) {
if (msg.text === Menu.LAVAGNA) {
this.menuLavagna(msg)
} else if (msg.text === Menu.LINK_CONDIVIDERE) {
this.menuLinkCondividere(msg)
} else if (msg.text === Menu.ASSISTENZA) {
this.menuAssistenza(msg)
async isMenuNotVerified(rec, msg) {
if (msg.text === Menu.ASSISTENZA) {
await this.menuAssistenza(msg)
} else if (msg.text === Menu.INFO) {
this.menuInformazioni(msg)
} else if (msg.text === Menu.EXIT_TELEGRAM) {
this.menuExitToTelegram(msg)
await this.menuInformazioni(msg)
} else {
this.msgScegliMenu(msg);
await this.msgScegliMenu(msg);
}
}
async isMenu(rec, msg) {
if (msg.text === Menu.LAVAGNA) {
await this.menuLavagna(msg)
} else if (msg.text === Menu.LINK_CONDIVIDERE) {
await this.menuLinkCondividere(msg)
} else if (msg.text === Menu.EXIT_TELEGRAM) {
await this.menuExitToTelegram(msg)
} else if (msg.text === Menu.ADMIN) {
await this.menuAdmin(msg)
} else if (msg.text === Menu.MSGATUTTI) {
await this.menumsgAll(msg)
} else if (msg.text === Menu.INDIETRO) {
await this.msgScegliMenu(msg);
} else {
await this.isMenuNotVerified(rec, msg);
}
}
getsymb(symb, valid, isnum, verdeif, smileif) {
let str = symb + ': ';
if (valid)
str += emo.CHECK_VERDE;
else
str += emo.CROSS_ROSSA;
if (isnum) {
str += ' ' + getemojibynumber(valid);
if (smileif)
str += emo.SMILE_STAR;
}
return str + ' ';
}
isdreamset(user) {
if (user) {
if (user.profile.my_dream)
if (user.profile.my_dream.length > 10)
return true
}
return false
}
async menuLavagna(msg) {
const rec = this.getRecInMem(msg);
// console.log('rec', rec);
@@ -155,28 +293,43 @@ class Telegram {
const dashboard = await User.getDashboard(this.idapp, rec.user.aportador_solidario, rec.user.username);
const numpersone = (dashboard.downline) ? dashboard.downline.length : 0;
if (dashboard.aportador) {
mystr = emoji.get('seedling') + ` Chi ti ha invitato: ${dashboard.aportador.username} (${dashboard.aportador.name} ${dashboard.aportador.surname})\n`;
} else {
mystr = 'Chi ti ha invitato: Sei il Primo! ';
let numpersone = (dashboard.downline) ? dashboard.downline.length : 0;
mystr = "";
// if (dashboard.aportador) {
// mystr = emoji.get('seedling') + ` Chi ti ha invitato: ${dashboard.aportador.username} (${dashboard.aportador.name} ${dashboard.aportador.surname})\n`;
// } else {
// mystr = 'Chi ti ha invitato: Sei il Primo! ';
// }
// mystr += `____________________________________________\n`;
if (rec.user) {
mystr += tools.get__('BENVENUTO', msg) + ' ' + rec.user.name + ' ' + emo.DIZZY;
mystr += '\n' + '\n' + this.getsymb(emo.ENVELOPE, rec.user.verified_email);
mystr += rec.user.verified_email ? tools.get__('EMAIL_VERIF', msg) : tools.get__('EMAIL_NON_VERIF', msg);
mystr += '\n' + '\n' + this.getsymb(emo.EYES, rec.user.profile.saw_zoom_presentation) + tools.get__('ZOOM_PARTECIPATO', msg);
mystr += '\n' + '\n' + this.getsymb(emo.DREAM, this.isdreamset(rec.user)) + tools.get__('SCRITTO_SOGNO', msg);
// } else{
// mystr += tools.get__('TELEGRAM_NOT_CONNECTED', msg) + ' ' + emoji.get('e-mail');
}
mystr += `____________________________________________\n`;
// numpersone = 3;
mystr += '\n' + '\n' + this.getsymb(emo.INVITATI, numpersone, true, numpersone >= 2, numpersone >= 3) + tools.get__('INVITATI', msg) + '\n';
if (numpersone > 0) {
mystr += `Persone che hai invitato (${numpersone}):\n`;
let index = 1;
dashboard.downline.forEach((user) => {
mystr += emoji.get('star-struck') + ` ${index}°: ${user.username} (${user.name} ${user.surname})\n`;
index++;
});
} else {
mystr += `Attualmente non hai invitato nessuna persona.\n`;
}
}
if (!!mystr)
this.sendMsg(msg.chat.id, mystr);
await this.sendMsg(msg.chat.id, mystr);
}
@@ -184,7 +337,7 @@ class Telegram {
const rec = this.getRecInMem(msg);
if (rec.user) {
const mystr = tools.getHostByIdApp(this.idapp) + '/signup/' + rec.user.username;
this.sendMsg(msg.chat.id, mystr);
await this.sendMsg(msg.chat.id, mystr);
}
}
@@ -202,12 +355,28 @@ class Telegram {
async menuInformazioni(msg) {
const mystr = 'Informazioni Aggiuntive: ...';
this.sendMsg(msg.chat.id, mystr);
await this.sendMsg(msg.chat.id, mystr);
}
async menuAdmin(msg) {
const mystr = 'scegli una voce:';
await this.sendMsg(msg.chat.id, mystr, MenuAdmin);
}
async menumsgAll(msg) {
const rec = this.getRecInMem(msg);
if (rec.user) {
const mystr = 'Scrivi qui un Messaggio da inviare a TUTTI:';
rec.msgall_status = StatusMSGALL.ASK;
await this.sendMsg(msg.chat.id, mystr, MenuAdmin);
}
}
async menuAssistenza(msg) {
const mystr = 'Per contattarci usa la chat di gruppo al seguente link: ....';
this.sendMsg(msg.chat.id, mystr);
const mytext = tools.get__('TESTO_ASSISTENZA', msg);
await this.sendMsg(msg.chat.id, mytext);
}
existInMemory(msg) {
@@ -215,14 +384,18 @@ class Telegram {
return !!rec
}
getstatusInMemory(msg) {
const rec = this.getRecInMem(msg);
getstatus(rec) {
if (!!rec)
return rec.status;
else
return Status.NONE;
}
getstatusInMemory(msg) {
const rec = this.getRecInMem(msg);
return this.getstatus(rec);
}
getRecInMem(msg) {
return this.arrUsers.find((rec) => rec.id === msg.from.id);
}
@@ -243,20 +416,21 @@ class Telegram {
// Check if username exist
const user = await User.findByUsername(this.idapp, rec.username_bo);
if (!user) {
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND)
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND)
} else {
rec.user = user;
await User.SetTelegramCheckCode(this.idapp, rec.username_bo, rec.code);
rec.status = Status.WAITFOR_VERIFY_CODE;
this.sendMsg(msg.from.id, txt.MSG_VERIFY_CODE)
await this.sendMsg(msg.from.id, txt.MSG_VERIFY_CODE)
}
}
} else if (text.length === 0) {
if (rec)
rec.status = Status.NONE;
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA)
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA);
this.deleteRecInMem(msg)
} else {
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME)
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME)
}
} catch (e) {
console.error('Error setUsernameBo:', e)
@@ -272,7 +446,7 @@ class Telegram {
if (user) {
telegcode = user.profile.teleg_checkcode.toString();
} else {
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND);
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND);
return
}
if (msg.text.length < 7) {
@@ -287,24 +461,53 @@ class Telegram {
this.sendMsg(msg.from.id, txt.MSG_ERR_UNKNOWN_VERIFY_CODE);
}
});
} else {
rec.retry++;
this.sendMsg(msg.from.id, txt.MSG_ERR_VERIFY_CODE)
if (rec.retry < 2) {
rec.retry++;
await this.sendMsg(msg.from.id, txt.MSG_ERR_VERIFY_CODE)
} else {
rec.status = Status.NONE;
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA);
this.deleteRecInMem(msg);
}
}
}
} else if (msg.text.length === 0) {
if (rec)
rec.status = Status.NONE;
this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA)
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA)
} else {
this.sendMsg(msg.from.id, txt.MSG_ERRORE_VERIFY_CODE_MAXLEN)
await this.sendMsg(msg.from.id, txt.MSG_ERRORE_VERIFY_CODE_MAXLEN)
}
} catch (e) {
console.error('Error setVerifyCode', e);
}
}
async sendMsgToAll(rec, msg, texttosend) {
if (texttosend.length < 3) {
} else {
const usersall = await User.getUsersTelegALL(rec.user.idapp);
let nummsgsent = 0;
if (usersall) {
for (const rec of usersall) {
await this.sendMsg(rec.profile.teleg_id, texttosend);
nummsgsent++;
}
}
await this.sendMsg(msg.chat.id, nummsgsent + ' ' + getstr(msg.from.language_code, txt.MSG_MSG_SENT));
}
rec.start_write_msgall = false;
}
selectMenuHelp(msg) {
return ((msg.text === Menu.INFO) || (msg.text === Menu.ASSISTENZA))
}
async receiveMsg(msg) {
let status = this.getstatusInMemory(msg);
if (status === Status.NONE) {
@@ -312,18 +515,49 @@ class Telegram {
let status = this.getstatusInMemory(msg);
if (status !== Status.VERIFIED)
return
} else {
await this.setUser(msg)
}
status = this.getstatusInMemory(msg);
if (status === Status.WAITFOR_USERNAME_BO) {
const rec = this.getRecInMem(msg);
status = this.getstatus(rec);
if (status === Status.WAITFOR_USERNAME_BO && !this.selectMenuHelp(msg)) {
await this.setUsernameBo(msg)
} else if (status === Status.WAITFOR_VERIFY_CODE) {
await this.setVerifyCode(msg)
} else if (status === Status.NONE) {
await this.start(msg);
} else if (status === Status.VERIFIED) {
// Check Menu
await this.isMenu(msg);
let normale = true;
if (rec.msgall_status === StatusMSGALL.CONFIRM) {
if (msg.text === Menu.SI) {
// Take msg to send to ALL
await this.sendMsgToAll(rec, msg, rec.msgtosent)
} else {
this.sendMsg(msg.chat.id, txt.MSG_OPERAZ_ANNULLATA);
}
rec.msgall_status = StatusMSGALL.NONE;
normale = false;
} else if (rec.msgall_status === StatusMSGALL.ASK) {
if (msg.text !== Menu.INDIETRO) {
rec.msgtosent = msg.text;
rec.msgall_status = StatusMSGALL.CONFIRM;
const domanda = 'Confermi d\'Inviare questo messaggio a TUTTI ?\n' + rec.msgtosent;
this.ChiediSINO(msg, domanda);
} else {
rec.msgall_status = StatusMSGALL.NONE;
await this.msgScegliMenu(msg);
}
normale = false
}
if (normale) {
// Check Menu
await this.isMenu(rec, msg);
}
} else {
await this.isMenuNotVerified(rec, msg);
}
}
@@ -333,22 +567,42 @@ class Telegram {
if (!rec) {
await this.addUser(msg);
this.sendMsg(msg.chat.id, getstr(msg.from.language_code, txt.MSG_ASK_USERNAME_BO));
await this.sendMsg(msg.chat.id, getstr(msg.from.language_code, txt.MSG_ASK_USERNAME_BO));
return false;
}
return true;
}
async setUser(msg) {
const id = msg.from.id;
const user = await User.UserByIdTelegram(this.idapp, id);
let rec = this.arrUsers.find((rec) => rec.id === msg.from.id);
if (user && rec) {
rec.user = user;
}
}
async alreadyExist(msg) {
const id = msg.from.id;
const user = await User.UserByIdTelegram(this.idapp, id);
let rec = this.arrUsers.find((rec) => rec.id === msg.from.id);
if (user && !rec) {
rec = this.addUser(msg);
}
if (rec) {
rec.user = user;
rec.username_bo = user.username_bo
let rec = null;
try {
const user = await User.UserByIdTelegram(this.idapp, id);
let rec = this.arrUsers.find((rec) => rec.id === msg.from.id);
if (user && !rec) {
rec = this.addUser(msg);
}
if (rec) {
rec.user = user;
if (user)
rec.username_bo = user.username;
else
rec.username_bo = ''
}
} catch (e) {
console.error('Error: ', e);
}
return !!rec
}
@@ -363,7 +617,9 @@ class Telegram {
lang,
status: Status.WAITFOR_USERNAME_BO,
retry: 0,
username_bo: ''
username_bo: '',
msgall_status: StatusMSGALL.NONE,
msgtosent: '',
};
this.arrUsers.push(rec);
@@ -374,32 +630,62 @@ class Telegram {
insertIntoDB(msg) {
this.askVerifiedCode(msg);
return this.askVerifiedCode(msg);
}
sendMsg(id, text) {
async getKeyboard(id, menu) {
let keyb = MenuStandard;
// Check if you are Admin
const ismanager = await User.isManagerByIdTeleg(this.idapp, id);
if (ismanager)
keyb = MenuPerAdmin;
if (menu) {
keyb = menu
}
return keyb
}
async sendMsg(id, text, menu) {
if (!text)
return;
this.bot.sendMessage(id, text, {
"reply_markup": {
"keyboard": MenuStandard
"resize_keyboard": true,
"keyboard": await this.getKeyboard(id, menu)
}
});
}
msgBenvenuto(id) {
async msgBenvenuto(id) {
this.bot.sendMessage(id, Benvenuto, {
"reply_markup": {
"keyboard": MenuStandard
"resize_keyboard": true,
"keyboard": await this.getKeyboard(id)
}
});
}
msgScegliMenu(msg) {
async ChiediSINO(msg, domanda) {
this.bot.sendMessage(msg.from.id, domanda, {
"reply_markup": {
"resize_keyboard": true,
'one_time_keyboard': true,
"keyboard": MenuYesNo
}
});
}
async msgScegliMenu(msg) {
// const rec = this.getRecInMem(msg);
this.bot.sendMessage(msg.from.id, txt.MSG_SCEGLI_MENU, {
"reply_markup": {
"keyboard": MenuStandard
"resize_keyboard": true,
"keyboard": await this.getKeyboard(msg.from.id)
}
});
}

View File

@@ -1,4 +1,4 @@
var os = require("os");
const os = require("os");
const fs = require('fs');
@@ -8,7 +8,7 @@ require('../models/subscribers');
const CryptoJS = require('crypto-js');
var Url = require('url-parse');
const Url = require('url-parse');
const { ObjectID } = require('mongodb');
@@ -36,6 +36,56 @@ webpush.setVapidDetails(subject, publicVapidKey, privateVapidKey);
// console.log('setVapidDetails... config...');
// To Translate!
textlang = {
it: {
"L'Email è già stata Verificata": "L'Email è già stata Verificata",
"Nuova Registrazione": "Nuova Registrazione",
"Effettuata una Nuova Registrazione": "Effettuata una Nuova Registrazione",
"partecipanti": "partecipanti",
'TESTO_ASSISTENZA': "Chat d'Aiuto e Supporto: 'AYNI Help & Support'\nEntra in questa chat:\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n\n1 - Poni il tuo quesito, chiedi assistenza.\n2 - Terminata l\'assistenza, uscirete da quella Chat.\n\nPotrete rientrare tutte le volte che ce ne sia necessità.",
'BENVENUTO': "Benvenuto",
'EMAIL_VERIF': "Email Verificata",
'EMAIL_NON_VERIF': "Email Non Verificata\nleggi la tua casella email e trova **\"Confermare la Registrazione a Ayni\"**<br>e clicca sul bottone **\"Verifica Registrazione\"**",
'TELEGRAM_NOT_CONNECTED': "Telegram non associato al tuo account!",
'NESSUN_INVITATO': 'Non hai invitato nessuno',
'ZOOM_PARTECIPATO': 'Partecipazione ad almeno 1 Conferenza (Zoom)',
'SCRITTO_SOGNO': 'Hai scritto il tuo Sogno',
'INVITATI': 'persone registrate che hai invitato',
},
es: {
"L'Email è già stata Verificata": "L'Email è già stata Verificata",
"Nuova Registrazione": "Nuevo Registro",
"Effettuata una Nuova Registrazione": "Se ha realizado un nuevo registro",
"partecipanti": "participantes",
'TESTO_ASSISTENZA': "Chat d'Aiuto e Supporto: 'AYNI Help & Support'\nEntra in questa chat:\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n\n1 - Poni il tuo quesito, chiedi assistenza.\n2 - Terminata l\'assistenza, uscirete da quella Chat.\n\nPotrete rientrare tutte le volte che ce ne sia necessità.",
'BENVENUTO': "Benvenuto",
'EMAIL_VERIF': "Email Verificata",
'EMAIL_NON_VERIF': "Email Non Verificata\nleggi la tua casella email e trova **\"Confermare la Registrazione a Ayni\"**<br>e clicca sul bottone **\"Verifica Registrazione\"**",
'TELEGRAM_NOT_CONNECTED': "Telegram non associato al tuo account!",
'NESSUN_INVITATO': 'Non hai invitato nessuno',
'ZOOM_PARTECIPATO': 'Partecipazione ad almeno 1 Conferenza (Zoom)',
'SCRITTO_SOGNO': 'Hai scritto il tuo Sogno',
'INVITATI': 'persone registrate che hai invitato',
},
us: {
"partecipanti": "participants",
'TESTO_ASSISTENZA': "Chat d'Aiuto e Supporto: 'AYNI Help & Support'\nEntra in questa chat:\nhttps://t.me/joinchat/C741mlVmB_RMcOUpNqWC8w\n\n1 - Poni il tuo quesito, chiedi assistenza.\n2 - Terminata l\'assistenza, uscirete da quella Chat.\n\nPotrete rientrare tutte le volte che ce ne sia necessità.",
'BENVENUTO': "Benvenuto",
'EMAIL_VERIF': "Email Verificata",
'EMAIL_NON_VERIF': "Email Non Verificata\nleggi la tua casella email e trova **\"Confermare la Registrazione a Ayni\"**<br>e clicca sul bottone **\"Verifica Registrazione\"**",
'TELEGRAM_NOT_CONNECTED': "Telegram non associato al tuo account!",
'NESSUN_INVITATO': 'Non hai invitato nessuno',
'ZOOM_PARTECIPATO': 'Partecipazione ad almeno 1 Conferenza (Zoom)',
'SCRITTO_SOGNO': 'Hai scritto il tuo Sogno',
'INVITATI': 'persone registrate che hai invitato',
}
};
module.exports = {
INITDB_FIRSTIME: true,
@@ -64,6 +114,35 @@ module.exports = {
FIRST_PROJ: '__PROJECTS',
EXECUTE_CALCPROJ: true,
gettranslate(text, lang) {
try {
return textlang[lang][text]
}catch (e) {
return textlang['it'][text]
}
},
get__(text, msg) {
let lang = 'it';
if (msg)
lang = msg.from.language_code;
try {
return textlang[lang][text]
}catch (e) {
return textlang['it'][text]
}
},
getres__(text, res) {
// ++Todo: res estrarre la lingua
let lang = 'it';
try {
return textlang[lang][text]
}catch (e) {
return textlang['it'][text]
}
},
getHostname: function () {
return os.hostname()
},
@@ -173,9 +252,9 @@ module.exports = {
});
return false;
} else {
let conta = 0
let conta = 0;
let parallelSubscriptionCalls = subscriptions.map((subscription) => {
const trovati = subscriptions.length
const trovati = subscriptions.length;
return new Promise((resolve, reject) => {
const pushSubscription = {
endpoint: subscription.endpoint,
@@ -721,7 +800,7 @@ module.exports = {
}else if (campi.length > 4) {
namesurname.name = campi[0] + " " + campi[1];
namesurname.surname = " " + campi[2];
for (const ind = 3; ind < campi.length; ind++) {
for (let ind = 3; ind < campi.length; ind++) {
namesurname.surname += " " + campi[ind];
}
}

View File

@@ -6,9 +6,11 @@ module.exports = Object.freeze({
RIS_CODE_EMAIL_ALREADY_VERIFIED: -5,
RIS_CODE_EMAIL_VERIFIED: 1,
RIS_CODE_USER_NOT_THIS_APORTADOR: -75,
RIS_CODE_USER_EXTRALIST_NOTFOUND: -70,
RIS_CODE_USERNAME_ALREADY_EXIST: -60,
RIS_CODE_EMAIL_ALREADY_EXIST: -50,
RIS_CODE_EMAIL_NOT_EXIST: -45,
RIS_CODE_EMAIL_NOT_SENT: -40,
RIS_CODE_ERR_UNAUTHORIZED: -30,
RIS_CODE_LOGIN_ERR_GENERIC: -20,

View File

@@ -12,7 +12,7 @@ module.exports = {
},
fieldsUserToChange() {
return ['_id', 'username', 'email', 'name', 'surname', 'perm', 'date_reg', 'verified_email', 'ipaddr', 'lasttimeonline', 'profile', 'news_on', 'aportador_solidario', 'made_gift']
return ['_id', 'username', 'email', 'name', 'surname', 'perm', 'date_reg', 'date_temp_reg', 'verified_email', 'ipaddr', 'lasttimeonline', 'profile', 'calcstat', 'news_on', 'aportador_solidario', 'made_gift']
}
};