diff --git a/emails/admin/registration/it/html.pug b/emails/admin/registration/it/html.pug
index be3782a..23bf622 100644
--- a/emails/admin/registration/it/html.pug
+++ b/emails/admin/registration/it/html.pug
@@ -2,8 +2,18 @@ p #{name} #{surname} si è appena Registrato su #{nomeapp}
p Con i seguenti dati di accesso:
span Username:
strong #{username}
+span Nome:
+ strong #{user.name}
+span Cognome:
+ strong #{user.surname}
span Email:
strong #{emailto}
+span Cellulare:
+ strong #{user.profile.intcode_cell} #{user.profile.cell}
+span Nazionalità:
+ strong #{user.profile.nationality}
+span Username di chi lo ha Invitato:
+ strong #{user.aportador_solidario}
p
Saluti
style(type="text/css").
diff --git a/emails/newsletter/it/html.pug b/emails/newsletter/it/html.pug
index 36793d4..c2fbd31 100644
--- a/emails/newsletter/it/html.pug
+++ b/emails/newsletter/it/html.pug
@@ -82,7 +82,7 @@ html
td(class="emailContainer", valign="top")
each event in arrevents
- - var urlevent = baseurl + '/event/' + event.typol + '/' + event._id
+ - var urlevent = baseurl + '/event/' + event.typol + '?eventid=' + event._id
- var imgev = event.img_small
- var mydate = prettyDate(event.dateTimeStart)
unless (imgev)
@@ -91,9 +91,9 @@ html
- var teacher2 = ''
- var contrib = ''
- var myclteach = 'q-chip'
- - if (event.op1[0])
+ - if (event.op1[0] && event.op1[0].username !== 'nessuno')
- teacher1 = event.op1[0].name + ' ' + event.op1[0].surname
- - if (event.op2[0])
+ - if ((event.op2[0] && event.op2[0].username !== 'nessuno'))
- teacher2 = event.op2[0].name + ' ' + event.op2[0].surname
- myclteach = 'q-chip2'
diff --git a/package.json b/package.json
index 6ac51ff..e159deb 100644
--- a/package.json
+++ b/package.json
@@ -36,6 +36,7 @@
"mysql": "^2.17.1",
"node-cron": "^2.0.3",
"node-pre-gyp": "^0.11.0",
+ "node-telegram-bot-api": "^0.40.0",
"nodemailer": "^4.6.8",
"preview-email": "0.0.8",
"pug": "^2.0.4",
diff --git a/src/server/config/config.js b/src/server/config/config.js
index c9cc0d8..1bcdd60 100644
--- a/src/server/config/config.js
+++ b/src/server/config/config.js
@@ -17,6 +17,7 @@ process.env.DATABASE = process.env.DATABASE || 'FreePlanet';
process.env.MONGODB_URI = process.env.DOMAIN + process.env.DATABASE;
if (process.env.NODE_ENV === 'production') {
+ // ---------------- AMBIENTE DI PRODUZIONE !!!!!!!!!! --------------------
MYAPPS = [
{
idapp: '1',
@@ -27,6 +28,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'https://freeplanet.app',
portapp: '0',
dir: '/var/www/www.freeplanet.app',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '2',
@@ -34,9 +39,13 @@ if (process.env.NODE_ENV === 'production') {
adminemail: 'pao.loarena77@gmail.com',
manageremail: 'info@associazioneshen.it',
replyTo: 'info@associazioneshen.it',
- host: 'http://associazioneshen.it',
+ host: 'https://www.associazioneshen.it',
portapp: '0',
dir: '/var/www/associazioneshen.it',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '3',
@@ -47,6 +56,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://brigittemgdumont.com',
portapp: '0',
dir: '',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '4',
@@ -57,6 +70,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'https://mandala.freeplanet.app',
portapp: '0',
dir: '/var/www/mandala.freeplanet.app',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '6',
@@ -67,19 +84,28 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://mandalaperlanima.eu',
portapp: '0',
dir: '',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '7',
name: 'Notevole',
- adminemail: 'pao.loarena77@gmail.com',
+ adminemail: 'notevole.ayni@gmail.com',
manageremail: '',
replyTo: '',
host: 'https://notevole.freeplanet.app',
portapp: '0',
dir: '/var/www/notevole.freeplanet.app',
+ email_from: 'notevole.ayni@gmail.com',
+ email_pwd: '2e6ed34db0ef8fdc98e8a6872ec09a64350235c1ad7b756aa94047dec441d363xNvZnACxWSqSGu3lXcVyTuQiPR2ixYYf/HoY3agbNYU=',
+ telegram_key:'1037577457:AAGQbdIuYoB838v61ewJ0Hearx9UPpTBhMI',
+ telegram_bot_name: 'notevoleaynibot',
},
];
} else if (process.env.NODE_ENV === 'test') {
+ // ---------------- AMBIENTE DI TEST --------------------
MYAPPS = [
{
idapp: '1',
@@ -90,6 +116,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'https://test.freeplanet.app',
portapp: '0',
dir: '/var/www/www.freeplanet.app',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '2',
@@ -100,6 +130,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://test.associazioneshen.it',
portapp: '0',
dir: '/var/www/associazioneshen.it',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '3',
@@ -109,6 +143,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://test.brigittemgdumont.com',
portapp: '0',
dir: '',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '4',
@@ -118,6 +156,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'https://mandala.freeplanet.app',
portapp: '0',
dir: '/var/www/mandalatest.freeplanet.app',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '6',
@@ -127,6 +169,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://test.mandalaperlanima.eu',
portapp: '0',
dir: '',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '7',
@@ -136,9 +182,14 @@ if (process.env.NODE_ENV === 'production') {
host: 'https://testnotevole.freeplanet.app',
portapp: '0',
dir: '/var/www/testnotevole.freeplanet.app',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '2df135e2b6c02b2c68ec6bf6b103751fcb4dfc48c57d0acb302482358ee8141fmaDuooPabDvlThiBI2XMyA==',
+ telegram_key:'1037577457:AAGQbdIuYoB838v61ewJ0Hearx9UPpTBhMI',
+ telegram_bot_name: 'notevoleaynibot',
},
];
} else {
+ // ---------------- AMBIENTE IN L O C A L E --------------------
MYAPPS = [
{
idapp: '1',
@@ -149,6 +200,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://localhost',
portapp: '8080',
dir: '/home/paolo/myproject/freeplanet/dist/spa',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '66ffeb915e71fada64ad5c26947dd087c262be3b343734a0447c6dee534b888aZcfbjXEuMBWKxvbh60cniw==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '2',
@@ -159,6 +214,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://localhost',
portapp: '8081',
dir: '/home/paolo/myproject/associazioneShen/dist/spa',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '66ffeb915e71fada64ad5c26947dd087c262be3b343734a0447c6dee534b888aZcfbjXEuMBWKxvbh60cniw==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '3',
@@ -168,6 +227,8 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://localhost',
portapp: '8082',
dir: '',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '66ffeb915e71fada64ad5c26947dd087c262be3b343734a0447c6dee534b888aZcfbjXEuMBWKxvbh60cniw==',
},
{
idapp: '4',
@@ -177,6 +238,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://localhost',
portapp: '8084',
dir: '',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '66ffeb915e71fada64ad5c26947dd087c262be3b343734a0447c6dee534b888aZcfbjXEuMBWKxvbh60cniw==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '6',
@@ -186,6 +251,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://localhost',
portapp: '8083',
dir: '',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '66ffeb915e71fada64ad5c26947dd087c262be3b343734a0447c6dee534b888aZcfbjXEuMBWKxvbh60cniw==',
+ telegram_key:'',
+ telegram_bot_name: '',
},
{
idapp: '7',
@@ -195,6 +264,10 @@ if (process.env.NODE_ENV === 'production') {
host: 'http://localhost',
portapp: '8085',
dir: '',
+ email_from: 'info.pianetalibero@gmail.com',
+ email_pwd: '66ffeb915e71fada64ad5c26947dd087c262be3b343734a0447c6dee534b888aZcfbjXEuMBWKxvbh60cniw==',
+ telegram_bot_name: 'paotestlocalebot',
+ telegram_key:'353996190:AAEcEbfrm_zTK6mBKf8ye9j-PXt958SDxew',
},
];
diff --git a/src/server/models/paymenttype.js b/src/server/models/paymenttype.js
new file mode 100644
index 0000000..75591e6
--- /dev/null
+++ b/src/server/models/paymenttype.js
@@ -0,0 +1,48 @@
+const mongoose = require('mongoose');
+const Schema = mongoose.Schema;
+
+const tools = require('../tools/general');
+
+mongoose.Promise = global.Promise;
+mongoose.level = "F";
+
+
+// Resolving error Unknown modifier: $pushAll
+mongoose.plugin(schema => {
+ schema.options.usePushEach = true
+});
+
+const PaymentTypeSchema = new Schema({
+ idapp: {
+ type: String,
+ },
+ key: {
+ type: String,
+ },
+ label: {
+ type: String,
+ },
+});
+
+PaymentTypeSchema.statics.getFieldsForSearch = function () {
+ return ['label']
+};
+
+PaymentTypeSchema.statics.executeQueryTable = function (idapp, params) {
+ params.fieldsearch = this.getFieldsForSearch();
+ return tools.executeQueryTable(this, idapp, params);
+};
+
+PaymentTypeSchema.statics.findAllIdApp = function (idapp) {
+ const PaymentType = this;
+
+ const myfind = { idapp };
+
+ return PaymentType.find(myfind, (err, arrrec) => {
+ return arrrec
+ });
+};
+
+const PaymentType = mongoose.model('Paymenttype', PaymentTypeSchema);
+
+module.exports = { PaymentType };
diff --git a/src/server/models/user.js b/src/server/models/user.js
index 6bc9ca4..7e66529 100644
--- a/src/server/models/user.js
+++ b/src/server/models/user.js
@@ -136,9 +136,16 @@ var UserSchema = new mongoose.Schema({
email_paypal: {
type: String
},
+ paymenttypes: [],
username_telegram: {
type: String
},
+ teleg_id: {
+ type: Number
+ },
+ teleg_checkcode: {
+ type: Number
+ },
dateofbirth: {
type: Date,
},
@@ -404,6 +411,50 @@ UserSchema.statics.getEmailByUsername = async function (idapp, username) {
});
};
+UserSchema.statics.UserByIdTelegram = async function (idapp, teleg_id) {
+ const User = this;
+
+ return await User.findOne({ idapp, 'profile.teleg_id': teleg_id })
+ .then((rec) => {
+ return (!!rec) ? rec._doc : null;
+ }).catch((e) => {
+ console.error('UserExistByIdTelegram', e);
+ });
+};
+
+UserSchema.statics.SetTelegramCheckCode = async function (idapp, username, teleg_checkcode) {
+ const User = this;
+
+ const fields_to_update = {
+ 'profile.teleg_checkcode': teleg_checkcode
+ };
+
+ return await User.findOneAndUpdate({
+ idapp,
+ username
+ }, { $set: fields_to_update }, { new: false }).then((record) => {
+ return !!record;
+ });
+
+};
+
+UserSchema.statics.SetTelegramIdSuccess = async function (idapp, username, teleg_id) {
+ const User = this;
+
+ const fields_to_update = {
+ 'profile.teleg_id': teleg_id,
+ 'profile.teleg_checkcode': 0
+ };
+
+ return await User.findOneAndUpdate({
+ idapp,
+ username
+ }, { $set: fields_to_update }, { new: false }).then((record) => {
+ return record;
+ });
+
+};
+
UserSchema.statics.getUsersList = function (idapp) {
const User = this;
@@ -463,6 +514,32 @@ UserSchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params);
};
+UserSchema.statics.getDashboard = async function (idapp, aportador_solidario, username) {
+ try {
+
+ // DATA: username, name, surname, email, intcode_cell, cell
+ const dashboard = {
+ aportador: {},
+ downline: []
+ };
+
+ // Data of my Aportador
+ dashboard.aportador = await User.getUserShortDataByUsername(idapp, aportador_solidario);
+
+ // Data of my Downline
+ dashboard.downline = await User.getDownlineByUsername(idapp, username);
+
+ for (let index = 0; index < dashboard.downline.length; ++index) {
+ dashboard.downline[index].downline = await User.getDownlineByUsername(idapp, dashboard.downline[index].username);
+ }
+ return dashboard;
+ } catch (e) {
+ console.error(e);
+ return false;
+ }
+};
+
+
if (tools.INITDB_FIRSTIME) {
console.log(' createIndex User Index...');
// UserSchema.index({ username: 'text', name: 'text', surname: 'text', email: 'text' });
diff --git a/src/server/router/dashboard_router.js b/src/server/router/dashboard_router.js
index 4e7f28d..6a727b0 100644
--- a/src/server/router/dashboard_router.js
+++ b/src/server/router/dashboard_router.js
@@ -16,36 +16,16 @@ const _ = require('lodash');
const { ObjectID } = require('mongodb');
-
router.post('/', authenticate, async (req, res) => {
const idapp = req.body.idapp;
- try {
- const aportador_solidario = req.user.aportador_solidario;
+ const aportador_solidario = req.user.aportador_solidario;
- // DATA: username, name, surname, email, intcode_cell, cell
- const dashboard = {
- aportador: {},
- downline: []
- };
-
- // Data of my Aportador
- dashboard.aportador = await User.getUserShortDataByUsername(idapp, aportador_solidario);
-
- // Data of my Downline
- dashboard.downline = await User.getDownlineByUsername(idapp, req.user.username);
-
- for (let index = 0; index < dashboard.downline.length; ++index) {
- dashboard.downline[index].downline = await User.getDownlineByUsername(idapp, dashboard.downline[index].username);
- }
-
- // Extract all the todos of the userId only
- // tools.mylog('dashboard', dashboard);
+ const dashboard = User.getDashboard(idapp, aportador_solidario, req.user.username);
+ if (dashboard)
res.send({ dashboard });
- } catch (e) {
- console.error(e);
+ else
res.status(400).send(e);
- }
});
diff --git a/src/server/router/index_router.js b/src/server/router/index_router.js
index 926e6c4..f44dc76 100644
--- a/src/server/router/index_router.js
+++ b/src/server/router/index_router.js
@@ -27,6 +27,7 @@ const { Operator } = require('../models/operator');
const { Where } = require('../models/where');
const { MyEvent } = require('../models/myevent');
const { Contribtype } = require('../models/contribtype');
+const { PaymentType } = require('../models/paymenttype');
const { Discipline } = require('../models/discipline');
const { Newstosent } = require('../models/newstosent');
const { MyPage } = require('../models/mypage');
@@ -161,6 +162,8 @@ function getTableByTableName(tablename) {
mytable = MyEvent;
else if (tablename === 'contribtype')
mytable = Contribtype;
+ else if (tablename === 'paymenttypes')
+ mytable = PaymentType;
else if (tablename === 'disciplines')
mytable = Discipline;
else if (tablename === 'newstosent')
@@ -244,7 +247,7 @@ router.patch('/chval', authenticate, (req, res) => {
const mytable = getTableByTableName(mydata.table);
const fieldsvalue = mydata.fieldsvalue;
- // tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue);
+ tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue);
// If I change my record...
if ((!User.isAdmin(req.user) && !User.isManager(req.user)) && !(req.user._id.toString() === id)) {
@@ -373,6 +376,7 @@ router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) =>
const operators = Operator.findAllIdApp(idapp);
const wheres = Where.findAllIdApp(idapp);
const contribtype = Contribtype.findAllIdApp(idapp);
+ const paymenttype = PaymentType.findAllIdApp(idapp);
const disciplines = Discipline.findAllIdApp(idapp);
const settings = Settings.findAllIdApp(idapp, false);
@@ -386,7 +390,7 @@ 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])
+ return Promise.all([bookedevent, eventlist, operators, wheres, contribtype, settings, permissions, disciplines, newstosent, mailinglist, mypage, gallery, paymenttype])
.then((arrdata) => {
// console.table(arrdata);
const myuser = req.user;
@@ -407,6 +411,7 @@ router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) =>
mailinglist: arrdata[9],
mypage: arrdata[10],
gallery: arrdata[11],
+ paymenttypes: arrdata[12],
myuser,
});
})
diff --git a/src/server/router/users_router.js b/src/server/router/users_router.js
index d718842..57544f8 100644
--- a/src/server/router/users_router.js
+++ b/src/server/router/users_router.js
@@ -147,9 +147,9 @@ router.post('/login', (req, res) => {
var user = new User(body);
// const subs = _.pick(req.body, ['subs']);
- tools.mylog("LOGIN: username: " + user.username + " pwd = " + user.password);
+ // tools.mylog("LOGIN: username: " + user.username + " pwd = " + user.password);
- tools.mylog("user REC:", user);
+ // tools.mylog("user REC:", user);
if (body.keyappid !== process.env.KEY_APP_ID)
return res.status(400).send();
@@ -180,7 +180,7 @@ router.post('/login', (req, res) => {
// }
// tools.mylog("user.verified_email:" + user.verified_email);
- tools.mylog("usertosend.userId", usertosend.userId);
+ // tools.mylog("usertosend.userId", usertosend.userId);
return { usertosend, token }
@@ -198,7 +198,7 @@ router.post('/login', (req, res) => {
return { usertosend: myris.usertosend, token: myris.token, subsExistonDb: false }
})
}).then(myris => {
- console.log('res', myris.token, myris.usertosend);
+ // console.log('res', myris.token, myris.usertosend);
// SEND TOKEN AND CODE RESULT
res.header('x-auth', myris.token).send({
diff --git a/src/server/sendemail.js b/src/server/sendemail.js
index ed597e4..2e6d22f 100644
--- a/src/server/sendemail.js
+++ b/src/server/sendemail.js
@@ -58,21 +58,26 @@ module.exports = {
}
// if (!transport) {
- // transport = this.getTransport();
+ // transport = this.getTransport(mylocalsconf);
// }
+ // console.log('1 . transport', transport);
+
if (transport) {
paramemail.transport = transport;
} else {
+ // console.log('1b . transport gmail');
paramemail.transport = {
service: 'gmail',
auth: {
- user: process.env.EMAIL_FROM,
- pass: process.env.EMAIL_PW
+ user: tools.getEmailByIdApp(mylocalsconf.idapp),
+ pass: tools.getPwdByIdApp(mylocalsconf.idapp)
}
}
}
+ // console.log('2 . paramemail.transport', paramemail.transport);
+
// console.log('paramemail', paramemail);
const email = new Email(paramemail);
@@ -86,11 +91,11 @@ module.exports = {
locals: mylocalsconf,
})
.then((ris) => {
- console.log('ris EMAIL', ris);
+ // console.log('ris EMAIL', ris);
return !!ris
})
.catch((err) => {
- console.error('Error: ', err);
+ console.error('sendEmail_base Error: ', err);
return false
});
},
@@ -99,7 +104,7 @@ module.exports = {
// setup e-mail data with unicode symbols
var mailOptions = {
- from: process.env.EMAIL_FROM, // sender address
+ from: tools.getEmailByIdApp(mylocalsconf.idapp), // sender address
to: to,
generateTextFromHTML: true,
subject: subject,
@@ -110,13 +115,13 @@ module.exports = {
mailOptions['reply-to'] = replyTo;
if (process.env.SEND_EMAIL === 1) {
- console.log("SEND EMAIL smtpTransport");
+ console.log("SEND EMAIL...");
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
} else {
- console.log("Message sent: " + response);
+ console.log("Email Inviata RISPOSTA: " + response);
}
});
} else {
@@ -148,6 +153,7 @@ module.exports = {
console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
mylocalsconf = {
+ idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
@@ -157,20 +163,22 @@ module.exports = {
surname: user.surname,
forgetpwd: "",
emailto: emailto,
+ user,
};
this.sendEmail_base('registration/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));
// Send to the Admin an Email
- this.sendEmail_base('admin/registration/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
+ this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
if (tools.isManagAndAdminDifferent(idapp)) {
- this.sendEmail_base('admin/registration/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
+ this.sendEmail_base('admin/registration/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
},
sendEmail_RequestNewPassword: async function (lang, emailto, idapp, tokenforgot) {
mylocalsconf = {
+ idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
@@ -188,6 +196,7 @@ module.exports = {
tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp);
mylocalsconf = {
+ idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
@@ -216,10 +225,10 @@ module.exports = {
this.sendEmail_base('booking/' + texthtml + '/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));
// Send Email also to the Admin
- this.sendEmail_base('admin/' + texthtml + '/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
+ this.sendEmail_base('admin/' + texthtml + '/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
if (tools.isManagAndAdminDifferent(idapp)) {
- this.sendEmail_base('admin/' + texthtml + '/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
+ this.sendEmail_base('admin/' + texthtml + '/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
}));
@@ -231,6 +240,7 @@ module.exports = {
tools.mylog('sendEmail_CancelBooking');
mylocalsconf = {
+ idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
@@ -248,10 +258,10 @@ module.exports = {
this.sendEmail_base('booking/cancelbooking/' + lang, emailto, mylocalsconf, tools.getreplyToEmailByIdApp(idapp));
// Send Email also to the Admin
- this.sendEmail_base('admin/cancelbooking/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
+ this.sendEmail_base('admin/cancelbooking/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
if (tools.isManagAndAdminDifferent(idapp)) {
- this.sendEmail_base('admin/cancelbooking/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
+ this.sendEmail_base('admin/cancelbooking/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
},
@@ -261,6 +271,7 @@ module.exports = {
tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp);
mylocalsconf = {
+ idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
@@ -289,13 +300,13 @@ module.exports = {
console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
mylocalsconf = {
+ idapp,
dataemail: await this.getdataemail(idapp),
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
name: user.name,
surname: user.surname,
emailto: user.email,
- idapp
};
const hash = tools.getHash(mylocalsconf.emailto);
@@ -327,10 +338,10 @@ module.exports = {
if (sendnews) {
// Send to the Admin an Email
- this.sendEmail_base('admin/added_to_newsletter/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
+ this.sendEmail_base('admin/added_to_newsletter/' + tools.LANGADMIN, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
if (tools.isManagAndAdminDifferent(idapp)) {
- this.sendEmail_base('admin/added_to_newsletter/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
+ this.sendEmail_base('admin/added_to_newsletter/' + tools.LANGADMIN, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
}
@@ -432,7 +443,7 @@ module.exports = {
return mydata
},
- getTransport: () => {
+ getTransport: (mylocalsconf) => {
// Create Transport
let smtpTransport = null;
@@ -445,7 +456,7 @@ module.exports = {
pass: mylocalsconf.dataemail.pwd_from
}
});
- } else if (mylocalsconf.dataemail.email_service === 'gmail') {
+ } else if (mylocalsconf.dataemail.email_service === 'gmail' && mylocalsconf.dataemail.email_service !== undefined) {
smtpTransport = {
service: 'gmail', //'Gmail',
auth: {
@@ -457,8 +468,8 @@ module.exports = {
smtpTransport = {
service: 'gmail',
auth: {
- user: process.env.EMAIL_FROM,
- pass: process.env.EMAIL_PW
+ user: tools.getEmailByIdApp(mylocalsconf.idapp),
+ pass: tools.getPwdByIdApp(mylocalsconf.idapp)
}
};
}
@@ -476,8 +487,8 @@ module.exports = {
const myarrevents = await MyEvent.getLastEvents(idapp);
mylocalsconf = {
- locale: lang,
idapp,
+ locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
arrevents: myarrevents,
baseurl: tools.getHostByIdApp(idapp),
@@ -492,7 +503,7 @@ module.exports = {
mynewsrec.templemail_str = mylocalsconf.dataemail.templ.subject;
mynewsrec.numemail_sent = await MailingList.getnumSent(idapp, id_newstosent);
- const smtpTransport = this.getTransport();
+ const smtpTransport = this.getTransport(mylocalsconf);
// LOOP USERS EMAIL
for (const user of userstosend) {
@@ -500,7 +511,7 @@ module.exports = {
const isok = await MailingList.isOk(idapp, user._id, id_newstosent);
if (isok) {
let secpause = await Settings.getValDbSettings(idapp, 'MSEC_PAUSE_SEND', process.env.DELAY_SENDEMAIL);
- if (secpause > process.env.DELAY_SENDEMAIL)
+ if (secpause < process.env.DELAY_SENDEMAIL)
secpause = process.env.DELAY_SENDEMAIL;
activate = await Newstosent.isActivated(id_newstosent);
@@ -607,13 +618,13 @@ module.exports = {
const myarrevents = await MyEvent.getLastEvents(idapp);
const myemail = await Settings.getValDbSettings(idapp, 'EMAIL_TEST');
mylocalsconf = {
+ idapp,
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
arrevents: myarrevents,
name: 'TestNome',
surname: 'TestCognome',
emailto: myemail,
- idapp,
baseurl: tools.getHostByIdApp(idapp),
hashemail: tools.getHash(myemail),
};
@@ -625,7 +636,7 @@ module.exports = {
this.replacefields(mylocalsconf);
- const smtpTransport = this.getTransport();
+ const smtpTransport = this.getTransport(mylocalsconf);
console.log('-> Invio Email TEST a', mylocalsconf.emailto, 'previewonly', previewonly);
return this.sendEmail_base('newsletter/' + lang, mylocalsconf.emailto, mylocalsconf, '', smtpTransport, previewonly);
diff --git a/src/server/server.js b/src/server/server.js
index 468c5f0..61dee7e 100644
--- a/src/server/server.js
+++ b/src/server/server.js
@@ -18,7 +18,6 @@ const sendemail = require('./sendemail');
const cron = require('node-cron');
-
i18n = require("i18n");
if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')) {
@@ -128,6 +127,7 @@ app.use('/admin', admin_router);
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
+
app.use(function (err, req, res, next) {
console.log('Error: ', err.message);
// console.trace();
@@ -139,6 +139,9 @@ if (app.get('env') === 'development') {
});
}
+require('./telegram/telegrambot');
+
+
// *** DB CONNECTIONS ***
// mysql_func.mySqlConn_Shen.connect((err) => {
// if (!err)
@@ -170,6 +173,12 @@ if (process.env.PROD !== 1) {
// testmsgwebpush();
// sendemail.testemail('2', 'it');
+ // let crypt = tools.cryptdata('');
+ // let decrypt = tools.decryptdata(crypt);
+
+ // console.log('crypted:', crypt);
+ // console.log('decrypted:', decrypt);
+
mycron();
}
diff --git a/src/server/telegram/telegrambot.js b/src/server/telegram/telegrambot.js
new file mode 100644
index 0000000..4167803
--- /dev/null
+++ b/src/server/telegram/telegrambot.js
@@ -0,0 +1,372 @@
+const tools = require('../tools/general');
+
+const appTelegram = ['7'];
+
+const printf = require('util').format;
+
+const { User } = require('../models/user');
+
+const Benvenuto = 'Benvenuto';
+
+const Menu = {
+ LAVAGNA: 'La tua Lavagna',
+ LINK_CONDIVIDERE: 'Tuo Link da condividere',
+ INFO: 'Informazioni',
+ ASSISTENZA: 'Assistenza',
+};
+
+const MenuStandard = [[Menu.LAVAGNA, Menu.LINK_CONDIVIDERE], [Menu.INFO], [Menu.ASSISTENZA]];
+
+const Status = {
+ NONE: 0,
+ VERIFIED: 1,
+ WAITFOR_USERNAME_BO: 102,
+ WAITFOR_VERIFY_CODE: 103,
+};
+
+const txt = {
+ 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_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_ERR_VERIFY_CODE: 'Codice di Verifica Errato! Reinserire il codice di 6 cifre.',
+ MSG_VERIFY_OK: 'Benvenuto %s. Ora sei correttamente verificato!',
+ MSG_ERR_UNKNOWN_VERIFY_CODE: 'Errore durante il salvataggio sul Server. Riprovare piú tardi'
+};
+
+const TelegramBot = require('node-telegram-bot-api');
+
+
+function getstr(lang, text) {
+ return text;
+}
+
+class Telegram {
+ constructor(idapp, bot) {
+ this.idapp = idapp;
+ this.bot = bot;
+ this.token = bot.token;
+ this.arrUsers = [];
+ }
+
+ async start(msg) {
+
+ // this.msgBenvenuto(msg.chat.id);
+
+ // Check if Present to the DB
+ if (!await this.alreadyExist(msg)) {
+ this.insertIntoDB(msg);
+ } else {
+ let rec = this.getRecInMem(msg);
+ if (!rec)
+ rec = this.addUser(msg);
+ 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)
+ }else if (msg.text === Menu.INFO) {
+ this.menuInformazioni(msg)
+ }
+ }
+
+ async menuLavagna(msg) {
+ const rec = this.getRecInMem(msg);
+ // console.log('rec', rec);
+ let mystr = '';
+ if (rec.user) {
+
+ 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 = `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 (numpersone > 0) {
+ mystr += `Persone che hai invitato (${numpersone}):\n`;
+ let index = 1;
+ dashboard.downline.forEach((user) => {
+ mystr += `${index}°: ${user.username} (${user.name} ${user.surname})`;
+ index++;
+ });
+ } else {
+ mystr += `Attualmente non hai invitato nessuna persona.\n`;
+ }
+
+
+ }
+ if (!!mystr)
+ this.sendMsg(msg.chat.id, mystr);
+ }
+
+
+ async menuLinkCondividere(msg) {
+ const rec = this.getRecInMem(msg);
+ if (rec.user) {
+ const mystr = tools.getHostByIdApp(this.idapp) + '/signup/' + rec.user.username;
+ this.sendMsg(msg.chat.id, mystr);
+ }
+ }
+ async menuInformazioni(msg) {
+ const mystr = 'Informazioni Aggiuntive: ...';
+ this.sendMsg(msg.chat.id, mystr);
+ }
+
+ async menuAssistenza(msg) {
+ const mystr = 'Per contattarci usa questa chat di gruppo: ....';
+ this.sendMsg(msg.chat.id, mystr);
+ }
+
+ existInMemory(msg) {
+ const rec = this.getRecInMem(msg);
+ return !!rec
+ }
+
+ getstatusInMemory(msg) {
+ const rec = this.getRecInMem(msg);
+ if (!!rec)
+ return rec.status;
+ else
+ return Status.NONE;
+ }
+
+ getRecInMem(msg) {
+ return this.arrUsers.find((rec) => rec.id === msg.from.id);
+ }
+
+ async setUsernameBo(msg) {
+ try {
+ const rec = this.getRecInMem(msg);
+ console.log('msg.text', msg.text);
+ const text = msg.text;
+ if (text.length < 20) {
+ if (rec) {
+ rec.username_bo = text;
+
+ // Check if username exist
+ const user = await User.findByUsername(this.idapp, rec.username_bo.toLowerCase());
+ if (!user) {
+ this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_NOT_FOUND)
+ } else {
+ 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)
+ }
+ }
+ } else if (text.length === 0) {
+ if (rec)
+ rec.status = Status.NONE;
+ this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA)
+ } else {
+ this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME)
+ }
+ } catch (e) {
+ console.error('Error setUsernameBo:', e)
+ }
+ }
+
+ async setVerifyCode(msg) {
+ try {
+ const rec = this.getRecInMem(msg);
+ const code = msg.text.toString().trim();
+ if (msg.text.length < 7) {
+ if (rec) {
+ if (code === msg.text) {
+ rec.status = Status.VERIFIED;
+ await User.SetTelegramIdSuccess(this.idapp, rec.username_bo, msg.from.id).then((recuser) => {
+ if (recuser) {
+ let name = recuser.name;
+ this.sendMsg(msg.from.id, printf(txt.MSG_VERIFY_OK, name))
+ } else {
+ this.sendMsg(msg.from.id, txt.MSG_ERR_UNKNOWN_VERIFY_CODE);
+ }
+ });
+
+ } else {
+ rec.retry++;
+ this.sendMsg(msg.from.id, txt.MSG_ERR_VERIFY_CODE)
+ }
+ }
+ } else if (msg.text.length === 0) {
+ if (rec)
+ rec.status = Status.NONE;
+ this.sendMsg(msg.from.id, txt.MSG_ERRORE_USERNAME_ANNULLA)
+ } else {
+ this.sendMsg(msg.from.id, txt.MSG_ERRORE_VERIFY_CODE_MAXLEN)
+ }
+ } catch (e) {
+ console.error('Error setVerifyCode', e);
+ }
+ }
+
+ async receiveMsg(msg) {
+ let status = this.getstatusInMemory(msg);
+ if (status === Status.NONE) {
+ await this.start(msg);
+ }
+
+ status = this.getstatusInMemory(msg);
+ if (status === Status.WAITFOR_USERNAME_BO) {
+ this.setUsernameBo(msg)
+ } else if (status === Status.WAITFOR_VERIFY_CODE) {
+ this.setVerifyCode(msg)
+ } else if (status === Status.NONE) {
+ this.start(msg);
+ } else if (status === Status.VERIFIED) {
+ // Check Menu
+ this.isMenu(msg);
+ }
+ }
+
+ async askVerifiedCode(msg) {
+
+ const rec = this.arrUsers.find((rec) => rec.id === msg.from.id);
+ if (!rec) {
+ await this.addUser(msg);
+
+ this.sendMsg(msg.chat.id, getstr(msg.from.language_code, txt.MSG_ASK_USERNAME_BO));
+ }
+
+ }
+
+ 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;
+ return !!rec
+ }
+
+ addUser(msg) {
+ const lang = msg.from.language_code;
+ const code = 100000 + Math.round(Math.random() * 899999);
+
+ const rec = {
+ id: msg.from.id,
+ code,
+ lang,
+ status: Status.WAITFOR_USERNAME_BO,
+ retry: 0,
+ username_bo: ''
+ };
+
+ this.arrUsers.push(rec);
+
+ return rec;
+
+ }
+
+ insertIntoDB(msg) {
+
+ this.askVerifiedCode(msg);
+
+ }
+
+ sendMsg(id, text) {
+ this.bot.sendMessage(id, text, {
+ "reply_markup": {
+ "keyboard": MenuStandard
+ }
+ });
+ }
+
+ msgBenvenuto(id) {
+
+ this.bot.sendMessage(id, Benvenuto, {
+ "reply_markup": {
+ "keyboard": MenuStandard
+ }
+ });
+ }
+}
+
+const arrTelegram = [];
+
+function getclTelegBytoken(token) {
+ const rec = arrTelegram.find((rec) => rec.cl.token === token)
+ if (!!rec)
+ return rec.cl;
+ else
+ return null;
+}
+
+for (const idapp of appTelegram) {
+
+ const token = tools.getTelegramKeyByIdApp(idapp);
+ // console.log('idapp', idapp, 'token', token);
+
+ if (!!token) {
+ const bot = new TelegramBot(token, { polling: true });
+
+ arrTelegram.push({ idapp, cl: new Telegram(idapp, bot) });
+
+ bot.onText(/\/start/, (msg) => {
+ const myclTelegram = getclTelegBytoken(bot.token);
+
+ myclTelegram.start(msg);
+
+
+ });
+
+ // Matches "/echo [whatever]"
+ bot.onText(/\/echo (.+)/, (msg, match) => {
+ // 'msg' is the received Message from Telegram
+ // 'match' is the result of executing the regexp above on the text content
+ // of the message
+
+
+ const chatId = msg.chat.id;
+ const resp = match[1]; // the captured "whatever"
+
+ // send back the matched "whatever" to the chat
+ bot.sendMessage(chatId, resp);
+ });
+
+ // Listen for any kind of message. There are different kinds of
+ // messages.
+ bot.on('message', (msg) => {
+
+ const myclTelegram = getclTelegBytoken(bot.token);
+
+ // console.log('msg', msg);
+ const chatId = msg.chat.id;
+
+ myclTelegram.receiveMsg(msg);
+ // var bye = "bye";
+ // if (msg.text.toString().toLowerCase().includes(bye)) {
+ // bot.sendMessage(msg.chat.id, "Hope to see you around again , Bye");
+ // }
+
+ // send a message to the chat acknowledging receipt of their message
+ // bot.sendMessage(chatId, 'Received your message');
+ });
+
+ // Handle callback queries
+ bot.on('callback_query', function onCallbackQuery(callbackQuery) {
+ console.log('callback_query', callbackQuery);
+
+ bot.answerCallbackQuery(callbackQuery.id, { url });
+ });
+ }
+
+}
+
+
+
diff --git a/src/server/tools/general.js b/src/server/tools/general.js
index 2370b12..7984c3f 100644
--- a/src/server/tools/general.js
+++ b/src/server/tools/general.js
@@ -20,10 +20,15 @@ const server_constants = require('./server_constants');
// SETTINGS WebPush Configuration
const webpush = require('web-push');
-const subject = process.env.URLBASE_APP1; //'mailto:' + process.env.EMAIL_FROM
+const subject = process.env.URLBASE_APP1;
const publicVapidKey = process.env.PUBLIC_VAPI_KEY;
const privateVapidKey = process.env.PRIVATE_VAPI_KEY;
+// Code goes here
+const keySize = 256;
+const ivSize = 128;
+const iterations = 100;
+
if (process.env.GCM_API_KEY !== "")
webpush.setGCMAPIKey(process.env.GCM_API_KEY);
@@ -34,6 +39,8 @@ webpush.setVapidDetails(subject, publicVapidKey, privateVapidKey);
module.exports = {
INITDB_FIRSTIME: true,
+ LANGADMIN: 'it',
+
TYPE_PROJECT: 1,
TYPE_TODO: 2,
@@ -398,6 +405,26 @@ module.exports = {
return '';
},
+ getEmailByIdApp: function (idapp) {
+ const myapp = MYAPPS.find((item) => item.idapp === idapp);
+ return (myapp) ? myapp.email_from : ''
+ },
+
+ getPwdByIdApp: function (idapp) {
+ const myapp = MYAPPS.find((item) => item.idapp === idapp);
+ return (myapp) ? this.decryptdata(myapp.email_pwd) : ''
+ },
+
+ getTelegramBotNameByIdApp: function (idapp) {
+ const myapp = MYAPPS.find((item) => item.idapp === idapp);
+ return (myapp) ? myapp.telegram_bot_name : ''
+ },
+
+ getTelegramKeyByIdApp: function (idapp) {
+ const myapp = MYAPPS.find((item) => item.idapp === idapp);
+ return (myapp) ? myapp.telegram_key : ''
+ },
+
getQueryTable(idapp, params) {
// console.log('idapp', idapp);
// console.table(params);
@@ -514,15 +541,60 @@ module.exports = {
return CryptoJS.SHA512(mystr, { outputLength: 256 }).toString();
},
+ encrypt(msg, pass) {
+ var salt = CryptoJS.lib.WordArray.random(128 / 8);
+
+ var key = CryptoJS.PBKDF2(pass, salt, {
+ keySize: keySize / 32,
+ iterations: iterations
+ });
+
+ var iv = CryptoJS.lib.WordArray.random(128 / 8);
+
+ var encrypted = CryptoJS.AES.encrypt(msg, key, {
+ iv: iv,
+ padding: CryptoJS.pad.Pkcs7,
+ mode: CryptoJS.mode.CBC
+
+ });
+
+ // salt, iv will be hex 32 in length
+ // append them to the ciphertext for use in decryption
+ var transitmessage = salt.toString() + iv.toString() + encrypted.toString();
+ return transitmessage;
+ },
+
+ decrypt(transitmessage, pass) {
+ var salt = CryptoJS.enc.Hex.parse(transitmessage.substr(0, 32));
+ var iv = CryptoJS.enc.Hex.parse(transitmessage.substr(32, 32))
+ var encrypted = transitmessage.substring(64);
+
+ var key = CryptoJS.PBKDF2(pass, salt, {
+ keySize: keySize / 32,
+ iterations: iterations
+ });
+
+ var decrypted = CryptoJS.AES.decrypt(encrypted, key, {
+ iv: iv,
+ padding: CryptoJS.pad.Pkcs7,
+ mode: CryptoJS.mode.CBC
+
+ });
+ return decrypted;
+ },
+
cryptdata(mydata) {
// Encrypt
- return CryptoJS.AES.encrypt(JSON.stringify(data), process.env.SECRK);
+ //return CryptoJS.AES.encrypt(JSON.stringify(mydata), process.env.SECRK);
+ return this.encrypt(mydata, process.env.SECRK);
},
+
decryptdata(mydatacrypted) {
// Decrypt
- const bytes = CryptoJS.AES.decrypt(mydatacrypted.toString(), process.env.SECRK);
- return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
+ // const bytes = CryptoJS.AES.decrypt(mydatacrypted.toString(), process.env.SECRK);
+ // return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
+ return this.decrypt(mydatacrypted, process.env.SECRK).toString(CryptoJS.enc.Utf8);
},
BoolToInt(mybool) {
@@ -575,7 +647,7 @@ module.exports = {
mkdirpath(dirPath) {
// if (!fs.accessSync(dirPath, fs.constants.R_OK | fs.constants.W_OK)) {
- if (!fs.existsSync(dirPath)){
+ if (!fs.existsSync(dirPath)) {
try {
fs.mkdirSync(dirPath, { recursive: true });
}