- Create Newsletter Page: MailingList (without the class style, using Gulp tasks)#94

This commit is contained in:
Paolo Arena
2019-11-21 00:18:40 +01:00
parent 20a3120054
commit f7fa0c4909
54 changed files with 675 additions and 51 deletions

View File

@@ -0,0 +1 @@

View File

@@ -0,0 +1,76 @@
class CParamsQuery {
constructor(params) {
this.startRow = params.startRow;
this.endRow = params.endRow;
// this.count = params.count;
this.filter = params.filter;
this.sortBy = params.sortBy;
this.descending = params.descending;
}
}
/**
* Query blog posts by user -> paginated results and a total count.
* @param userId {ObjectId} ID of user to retrieve blog posts for
* @param startRow {Number} First row to return in results
* @param endRow {Number} Last row to return in results
* @param [filter] {Object} Optional extra matching query object
* @param [sort] {Object} Optional sort query object
* @returns {Object} Object -> `{ rows, count }`
*/
function queryBlogPostsByUser (userId, startRow, endRow, filter = {}, sort = false) {
const User = this;
if (!(user instanceof mongoose.Types.ObjectId)) {
throw new Error('userId must be ObjectId')
} else if (typeof startRow !== 'number') {
throw new Error('startRow must be number')
} else if (typeof endRow !== 'number') {
throw new Error('endRow must be number')
}
const query = [
// more lookups go here if you need them
// we have a many-to-one from blogPost -> user
{ $lookup: {
from: 'users',
localField: 'user',
foreignField: '_id',
as: 'user'
} },
// each blog has a single user (author) so flatten it using $unwind
{ $unwind: '$user' },
// filter the results by our userId
{ $match: Object.assign({ 'user._id': userId }, filter) }
];
if (sort) {
// maybe we want to sort by blog title or something
query.push({ $sort: sort })
}
query.push(
{ $group: {
_id: null,
// get a count of every result that matches until now
count: { $sum: 1 },
// keep our results for the next operation
results: { $push: '$$ROOT' }
} },
// and finally trim the results to within the range given by start/endRow
{ $project: {
count: 1,
rows: { $slice: ['$results', startRow, endRow] }
} }
);
return User
.aggregate(query)
.then(([{ count, rows }]) => ({ count, rows }))
};
module.exports = { CParamsQuery, queryBlogPostsByUser };

133
src/server/config/config.js Normal file
View File

@@ -0,0 +1,133 @@
// still in app.js
const node_env = process.env.NODE_ENV || 'production';
var file = `.env.${node_env}`;
// GLOBALI (Uguali per TUTTI)
process.env.LINKVERIF_REG = '/vreg';
process.env.LINK_REQUEST_NEWPASSWORD = '/requestnewpwd';
process.env.LINK_CHECK_UPDATES = '/checkupdates';
process.env.LINK_UPDATE_PASSWORD = '/updatepwd';
process.env.KEY_APP_ID = 'KKPPAA5KJK435J3KSS9F9D8S9F8SD98F9SDF';
console.log("FILE : " + file);
require('dotenv').config({ path: file });
process.env.DATABASE = process.env.DATABASE || 'FreePlanet';
process.env.MONGODB_URI = process.env.DOMAIN + process.env.DATABASE;
if (process.env.NODE_ENV === 'production') {
MYAPPS = [
{
idapp: '1',
name: 'FreePlanet',
adminemail: 'paolo.arena77@gmail.com',
manageremail: '',
replyTo: 'paolo.arena77@gmail.com',
host: 'https://freeplanet.app',
portapp: '0',
},
{
idapp: '2',
name: 'Associazione Shen',
adminemail: 'pao.loarena77@gmail.com',
manageremail: 'info@associazioneshen.it',
replyTo: 'info@associazioneshen.it',
host: 'http://associazioneshen.it',
portapp: '0',
},
{
idapp: '3',
name: 'Brigitte MG Dumont',
adminemail: '',
manageremail: '',
replyTo: '',
host: 'http://brigittemgdumont.com',
portapp: '0',
},
{
idapp: '4',
name: 'Mandala per l\'Anima',
adminemail: '',
manageremail: '',
replyTo: '',
host: 'http://mandalaperlanima.eu',
portapp: '0',
}
];
} else if (process.env.NODE_ENV === 'test') {
MYAPPS = [
{
idapp: '1',
name: 'FreePlanet',
adminemail: 'paolo.arena77@gmail.com',
manageremail: '',
replyTo: 'paolo.arena77@gmail.com',
host: 'https://test.freeplanet.app',
portapp: '0',
},
{
idapp: '2',
name: 'Associazione Shen',
adminemail: 'pao.loarena77@gmail.com',
manageremail: '',
replyTo: 'info@associazioneshen.it',
host: 'http://test.associazioneshen.it',
portapp: '0',
},
{
idapp: '3',
name: 'Brigitte MG Dumont',
adminemail: '',
manageremail: '',
host: 'http://test.brigittemgdumont.com',
portapp: '0',
},
{
idapp: '4',
name: 'Mandala per l\'Anima',
adminemail: '',
manageremail: '',
host: 'http://test.mandalaperlanima.eu',
portapp: '0',
}
];
} else {
MYAPPS = [
{
idapp: '1',
name: 'FreePlanet',
adminemail: 'paolo.arena77@gmail.com',
manageremail: '',
replyTo: 'paolo.arena77@gmail.com',
host: 'http://localhost',
portapp: '8080',
},
{
idapp: '2',
name: 'Associazione Shen',
adminemail: 'paolo.arena77@gmail.com',
manageremail: '',
replyTo: 'info@associazioneshen.it',
host: 'http://localhost',
portapp: '8081',
},
{
idapp: '3',
name: 'Brigitte',
adminemail: 'paolo.arena77@gmail.com',
manageremail: '',
host: 'http://localhost',
portapp: '8082',
},
{
idapp: '4',
name: 'Mandala per l\'Anima',
adminemail: 'paolo.arena77@gmail.com',
manageremail: '',
host: 'http://localhost',
portapp: '8083',
}
];
}

47
src/server/db/mongoose.js Normal file
View File

@@ -0,0 +1,47 @@
var mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.level = "";
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', false);
var options = {
// user: process.env.UDB,
// pass: process.env.PDB,
useMongoClient: true,
// useNewUrlParser: true, // non supportato
promiseLibrary: require('bluebird')
// useCreateIndex: true,
// useFindAndModify: false,
// autoIndex: false, // Don't build indexes
// reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
// reconnectInterval: 500, // Reconnect every 500ms
// poolSize: 10, // Maintain up to 10 socket connections
// // If not connected, return errors immediately rather than waiting for reconnect
// bufferMaxEntries: 0,
// connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
// socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
// family: 4 // Use IPv4, skip trying IPv6
// keepAlive: true, // keepAlive is true by default since mongoose 5.2.0
// keepAliveInitialDelay: 300000 // keepAliveInitialDelay is the number of milliseconds to wait before initiating keepAlive on the socket.
};
// mongoose.connect(process.env.MONGODB_URI + '?authSource=admin', { options })
mongoose.connect(process.env.MONGODB_URI, options)
.then(() =>
console.log('connection succesful ' + process.env.MONGODB_URI + ' db: ' + process.env.DATABASE)
)
.catch((err) => console.error(err));
module.exports = {mongoose};

View File

@@ -0,0 +1,4 @@
{
"Email Verificata!": "Email Verificata!",
"partecipanti": "partecipanti"
}

View File

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

View File

@@ -0,0 +1,8 @@
{
"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

@@ -0,0 +1,62 @@
const server_constants = require('../tools/server_constants');
var {User} = require('../models/user');
const tools = require('../tools/general');
const authenticate = (req, res, next) => {
const token = req.header('x-auth');
// console.log('authenticate... ');
const access = 'auth';
User.findByToken(token, access).then((user) => {
if (!user) {
tools.mylog("TOKEN " + token);
tools.mylog(" NOT FOUND! (Maybe Connected to other Page) ACCESS: '" + access + "'");
return Promise.reject(server_constants.RIS_CODE_HTTP_INVALID_TOKEN);
// res.status().send();
}
// Save last time online
user.lasttimeonline = new Date();
return user.save().then(() => {
req.user = user;
req.token = token;
req.access = access;
next();
});
// tools.mylog('userid', user._id);
}).catch((e) => {
tools.mylog("ERR =", e);
res.status(server_constants.RIS_CODE_HTTP_INVALID_TOKEN).send();
});
};
const authenticate_noerror = (req, res, next) => {
const token = req.header('x-auth');
const access = 'auth';
User.findByToken(token, access).then((user) => {
if (!user) {
req.user = null;
req.token = null;
req.access = null;
}else {
req.user = user;
req.token = token;
req.access = access;
}
next();
}).catch((e) => {
req.user = null;
req.token = null;
req.access = null;
});
};
module.exports = {authenticate, authenticate_noerror};

View File

@@ -0,0 +1,110 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const bookingSchema = new Schema({
idapp: {
type: String,
},
userId: {
type: String,
},
id_bookedevent: {
type: String,
},
numpeople: {
type: Number,
},
infoevent: {
type: String,
},
msgbooking: {
type: String,
},
datebooked: {
type: Date,
},
modified: {
type: Boolean,
default: false
},
booked: {
type: Boolean,
},
});
bookingSchema.statics.findAllByUserIdAndIdApp = function (userId, idapp, sall) {
const Booking = this;
let myfind = {};
if (sall === '1')
myfind = { idapp, booked: true };
else
myfind = { userId, idapp, booked: true };
return Booking.find(myfind, (err, arrbooked) => {
// console.log('ris Booking:', arrbooked);
return arrbooked
});
};
function getUsersByBooking(idapp) {
const query = [
{
$match: { idapp }
},
{
$group: { _id: "$userId" }
},
{
$project: {
_id: {
$toString: "$userId"
}
}
},
{
$Lookup: {
from: "users",
localField: "userId", // field in my collection
foreignField: "ObjectId(_id)", // field in the 'from' collection
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$fromItems", 0] },] } }
},
{ $project: { username: 1, name: 1, surname: 1 } }
];
return query
}
bookingSchema.statics.findAllDistinctByBooking = function (idapp) {
const Booking = this;
const query = getUsersByBooking(idapp);
return Booking.aggregate(query)
.then(ris => {
return ris
});
};
const Booking = mongoose.model('Booking', bookingSchema);
module.exports = { Booking };

View File

@@ -0,0 +1,30 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const cfgserverSchema = new Schema({
chiave: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: true,
},
userId: {
type: String,
},
valore: {
type: String,
},
});
mongoose.model('cfgserver', cfgserverSchema);

View File

@@ -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 ContribtypeSchema = new Schema({
idapp: {
type: String,
},
label: {
type: String,
},
showprice: {
type: Boolean,
}
});
ContribtypeSchema.statics.getFieldsForSearch = function () {
return ['label']
};
ContribtypeSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
ContribtypeSchema.statics.findAllIdApp = function (idapp) {
const Contribtype = this;
const myfind = { idapp };
return Contribtype.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Contribtype = mongoose.model('Contribtype', ContribtypeSchema);
module.exports = { Contribtype };

View File

@@ -0,0 +1,86 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const DisciplineSchema = new Schema({
idapp: {
type: String,
},
order: {
type: Number,
},
typol_code: {
type: String,
},
label: {
type: String,
},
description: {
type: String,
},
linkpage: {
type: String,
},
color: {
type: String,
},
icon: {
type: String,
},
img_small: {
type: String,
},
img: {
type: String,
},
showinnewsletter: {
type: Boolean,
},
showinhome: {
type: Boolean,
},
teachers: [{
type: String,
}],
});
DisciplineSchema.statics.findAllIdApp = function (idapp) {
const Discipline = this;
const query = [
{ $match: { idapp } },
{ $sort: { order: 1 } }
];
return Discipline
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
DisciplineSchema.statics.getFieldsForSearch = function () {
return ['label', 'description']
};
DisciplineSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
const Discipline = mongoose.model('Discipline', DisciplineSchema);
module.exports = { Discipline };

View File

@@ -0,0 +1,59 @@
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 MailingListSchema = new Schema({
idapp: {
type: String,
},
email: {
type: String,
trim: true,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
lastid_newstosent: {
type: String
}
});
MailingListSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email']
};
MailingListSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
MailingListSchema.statics.findAllIdApp = function (idapp) {
const MailingList = this;
const myfind = { idapp };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return MailingList.find(myfind, (err, arrrec) => {
return arrrec
});
};
const MailingList = mongoose.model('MailingList', MailingListSchema);
module.exports = { MailingList };

View File

@@ -0,0 +1,152 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const tools = require('../tools/general');
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const MyEventSchema = new Schema({
idapp: {
type: String,
},
typol: {
type: String,
},
short_tit: {
type: String,
},
title: {
type: String,
},
details: {
type: String,
},
bodytext: {
type: String,
},
dateTimeStart: {
type: Date,
},
dateTimeEnd: {
type: Date,
},
bgcolor: {
type: String,
},
icon: {
type: String,
},
img_small: {
type: String,
},
img: {
type: String,
},
wherecode: {
type: String,
},
contribtype: {
type: String,
},
price: {
type: Number,
},
infoafterprice: {
type: String,
},
teacher: {
type: String,
},
teacher2: {
type: String,
},
infoextra: {
type: String,
},
linkpage: {
type: String,
},
linkpdf: {
type: String,
},
nobookable: {
type: Boolean,
},
news: {
type: Boolean,
},
canceled: {
type: Boolean,
},
deleted: {
type: Boolean,
},
dupId: {
type: mongoose.Schema.Types.ObjectId,
},
modified: {
type: Boolean,
},
});
MyEventSchema.statics.findAllIdApp = function (idapp) {
const Event = this;
const query = [
{ $match: { idapp } },
{ $sort: { dateTimeStart: 1 } }
];
return Event
.aggregate(query)
.then((arrrec) => {
return arrrec
})
};
MyEventSchema.statics.getLastEvents = function (idapp) {
const Event = this;
const lastn = 3;
const query = [
{ $match: { idapp } },
{ $sort: { dateTimeStart: 1 } }
];
return Event
.aggregate(query)
.then((arrrec) => {
return arrrec.slice(-lastn)
})
};
MyEventSchema.statics.getFieldsForSearch = function () {
return ['short_tit', 'title', 'teacher', 'details']
};
MyEventSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
if (tools.INITDB_FIRSTIME) {
// console.log(' createIndex MyEvent Index...');
// MyEventSchema.index({ short_tit: 'text', title: 'text', teacher: 'text', details: 'text' });
}
const MyEvent = mongoose.model('MyEvent', MyEventSchema);
module.exports = { MyEvent };

View File

@@ -0,0 +1,114 @@
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 NewstosentSchema = new Schema({
idapp: {
type: String,
},
label: {
type: String,
},
activate: {
type: Boolean,
default: false
},
numemail_tot: {
type: Number,
default: 0
},
numemail_sent: {
type: Number,
default: 0
},
datetoSent: {
type: Date
},
datestartJob: {
type: Date
},
datefinishJob: {
type: Date
},
lastemailsent_Job: {
type: Date
},
starting_job: {
type: Boolean,
default: false
},
finish_job: {
type: Boolean,
default: false
},
error_job: {
type: String,
}
});
NewstosentSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email']
};
NewstosentSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
NewstosentSchema.statics.findNewsletter_To_Send = function (idapp) {
const Newstosent = this;
return Newstosent.findOne({
datetoSent: { $gte: tools.IncDateNow(-1000 * 60 * 60) },
activate: true,
starting_job: false,
finish_job: false,
idapp
}).then((rec) => {
return (rec) ? rec._doc : null;
});
};
NewstosentSchema.statics.findNewsletterPending_To_Send = function (idapp) {
const Newstosent = this;
// Resend the Email after N hours no other email sent.
const numhours = 8;
return Newstosent.findOne({
datestartJob: { $lt: tools.IncDateNow(0) },
activate: true,
starting_job: true,
finish_job: false,
lastemailsent_Job: { $gte: tools.IncDateNow(-1000 * 60 * 60 * numhours) },
idapp
}).then((rec) => {
return (rec) ? rec._doc : null;
});
};
NewstosentSchema.statics.findAllIdApp = function (idapp) {
const Newstosent = this;
const myfind = { idapp };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return Newstosent.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Newstosent = mongoose.model('Newstosent', NewstosentSchema);
module.exports = { Newstosent };

View File

@@ -0,0 +1,112 @@
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 OperatorSchema = new Schema({
idapp: {
type: String,
},
username: {
type: String,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
email: {
type: String,
trim: true,
},
usertelegram: {
type: String,
},
cell: {
type: String,
trim: true,
},
img: {
type: String,
},
qualification: { // President, Vice-President, ecc...
type: String,
},
disciplines: {
type: String,
},
certifications: {
type: String,
},
webpage: {
type: String,
},
days_working: {
type: String,
},
facebook: {
type: String,
},
info: {
type: String,
},
intro: {
type: String,
},
offers: {
type: String,
},
skype: {
type: String,
},
});
OperatorSchema.statics.getEmailByUsername = async function (idapp, username) {
const Operator = this;
return await Operator.findOne({ idapp, username })
.then((arrrec) => {
return ((arrrec) ? arrrec.email : '');
}).catch((e) => {
console.error('getEmailByUsername', e);
});
};
OperatorSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email', 'cell']
};
OperatorSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
OperatorSchema.statics.findAllIdApp = function (idapp) {
const Operator = this;
const myfind = { idapp };
// Extract only the Teacher where in the users table the field permissions is set 'Teacher' bit.
return Operator.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Operator = mongoose.model('Operator', OperatorSchema);
module.exports = { Operator };

View File

@@ -0,0 +1,60 @@
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 PermissionSchema = new Schema({
_id: {
type: Number,
},
label: {
type: String,
default: ''
}
},{ _id : false });
PermissionSchema.pre('save', async function (next) {
if (this.isNew) {
const myrec = await Permission.findOne().limit(1).sort({_id:-1});
if (!!myrec) {
if (myrec._doc._id === 0)
this._id = 1;
else
this._id = myrec._doc._id * 2;
} else {
this._id = 1;
}
}
next();
});
PermissionSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, 0, params);
};
PermissionSchema.statics.findAllIdApp = function () {
const Permission = this;
const myfind = { };
return Permission.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Permission = mongoose.model('Permission', PermissionSchema);
module.exports = { Permission };

View File

@@ -0,0 +1,347 @@
var mongoose = require('mongoose');
const _ = require('lodash');
const tools = require('../tools/general');
var server_constants = require('../tools/server_constants');
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', process.env.DEBUG);
var ProjectSchema = new mongoose.Schema({
userId: {
type: String,
},
pos: {
type: Number,
},
descr: {
type: String,
},
longdescr: {
type: String,
},
typeproj: {
type: Number,
},
id_main_project: mongoose.Schema.Types.ObjectId,
id_parent: mongoose.Schema.Types.ObjectId,
priority: {
type: Number,
},
statusproj: {
type: Number,
default: 0
},
created_at: {
type: Date
},
modify_at: {
type: Date
},
completed_at: {
type: Date
},
expiring_at: {
type: Date,
},
enableExpiring: {
type: Boolean,
default: false
},
id_prev: mongoose.Schema.Types.ObjectId,
modified: {
type: Boolean,
},
live_url: {
type: String,
},
test_url: {
type: String,
},
totalphases: {
type: Number,
default: 1
},
actualphase: {
type: Number,
default: 1
},
hoursplanned: {
type: Number,
default: 0
},
hoursleft: {
type: Number,
default: 0
},
hoursworked: {
type: Number,
default: 0
},
themecolor: {
type: String,
default: ''
},
themebgcolor: {
type: String,
default: ''
},
progressCalc: {
type: Number,
default: 0
},
begin_development: {
type: Date,
},
begin_test: {
type: Date,
},
hoursweeky_plannedtowork: {
type: Number,
default: 0
},
endwork_estimate: {
type: Date
},
privacyread: {
type: String
},
privacywrite: {
type: String
}
});
ProjectSchema.methods.toJSON = function () {
var Project = this;
var projObject = Project.toObject();
// console.log(projObject);
return _.pick(projObject, tools.allfieldProjectWithId());
};
ProjectSchema.statics.findByUserIdAndIdParent = function (userId, id_parent) {
var Project = this;
if (userId === '') {
return Project.find({
'id_parent': id_parent,
});
} else {
return Project.find({
'userId': userId,
'id_parent': id_parent,
});
}
};
ProjectSchema.statics.findProjectByUserId = function (userId, idproj) {
var Project = this;
if (userId === '') {
return Project.findOne({
'_id': idproj,
});
} else {
return Project.findOne({
'userId': userId,
'_id': idproj,
});
}
};
ProjectSchema.statics.findAllProjByUserId = async function (userId) {
var Project = this;
return Project.aggregate([
{ $match: { $or: [{ privacyread: server_constants.Privacy.all }, { userId: userId }] } },
{
$graphLookup: {
from: "projects",
startWith: "$id_main_project",
connectFromField: "id_main_project",
connectToField: "_id",
as: "ris",
restrictSearchWithMatch: { $or: [{ privacyread: server_constants.Privacy.all }, { userId: userId }] }
}
},
{ $match: { "ris.privacyread": { $exists: true } } },
// {
// $project: {
// "descr": 1,
// "typeproj": 1,
// "id_main_project": 1,
// }
// }
]).then(ris1 => {
// console.log('findAllProjByUserId', ris1);
return ris1;
})
// return Project.find({
// $or: [
// { 'userId': userId },
// {'privacyread' : server_constants.Privacy.all}
// ],
// $or: [
// { 'typeproj': server_constants.TypeProj.TYPE_PROJECT },
// { 'typeproj': server_constants.TypeProj.TYPE_SUBDIR }
// ],
};
ProjectSchema.statics.getArrIdParentInTable = function (userId) {
var Project = this;
return Project.find({ 'userId': userId }).distinct("id_parent")
};
ProjectSchema.statics.getIdParentByIdProj = function (idProj) {
var Project = this;
console.log('INIT getIdParentByIdProj', idProj);
return Project.findOne({ '_id': ObjectId(idProj) }).then(rec => {
if (!!rec) {
console.log('getIdParentByIdProj', rec.id_parent);
return rec.id_parent;
} else {
return '';
}
}).catch(e => {
return '';
})
};
ProjectSchema.statics.creaProjMain = async function () {
const projmain = {
descr: process.env.PROJECT_DESCR_MAIN,
longdescr: process.env.PROJECT_DESCR_MAIN,
typeproj: 1,
id_main_project: null,
id_parent: null,
privacyread: server_constants.Privacy.all
};
return await new Project(projmain).save()
.then(ris => {
console.log('ris', ris);
if (!!ris)
return ris._doc;
else
return null;
});
};
ProjectSchema.statics.getAllProjects = async function (userId) {
var Project = this;
// console.log('getAllProjects');
let obj = [];
const projbase = await Project.findOne( { descr: process.env.PROJECT_DESCR_MAIN })
.then(ris => {
if (!!ris) {
// console.log('ris', ris);
if (!!ris._doc)
return ris._doc;
else
return null;
}else {
return Project.creaProjMain();
}
});
obj.arrproj = await Project.findAllProjByUserId(userId);
obj.arrproj.push(projbase);
return obj;
};
ProjectSchema.statics.enabletoModify = async function (userId, idProj) {
var Project = this;
let obj = [];
return Project.findOne({
'_id': idProj,
$or: [{
'privacywrite': server_constants.Privacy.all,
'userId': userId
}]
}).then(ris => {
return (!!ris);
});
};
ProjectSchema.statics.updateCalc = async function (userId, idproj, objdatacalc, recIn) {
return new Promise((resolve, reject) => {
if (!!recIn) {
return resolve(recIn);
} else {
return resolve(Project.findProjectByUserId(userId, idproj))
}
}).then((myproj) => {
if (!!myproj) {
console.log('objdatacalc progressCalc', objdatacalc.mydata.progressCalc);
objdatacalc.setValuesToRecord(myproj);
// console.log('updateCalc', myproj._id, myproj.progressCalc);
return myproj.save()
.then(() => {
// console.log('salvato proj!');
return true;
})
.catch(err => {
console.log("Error updateCalc", err.message);
});
}
return false;
}).catch(e => {
console.log('Error: ', e);
return false;
});
};
ProjectSchema.pre('save', function (next) {
// var Project = this;
// console.log('Project.expiring_at', Project.expiring_at);
next();
});
var Project = mongoose.model('Projects', ProjectSchema);
module.exports = { Project };

View File

@@ -0,0 +1,112 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const sendmsgSchema = new Schema({
idapp: {
type: String,
},
source: {
page: { type: String },
event_id: { type: String }
},
origin: {
username: { type: String },
},
dest: {
idapp: { type: String, },
username: { type: String },
},
message: {
type: String,
},
datemsg: {
type: Date,
},
status: {
type: Number,
},
options: {
type: Number,
},
read: {
type: Boolean,
default: false
},
deleted: {
type: Boolean,
default: false
},
});
sendmsgSchema.statics.findAllMsgByUsernameIdAndIdApp = function (username, lastdataread, idapp) {
const SendMsg = this;
return SendMsg.find({
$and: [
{ $or: [ { 'dest.username': username }, { 'origin.username': username },] },
{ 'datemsg': {$gt: new Date(lastdataread)} },
{ idapp }
]
}).then((arrmsg) => {
console.log('arrmsg', arrmsg.length);
return arrmsg
}).catch((err) => {
console.error('err', err);
});
};
sendmsgSchema.statics.findLastGroupByUserIdAndIdApp = function (userId, username, idapp) {
const SendMsg = this;
return SendMsg.aggregate([
{
$match: {
$or: [{ 'origin.username': username }, { 'dest.username': username }, { idapp }],
$and: [{ idapp }]
}
},
{
$group:
{
_id: "$dest.username",
message: { $last: "$message" },
datemsg: { $last: "$datemsg" },
dest: { $last: "$dest" },
origin: { $last: "$origin" },
read: { $last: "$read" }
}
},
{
$sort: { datemsg: -1 }
},
])
.then((arrmsg) => {
// Remove duplicate
// Exclude my chat
const myarr = arrmsg.filter((ris) => ris._id !== username);
// console.table(myarr);
return myarr
}).catch((err) => {
console.error(err);
});
};
const SendMsg = mongoose.model('SendMsg', sendmsgSchema);
module.exports = { SendMsg };

View File

@@ -0,0 +1,79 @@
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 SettingsSchema = new Schema({
idapp: {
type: String,
},
key: {
type: String,
},
type: {
type: Number,
},
value_str: {
type: String,
},
value_date: {
type: Date,
},
value_num: {
type: Number,
}
});
SettingsSchema.statics.getFieldsForSearch = function () {
return ['key', 'value_str']
};
SettingsSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
SettingsSchema.statics.getValDbSettings = function (idapp, key) {
return Settings.findOne({ idapp, key })
.then((myrec) => {
console.log('getValDbSettings', myrec, 'idapp', idapp);
if (myrec) {
if (myrec.type === tools.FieldType.date)
return myrec.value_date;
if (myrec.type === tools.FieldType.number)
return myrec.value_num;
else
return myrec.value_str;
} else {
return ''
}
}).catch((err) => {
console.error('getValDbSettings', err);
return null;
});
};
SettingsSchema.statics.findAllIdApp = function (idapp) {
const Settings = this;
const myfind = { idapp };
return Settings.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Settings = mongoose.model('Settings', SettingsSchema);
module.exports = { Settings };

View File

@@ -0,0 +1,27 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.Promise = global.Promise;
mongoose.level = "F";
const { ObjectID } = require('mongodb');
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
const SubscriberSchema = new Schema({
endpoint: String,
keys: Schema.Types.Mixed,
userId: String,
access: String,
browser: String,
createDate: {
type: Date,
default: Date.now
}
});
mongoose.model('subscribers', SubscriberSchema);

473
src/server/models/todo.js Normal file
View File

@@ -0,0 +1,473 @@
var mongoose = require('mongoose');
const _ = require('lodash');
const tools = require('../tools/general');
var { Project } = require('./project');
var server_constants = require('../tools/server_constants');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', process.env.DEBUG);
var TodoSchema = new mongoose.Schema({
userId: {
type: String,
},
pos: {
type: Number,
},
category: mongoose.Schema.Types.ObjectId,
descr: {
type: String,
},
priority: {
type: Number,
},
statustodo: {
type: Number,
default: 0
},
created_at: {
type: Date
},
modify_at: {
type: Date
},
start_date: {
type: Date,
},
completed_at: {
type: Date
},
expiring_at: {
type: Date,
},
enableExpiring: {
type: Boolean,
default: false
},
id_prev: mongoose.Schema.Types.ObjectId,
progress: {
type: Number,
},
phase: {
type: Number,
},
assigned_to_userId: {
type: String,
},
hoursplanned: {
type: Number,
},
hoursworked: {
type: Number,
},
themecolor: {
type: String,
},
themebgcolor: {
type: String,
default: '',
},
modified: {
type: Boolean,
},
});
TodoSchema.methods.toJSON = function () {
var todo = this;
var todoObject = todo.toObject();
// console.log(todoObject);
return _.pick(todoObject, tools.allfieldTodoWithId());
};
TodoSchema.statics.findByUserIdAndIdParent = function (userId, category, phase = '') {
var Todo = this;
let tofind = {
'category': category,
};
if (userId !== '') {
tofind['userId'] = userId;
}
if (!!phase) {
tofind['phase'] = phase;
}
return Todo.find(tofind);
};
// User.find({ admin: true }).where('created_at').gt(monthAgo).exec(function(err, users) {
// if (err) throw err;
function getQueryFilterTodo(userId) {
myobj = [{ privacyread: server_constants.Privacy.all }, { userId: userId }];
return myobj;
}
function getQueryTodo(filterMatchBefore = {}, userId) {
let filterMatchAfter = {
$or: getQueryFilterTodo(userId)
};
let myobjField = getobjFieldTodo(true);
const query = [
{ $match: filterMatchBefore },
{
$lookup: {
from: "projects",
localField: "category", // field in the Todo collection
foreignField: "_id", // field in the projects collection
as: "fromItems"
}
},
{
$replaceRoot: { newRoot: { $mergeObjects: [{ $arrayElemAt: ["$fromItems", 0] }, "$$ROOT"] } }
},
{ $match: filterMatchAfter },
{ $project: myobjField }];
return query;
}
TodoSchema.statics.findAllByUserIdAndCat = function (userId) {
var Todo = this;
const query = getQueryTodo({}, userId);
return Todo.aggregate(query)
.then(ris => {
// console.log('ris TODO:', ris);
//return tools.mapSort(ris)
return ris
});
};
TodoSchema.statics.getArrIdParentInTable = function (userId) {
var Todo = this;
return Todo.find(getQueryFilterTodo(userId)).distinct("category")
.then(arrcategory => {
return arrcategory
})
};
function getobjFieldTodo(withprojectfield) {
let objfield = {};
for (const field of tools.allfieldTodo()) {
objfield[field] = 1;
}
if (withprojectfield) {
objfield["privacyread"] = 1;
objfield["privacywrite"] = 1;
}
// console.log("getobjFieldTodo", objfield);
return objfield
}
TodoSchema.statics.enabletoModify = async function (userId, idTodo) {
var Todo = this;
let params = {};
params['_id'] = ObjectId(idTodo);
const query = getQueryTodo(params, userId);
return Todo.aggregate(query)
.then(ris => {
return (!!ris);
})
.catch(err => {
console.log("ERR: ".err);
return false;
});
};
TodoSchema.statics.getAllTodo = async function (userId) {
var Todo = this;
const arralltodo = await Todo.findAllByUserIdAndCat(userId);
// console.log('arralltodo', arralltodo);
let obj = [];
obj.arrcategories = await Todo.getArrIdParentInTable(userId);
// console.log('obj.arrcategories', obj.arrcategories);
let arrtodos = [];
if (obj.arrcategories.length > 0) {
for (const mycat of obj.arrcategories) {
if (!!arralltodo) {
const arrfiltrato = arralltodo.filter(item => item.category.toString() === mycat.toString());
if (arrfiltrato.length > 0) {
const arrmap = tools.mapSort(arrfiltrato);
arrtodos.push(arrmap);
// console.log('AGGIUNGI RECORDS TODO! cat: ', mycat, 'da aggiungere:', arrfiltrato.length, 'attuali', arrtodos.length);
// console.log(arrtodos)
} else {
arrtodos.push([]);
}
}
}
}
obj.arrtodos = arrtodos;
// console.log('obj.arrtodos:');
// logtodo(obj.arrtodos);
return obj;
};
function getelem(item) {
return item.descr + ' ' + item.category;
}
function logtodo(myarr) {
console.log(getarrlog(myarr));
}
function getarrlog(myarr) {
let mystr = "";
for (const indcat in myarr) {
mystr += indcat + ': \n';
for (const indelem in myarr[indcat]) {
mystr += ' [' + indelem + '] ' + getelem(myarr[indcat][indelem]) + '\n';
}
}
return mystr
}
class CalcTodo {
constructor(phase) {
this.mydata = {
phase: phase,
numitem: 0
};
this.clean()
}
clean() {
this.mydata.hoursleft = 0;
this.mydata.hoursplanned = 0;
this.mydata.hoursworked = 0;
this.mydata.progressCalc = 0;
}
addDataProj(datain) {
if (!!datain) {
if (datain.actualphase === this.mydata.phase) {
CalcTodo.addFields(this.mydata, datain, true);
}
}
}
addDataTodo(datain) {
if (!!datain) {
if (datain.phase === this.mydata.phase) {
CalcTodo.addFields(this.mydata, datain, false);
}
}
}
static addFields(recout, recin, isproj) {
// console.log('addFields', recin);
recout.hoursworked += recin.hoursworked;
recout.hoursplanned += recin.hoursplanned;
let hoursleft = (recin.hoursplanned - recin.hoursworked);
if (hoursleft < 0)
hoursleft = 0;
recout.hoursleft += hoursleft;
if (recin.progress === undefined) {
recout.progressCalc += recin.progressCalc;
} else {
recout.progressCalc += recin.progress;
}
recout.numitem++;
}
static copyFields(recout, recin) {
recout.hoursworked = recin.hoursworked;
recout.hoursplanned = recin.hoursplanned;
recout.hoursleft = recin.hoursleft;
if (recin.progress === undefined)
recout.progressCalc = recin.progressCalc;
else {
if (!!recin.progressCalc)
recout.progressCalc = recin.progressCalc;
else
recout.progressCalc = 0;
}
}
setValuesToRecord(objout) {
CalcTodo.copyFields(objout, this.mydata)
}
endDataCalc() {
if (this.mydata.numitem > 0) {
this.mydata.progressCalc = Math.round(this.mydata.progressCalc / this.mydata.numitem);
}
console.log('this.mydata.progressCalc', this.mydata.progressCalc)
}
getData() {
// return tools.jsonCopy(this.mydata);
return { ...this.mydata }
}
}
TodoSchema.statics.calculateTreeTodo = async function (actualphase, userId, idproj, calcalsoUpper, masterproj, nocalcDown) {
// console.log('calculateTreeTodo', 'actualphase', actualphase, idproj);
const myrecproj = await Project.findProjectByUserId(userId, idproj);
// const id_parent = await Project.getIdParentByIdProj(idproj);
let objdata = new CalcTodo(actualphase);
let promiseChain = Promise.resolve();
return await Project.findByUserIdAndIdParent(userId, idproj)
.then(arrsubproj => {
// console.log(' ', arrsubproj.length, 'SubProjects trovati');
// console.log('arrsubproj', 'userId', userId, 'idproj', idproj, arrsubproj.length);
if (!nocalcDown) {
// 1) Calculate the SubProjects of this project Main
for (const subproj of arrsubproj) {
if (!calcalsoUpper) { // not include the first Project because it was already calculated before
promiseChain = promiseChain.then(() => {
return Todo.calculateTreeTodo(actualphase, userId, subproj._id, calcalsoUpper, masterproj, true)
.then((subobjdata) => {
objdata.addDataProj(subobjdata);
});
});
} else {
promiseChain = promiseChain.then(() => {
objdata.addDataProj(subproj);
});
}
}
}
return promiseChain;
})
.then(() => {
// console.log('objdata', objdata);
// 2) Calculate the Todos of this project
if (!!myrecproj)
return Todo.calculateTodoHoursAndProgress(userId, idproj, myrecproj.actualphase);
else
return null
})
.then((objdatatodos) => {
if (!!objdatatodos) {
if (!!myrecproj) {
if (myrecproj.actualphase === actualphase) {
// console.log('objdatatodos', objdatatodos);
objdata.addDataTodo(objdatatodos);
// End Calculate
objdata.endDataCalc();
// Update into the DB:
return Project.updateCalc(userId, idproj, objdata, null)
.then((ris) => {
if (ris)
return objdata.getData();
else
return null;
});
}
}
}
return null;
})
.then((ris) => {
if (calcalsoUpper) {
if (!!myrecproj) {
if (!!myrecproj.id_parent) {
// Calculate also the upper Projects !
return new Promise((resolve, reject) => {
Todo.calculateTreeTodo(actualphase, userId, myrecproj.id_parent, true, masterproj, false);
resolve(ris)
});
} else {
return new Promise((resolve, reject) => {
resolve()
});
}
}
}
return new Promise((resolve, reject) => {
resolve()
});
})
};
TodoSchema.statics.calculateTodoHoursAndProgress = async function (userId, idproj, actualphase) {
var Todo = this;
let objdata = new CalcTodo(actualphase);
return await Todo.findByUserIdAndIdParent(userId, idproj, actualphase)
.then(arrtodo => {
// console.log(' calculateTodo *', arrtodo.length, '* FOUND');
for (let itemtodo of arrtodo) {
objdata.addDataTodo(itemtodo);
}
objdata.endDataCalc();
return objdata.getData();
})
.catch(e => {
console.log('Error: ', e);
return null;
});
};
TodoSchema.pre('save', function (next) {
// var todo = this;
// console.log('todo.expiring_at', todo.expiring_at);
next();
});
var Todo = mongoose.model('Todos', TodoSchema);
module.exports = { Todo };

414
src/server/models/user.js Normal file
View File

@@ -0,0 +1,414 @@
var bcrypt = require('bcryptjs');
const mongoose = require('mongoose');
const validator = require('validator');
const jwt = require('jsonwebtoken');
const _ = require('lodash');
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const queryclass = require('../classes/queryclass');
mongoose.Promise = global.Promise;
mongoose.level = "F";
// Resolving error Unknown modifier: $pushAll
mongoose.plugin(schema => {
schema.options.usePushEach = true
});
mongoose.set('debug', process.env.DEBUG);
var UserSchema = new mongoose.Schema({
userId: {
type: String,
},
email: {
type: String,
required: true,
trim: true,
minlength: 1,
unique: false,
/*validate: {
validator: validator.isEmail,
message: '{VALUE} is not a valid email'
}*/
},
cell: {
type: String,
},
idapp: {
type: String,
required: true,
},
username: {
type: String,
required: true,
trim: true,
minlength: 6,
unique: false,
},
name: {
type: String,
trim: true,
},
surname: {
type: String,
trim: true,
},
password: {
type: String,
require: true,
minlength: 6,
},
lang: {
type: String,
require: true,
},
linkreg: {
type: String,
required: false
},
verified_email: {
type: Boolean,
},
tokens: [{
access: {
type: String,
required: true
},
browser: {
type: String,
required: true
},
token: {
type: String,
required: true
},
date_login: {
type: Date
},
}],
perm: {
type: Number
},
ipaddr: {
type: String,
},
date_reg: {
type: Date,
default: Date.now()
},
date_tokenforgot: {
type: Date
},
tokenforgot: {
type: String,
},
lasttimeonline: {
type: Date
},
news_on: {
type: Boolean
},
profile: {
img: {
type: String
},
cell: {
type: String
},
dateofbirth: {
type: Date,
},
sex: {
type: Number,
},
},
});
UserSchema.methods.toJSON = function () {
var user = this;
var userObject = user.toObject();
return _.pick(userObject, ['_id', ...shared_consts.fieldsUserToChange()]);
};
UserSchema.methods.generateAuthToken = function (req) {
// console.log("GENERA TOKEN : ");
var user = this;
const useragent = req.get('User-Agent');
tools.mylog("GENERATE USER-AGENT = ", useragent);
const access = 'auth';
const browser = useragent;
const token = jwt.sign({ _id: user._id.toHexString(), access }, process.env.SIGNCODE).toString();
const date_login = new Date();
// CANCELLA IL PRECEDENTE !
user.tokens = user.tokens.filter(function (tok) {
return (tok.access !== access) || ((tok.access === access) && (tok.browser !== browser));
});
user.tokens.push({ access, browser, token, date_login });
user.lasttimeonline = new Date();
return user.save()
.then(() => {
console.log("TOKEN CREATO IN LOGIN : " + token);
return token;
})
.catch(err => {
console.log("Error", err.message);
});
};
UserSchema.statics.setPermissionsById = function (id, perm) {
const user = this;
return user.findByIdAndUpdate(id, { $set: { perm } }).then((user) => {
if (user)
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
else
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
});
};
UserSchema.statics.isAdmin = function (user) {
try {
return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
} catch (e) {
return false
}
};
UserSchema.statics.isManager = function (user) {
try {
return ((user.perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager);
} catch (e) {
return false
}
};
UserSchema.statics.findByToken = function (token, typeaccess) {
const User = this;
let decoded;
try {
decoded = jwt.verify(token, process.env.SIGNCODE);
} catch (e) {
return Promise.resolve(null);
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
'tokens.access': typeaccess,
});
};
UserSchema.statics.findByTokenAnyAccess = function (token) {
var User = this;
var decoded;
try {
decoded = jwt.verify(token, process.env.SIGNCODE);
} catch (e) {
return Promise.resolve(null);
}
return User.findOne({
'_id': decoded._id,
'tokens.token': token,
});
};
UserSchema.statics.findByCredentials = function (idapp, username, password) {
var User = this;
var pwd = "";
return User.findOne({ idapp, username: username }).then((user) => {
if (!user) {
// Check if with email:
return User.findOne({ idapp, email: username })
} else {
return user
}
}).then(user => {
if (!user)
return null;
pwd = user.password;
return new Promise((resolve, reject) => {
// Use bcrypt.compare to compare password and user.password
// console.log("pwd1 " + password);
// console.log("pwd2 " + pwd);
bcrypt.compare(password, pwd, (err, res) => {
if (res) {
resolve(user);
} else {
return resolve(null);
}
});
});
});
};
UserSchema.statics.findByUsername = function (idapp, username) {
const User = this;
return User.findOne({
'idapp': idapp,
'username': username,
});
};
UserSchema.statics.findByLinkreg = function (idapp, linkreg) {
var User = this;
return User.findOne({
'linkreg': linkreg,
'idapp': idapp,
});
};
UserSchema.statics.findByLinkTokenforgot = function (idapp, email, tokenforgot) {
var User = this;
return User.findOne({
'email': email,
'tokenforgot': tokenforgot,
'date_tokenforgot': { $gte: tools.IncDateNow(-1000 * 60 * 60 * 4) }, // 4 ore fa!
'idapp': idapp,
});
};
UserSchema.statics.findByEmail = function (idapp, email) {
var User = this;
return User.findOne({
'idapp': idapp,
'email': email,
});
};
UserSchema.pre('save', function (next) {
var user = this;
/*
if (user.isModified('password')) {
bcrypt.genSalt(10, (err, salt) => {
bcrypt.hash(user.password, salt, (err, hash) => {
user.password = hash;
next();
});
});
} else {
next();
}
*/
next();
});
UserSchema.methods.removeToken = function (token) {
const user = this;
return user.update({
$pull: {
tokens: { token }
}
});
};
UserSchema.statics.getEmailByUsername = async function (idapp, username) {
const User = this;
return await User.findOne({ idapp, username })
.then((arrrec) => {
return ((arrrec) ? arrrec.email : '');
}).catch((e) => {
console.error('getEmailByUsername', e);
});
};
UserSchema.statics.getUsersList = function (idapp) {
const User = this;
return User.find({ 'idapp': idapp }, {
username: 1,
name: 1,
surname: 1,
verified_email: 1,
perm: 1,
email: 1,
date_reg: 1,
img: 1
})
};
UserSchema.statics.getUsersListByParams = function (params) {
const User = this;
myclParamQuery = new queryclass.CParamsQuery(params);
const filterMatchBefore = `${ myclParamQuery.filter }`;
return User.find(
{ $match: filterMatchBefore },
{ 'idapp': idapp },
{ username: 1, name: 1, surname: 1, verified_email: 1, perm: 1, email: 1, date_reg: 1, img: 1, lasttimeonline: 1, news_on: 1 })
};
/**
* Query blog posts by user -> paginated results and a total count.
* @returns {Object} Object -> `{ rows, count }`
*/
UserSchema.statics.getFieldsForSearch = function () {
return ['name', 'surname', 'email', 'cell']
};
UserSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
if (tools.INITDB_FIRSTIME) {
console.log(' createIndex User Index...');
// UserSchema.index({ username: 'text', name: 'text', surname: 'text', email: 'text' });
// UserSchema.index({ name: 'name' });
// UserSchema.index({ name: 1 });
// UserSchema.index({ surname: 1 });
}
const User = mongoose.model('User', UserSchema);
class Hero {
constructor(name, level) {
this.name = name;
this.level = level;
}
// Adding a method to the constructor
greet() {
return `${this.name} says hello.`;
}
}
module.exports = { User, Hero };

View File

@@ -0,0 +1,54 @@
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 WhereSchema = new Schema({
_id: {
type: mongoose.Schema.Types.ObjectId
},
idapp: {
type: String,
},
code: {
type: String,
},
placename: {
type: String,
},
whereicon: {
type: String,
},
});
WhereSchema.statics.getFieldsForSearch = function () {
return ['placename']
};
WhereSchema.statics.executeQueryTable = function (idapp, params) {
params.fieldsearch = this.getFieldsForSearch();
return tools.executeQueryTable(this, idapp, params);
};
WhereSchema.statics.findAllIdApp = function (idapp) {
const Where = this;
const myfind = { idapp };
return Where.find(myfind, (err, arrrec) => {
return arrrec
});
};
const Where = mongoose.model('Where', WhereSchema);
module.exports = { Where };

View File

@@ -0,0 +1,39 @@
const mysql = require('mysql');
const mySqlConn_Shen = mysql.createConnection({
host : '198.136.49.34',
user : 'assoc499_user',
password : 'mypassmysql@1A',
database : 'assoc499_1',
debug: true
});
module.exports = { mySqlConn_Shen };
// POOL:
// const pool = mysql.createPool({
// connectionLimit : 100, //important
// host : '198.136.49.34',
// user : 'assoc499_user',
// password : 'mypassmysql@1A',
// database : 'assoc499_1',
// debug : false
// });
//
//
// function pool_queryRow(tablename, fieldID, IdValue) {
// let selectQuery = 'SELECT * FROM ?? WHERE ?? = ?';
// let query = mysql.format(selectQuery,[tablename,fieldID, IdValue]);
// // query = SELECT * FROM `tablename` where `fieldID` = 'IdValue'
// pool.query(query,(err, data) => {
// if(err) {
// console.error(err);
// return;
// }
// // rows fetch
// console.log(data);
// });
// }

View File

@@ -0,0 +1,28 @@
const jwt = require('jsonwebtoken');
function toHexString(bytes) {
return Array.from(bytes, byte =>
("00" + (byte & 0xFF).toString(16)).slice(-2)
).join('');
}
module.exports = {
getlinkregByEmail: function (idapp, email, username) {
try{
mystr = idapp + email + username;
return jwt.sign(toHexString(mystr), process.env.SIGNCODE).toString();
} catch (e) {
console.error(e);
}
},
getiPAddressUser: function (req) {
try {
return req.ip; // Express
} catch (e) {
return ''
}
}
};

View File

@@ -0,0 +1,26 @@
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const cfgserver = mongoose.model('cfgserver');
const tools = require('../tools/general');
var { authenticate } = require('../middleware/authenticate');
router.post('/updateval', authenticate, (req, res) => {
console.log('/updateval', req.body.pairval);
pair = req.body.pairval;
cfgserver.findOneAndUpdate({chiave: pair.chiave, userID: pair.userId}, { $set: pair }, { new: false }).then((item) => {
// cfgserver.find({ chiave: pair.chiave }, (err, item) => {
res.status(200).send();
}).catch(err => {
console.log('ERR:', err);
res.status(400).send();
})
});
module.exports = router;

View File

@@ -0,0 +1,29 @@
var mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');
module.exports = {
doOtherThingsAfterDeleted: async function (tablename, rec) {
try {
if (tablename === 'users') {
// Delete also all the subscribers record of this User
return Subscription.remove({ userId: rec._id })
}
} catch (e) {
return false
}
return true;
},
doOtherThingsAfterDuplicated: async function (tablename, myrec, mynewrec) {
try {
if (tablename === 'users') {
// Delete also all the subscribers record of this User
}
return { myrec }
} catch (e) {
return false
}
return true;
}
};

View File

@@ -0,0 +1,136 @@
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 { Booking } = require('../models/booking');
const { ObjectID } = require('mongodb');
const sendemail = require('../sendemail');
const _ = require('lodash');
function sendNotif(res, idapp, user, recbooking) {
//++Todo: tools.sendNotificationToUser
// Send Email
if (recbooking.booked)
sendemail.sendEmail_Booking(res, user.lang, user.email, user, idapp, recbooking);
else
sendemail.sendEmail_CancelBooking(res, user.lang, user.email, user, idapp, recbooking);
}
router.post('/', authenticate, (req, res) => {
// tools.mylog('INIZIO - booking');
// tools.mylog('req.body', req.body);
const myrec = _.pick(req.body, tools.allfieldBooking());
const id = myrec._id;
const fieldtochange = _.pick(myrec, tools.allfieldBookingChange());
tools.mylog('crea Booking');
const booking = new Booking(myrec);
const check = tools.checkUserOk(booking.userId, req.user._id, res);
if (check.exit) return check.ret;
// console.log('fieldtochange', fieldtochange);
// Modify:
return Booking.findOne({ id_bookedevent: id })
.then(trovato => {
// console.log('trovato', trovato);
if (trovato) {
return Booking.findOneAndUpdate({ id_bookedevent: id }, { $set: fieldtochange }, {
new: true,
upsert: true
}).then((recbooking) => {
// tools.mylog('booking:', booking);
// tools.mylog('already exist');
sendNotif(res, myrec.idapp, req.user, recbooking);
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recbooking._id });
});
} else {
// save to database a new record
tools.mylog('save to database a new record');
booking._id = new ObjectID();
return booking.save().then((writeresult) => {
let idobj = writeresult._id;
Booking.findById(idobj)
.then((recbooking) => {
sendNotif(res, myrec.idapp, req.user, recbooking);
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recbooking._id });
});
});
}
})
});
router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
console.log('DELETE Booking');
const id = req.params.id;
const notify = req.params.notify;
const idapp = req.params.idapp;
Booking.findByIdAndRemove(id).then((recbooking) => {
if (!recbooking) {
return res.status(404).send();
}
if (notify === '1') {
recbooking.booked = false;
sendNotif(res, idapp, req.user, recbooking);
}
tools.mylog('DELETED ', recbooking._id);
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recbooking._id });
}).catch((e) => {
res.status(400).send();
});
});
// router.get('/:userId/:idapp/:sall', authenticate, (req, res) => {
// const userId = req.params.userId;
// const idapp = req.params.idapp;
// const sall = req.params.sall;
// // var category = req.params.category;
//
// // tools.mylog('GET BOOKINGS : ', req.params);
//
// if (!ObjectID.isValid(userId)) {
// return res.status(404).send();
// }
//
// if (userId !== String(req.user._id)) {
// // I'm trying to write something not mine!
// return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
// }
//
// // Extract all the todos of the userId only
// const bookedevent = Booking.findAllByUserIdAndIdApp(userId, idapp, sall);
// const eventlist = MyEvent.findAllIdApp(idapp);
// const operators = Operator.findAllIdApp(idapp);
// const wheres = Where.findAllIdApp(idapp);
// const contribtype = Contribtype.findAllIdApp(idapp);
//
// return Promise.all([bookedevent, eventlist, operators, wheres, contribtype])
// .then((arrdata) => {
// console.table(arrdata);
// res.send({ bookedevent: arrdata[0], eventlist: arrdata[1], operators: arrdata[2], wheres: arrdata[3], contribtype: arrdata[4] });
// })
// .catch((e) => {
// console.log(e);
// res.status(400).send(e);
// });
//
// });
//
module.exports = router;

View File

@@ -0,0 +1,20 @@
const express = require('express');
const router = express.Router();
var {User} = require('../models/user');
router.get('/:email/:idapp', (req, res) => {
var email = req.params.email;
const idapp = req.params.idapp;
User.findByEmail(idapp, email).then((user) => {
if (!user) {
return res.status(404).send();
}
res.status(200).send();
}).catch((e) => {
res.status(400).send();
});
});
module.exports = router;

View File

@@ -0,0 +1,434 @@
const express = require('express');
const router = express.Router();
const { authenticate, authenticate_noerror } = require('../middleware/authenticate');
const { ObjectID } = require('mongodb');
const mongoose = require('mongoose');
const cfgserver = mongoose.model('cfgserver');
const _ = require('lodash');
const { User } = require('../models/user');
const { Booking } = require('../models/booking');
const { Operator } = require('../models/operator');
const { Where } = require('../models/where');
const { MyEvent } = require('../models/myevent');
const { Contribtype } = require('../models/contribtype');
const { Discipline } = require('../models/discipline');
const { Newstosent } = require('../models/newstosent');
const { MailingList } = require('../models/mailinglist');
const { Settings } = require('../models/settings');
const { SendMsg } = require('../models/sendmsg');
const { Permission } = require('../models/permission');
const tools = require('../tools/general');
const server_constants = require('../tools/server_constants');
const actions = require('./api/actions');
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);
// Cerco l'idlink se è ancora da Verificare
User.findByLinkreg(idapp, idlink).then((user) => {
if (!user) {
//console.log("NON TROVATO!");
return res.status(404).send();
} else {
if (user.verified_email) {
res.send({
code: server_constants.RIS_CODE_EMAIL_ALREADY_VERIFIED,
msg: res.__("L'Email è già stata Verificata.")
});
} 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!') });
});
}
}
}).catch((e) => {
console.log(e);
res.status(400).send();
});
});
// Faccio richiesta di una Nuova Password
router.post(process.env.LINK_REQUEST_NEWPASSWORD, (req, res) => {
const body = _.pick(req.body, ['idapp', 'email']);
const idapp = body.idapp;
const email = body.email;
console.log("POST " + process.env.LINK_REQUEST_NEWPASSWORD + " idapp= " + idapp + " email = " + email);
User.findByEmail(idapp, email).then((user) => {
if (!user) {
return res.status(404).send();
} 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(() => {
sendemail.sendEmail_RequestNewPassword(res.locale, user.email, user.idapp, user.tokenforgot);
res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
});
}
}).catch((e) => {
console.log(e);
res.status(400).send();
res.send({ code: server_constants.RIS_CODE_ERR, msg: e });
});
});
// Invio la Nuova Password richiesta dal reset!
// Ritorna il token per poter effettuare le chiamate...
router.post(process.env.LINK_UPDATE_PASSWORD, (req, res) => {
var body = _.pick(req.body, ['idapp', 'email', 'tokenforgot', 'password']);
var idapp = body.idapp;
var email = body.email;
var tokenforgot = body.tokenforgot;
var password = body.password;
console.log("POST " + process.env.LINK_UPDATE_PASSWORD + " idapp= " + idapp + " email = " + email + " tokenforgot = " + tokenforgot);
User.findByLinkTokenforgot(idapp, email, tokenforgot).then((user) => {
if (!user) {
return res.status(404).send();
} else {
// aggiorna la nuova password
user.password = password;
user.lasttimeonline = new Date();
// Crea token
user.generateAuthToken(req).then(token => {
user.tokenforgot = ''; // Svuota il tokenforgot perché non ti servirà più...
// Salva lo User
user.save().then(() => {
res.header('x-auth', token).send({ user }); // Ritorna il token di ritorno
});
})
}
}).catch((e) => {
console.log(e);
res.status(400).send();
});
});
function getTableByTableName(tablename) {
mytable = '';
if (tablename === 'users')
mytable = User;
else if (tablename === 'bookings')
mytable = Booking;
else if (tablename === 'operators')
mytable = Operator;
else if (tablename === 'sendmsgs')
mytable = SendMsg;
else if (tablename === 'wheres')
mytable = Where;
else if (tablename === 'myevents')
mytable = MyEvent;
else if (tablename === 'contribtype')
mytable = Contribtype;
else if (tablename === 'disciplines')
mytable = Discipline;
else if (tablename === 'newstosent')
mytable = Newstosent;
else if (tablename === 'settings')
mytable = Settings;
else if (tablename === 'permissions')
mytable = Permission;
else if (tablename === 'mailinglist')
mytable = MailingList;
return mytable
}
router.post('/settable', authenticate, (req, res) => {
const params = req.body;
const mytable = getTableByTableName(params.table);
const mydata = req.body.data;
mydata.idapp = req.user.idapp;
if (params.table === 'permissions') {
if (mydata["_id"] === undefined) {
mydata._id = 1;
}
} else {
if (mydata["_id"] === undefined) {
mydata._id = new ObjectID()
}
}
mytablerec = new mytable(mydata);
console.log('mytablerec', mytablerec);
return mytablerec.save()
.then(rec => {
// tools.mylog('rec', rec);
return res.send(rec);
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
router.post('/gettable', authenticate, (req, res) => {
const params = req.body;
const mytable = getTableByTableName(params.table);
// console.log('mytable', mytable);
if (!mytable) {
return res.status(400).send(e);
}
return mytable.executeQueryTable(req.user.idapp, params).then(ris => {
return res.send(ris);
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
router.patch('/chval', authenticate, (req, res) => {
// const idapp = req.body.idapp;
const id = req.body.data.id;
const mydata = req.body.data;
const mytable = getTableByTableName(mydata.table);
const fieldsvalue = mydata.fieldsvalue;
tools.mylogshow('PATCH CHVAL: ', id, fieldsvalue);
if (!User.isAdmin(req.user) && !User.isManager(req.user)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
mytable.findByIdAndUpdate(id, { $set: fieldsvalue }).then((rec) => {
tools.mylogshow(' REC TO MODIFY: ', rec);
if (!rec) {
return res.status(404).send();
} else {
res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
}
}).catch((e) => {
tools.mylogserr('Error patch USER: ', e);
res.status(400).send();
})
});
router.delete('/delrec/:table/:id', authenticate, (req, res) => {
const id = req.params.id;
const tablename = req.params.table;
// const idapp = req.body.idapp;
console.log('id', id, 'table', tablename);
const mytable = getTableByTableName(tablename);
if (!User.isAdmin(req.user) && !User.isManager(req.user)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
return mytable.findByIdAndRemove(id).then((rec) => {
if (!rec) {
return res.status(404).send();
}
tools.mylog('DELETED ', rec._id);
// Do extra things after deleted
return actions.doOtherThingsAfterDeleted(tablename, rec).then((ris) => {
if (ris) {
tools.mylog('DELETED Others things ...');
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
}
});
}).catch((e) => {
console.log(e);
res.status(400).send();
});
});
router.post('/duprec/:table/:id', authenticate, (req, res) => {
const id = req.params.id;
const tablename = req.params.table;
// const idapp = req.body.idapp;
console.log('id', id, 'table', tablename);
const mytable = getTableByTableName(tablename);
if (!User.isAdmin(req.user) && !User.isManager(req.user)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
return mytable.findById(id).then((mydata) => {
const datadup = tools.CloneRecordToNew(mydata);
const mynewrec = new mytable(datadup);
return mynewrec.save()
.then((rec) => {
if (!rec) {
return res.status(404).send();
}
tools.mylog('DUPLICATED ', rec);
// Do extra things after deleted
return actions.doOtherThingsAfterDuplicated(tablename, rec).then(({ myrec }) => {
// ...
mytable.findById(myrec._id).then((record) => {
return res.send({ code: server_constants.RIS_CODE_OK, record, msg: '' });
});
});
}).catch((e) => {
console.error(e);
res.status(400).send();
});
})
});
function doOtherThingsAfterDeleted() {
}
router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) => {
const userId = req.params.userId;
const idapp = req.params.idapp;
const sall = req.params.sall;
// var category = req.params.category;
// tools.mylog('loadsite : ', req.params);
let bookedevent = [];
let msgs = [];
if (userId !== '0') {
// LOGGED WITH USERID
bookedevent = Booking.findAllByUserIdAndIdApp(userId, idapp, sall);
}
// Extract all the todos of the userId only
const eventlist = MyEvent.findAllIdApp(idapp);
const operators = Operator.findAllIdApp(idapp);
const wheres = Where.findAllIdApp(idapp);
const contribtype = Contribtype.findAllIdApp(idapp);
const disciplines = Discipline.findAllIdApp(idapp);
const settings = Settings.findAllIdApp(idapp);
const permissions = Permission.findAllIdApp();
let newstosent = Promise.resolve([]);
let mailinglist = Promise.resolve([]);
if (sall){
newstosent = Newstosent.findAllIdApp(idapp);
mailinglist = MailingList.findAllIdApp(idapp);
}
return Promise.all([bookedevent, eventlist, operators, wheres, contribtype, settings, permissions, disciplines, newstosent, mailinglist])
.then((arrdata) => {
// console.table(arrdata);
res.send({
bookedevent: arrdata[0],
eventlist: arrdata[1],
operators: arrdata[2],
wheres: arrdata[3],
contribtype: arrdata[4],
settings: arrdata[5],
permissions: arrdata[6],
disciplines: arrdata[7],
newstosent: arrdata[8],
mailinglist: arrdata[9],
});
})
.catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
router.get(process.env.LINK_CHECK_UPDATES, authenticate, (req, res) => {
const userId = req.user._id;
// console.log("POST " + process.env.LINK_CHECK_UPDATES + " userId=" + userId);
if (!ObjectID.isValid(userId)) {
return res.status(404).send();
}
cfgserver.find().then((arrcfgrec) => {
if (!arrcfgrec)
return res.status(404).send();
// ++Todo: Add to Log Stat ....
// const sall = '0';
// msgs = SendMsg.findAllByUserIdAndIdApp(userId, req.user.username, req.user.idapp);
last_msgs = SendMsg.findLastGroupByUserIdAndIdApp(userId, req.user.username, req.user.idapp);
let usersList = null;
if (req.user) {
// If User is Admin, then send user Lists
if (User.isAdmin(req.user)) {
// Send UsersList
usersList = User.getUsersList(req.user.idapp)
}
}
return Promise.all([usersList, last_msgs])
.then((arrdata) => {
// console.table(arrdata);
return res.send({
cfgServer: arrcfgrec,
usersList: arrdata[0],
last_msgs: arrdata[1],
});
});
}).catch((e) => {
console.log(e);
res.status(400).send({ code: server_constants.RIS_CODE_ERR, msg: e });
});
});
module.exports = router;

View File

@@ -0,0 +1,114 @@
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 { MyEvent } = require('../models/myevent');
const { ObjectID } = require('mongodb');
const sendemail = require('../sendemail');
const _ = require('lodash');
router.post('/', authenticate, (req, res) => {
tools.mylog('INIZIO - MyEvent');
// tools.mylog('req.body', req.body);
const myrec = _.pick(req.body, tools.allfieldMyEvent());
const id = myrec._id;
const fieldtochange = _.pick(myrec, tools.allfieldMyEventChange());
tools.mylog('crea MyEvent');
const myevent = new MyEvent(myrec);
const check = tools.checkUserOk(myevent.userId, req.user._id, res);
if (check.exit) return check.ret;
// Modify:
return MyEvent.findOne({ id })
.then(trovato => {
// console.log('trovato', trovato);
if (trovato) {
return myevent.findOneAndUpdate({ id }, { $set: fieldtochange }, {
new: true,
upsert: true
}).then((recmyevent) => {
// tools.mylog('myevent:', myevent);
// tools.mylog('already exist');
sendNotif(res, myrec.idapp, req.user, recmyevent);
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id });
});
} else {
// save to database a new record
tools.mylog('save to database a new record');
myevent._id = new ObjectID();
return myevent.save().then((writeresult) => {
let idobj = writeresult._id;
myevent.findById(idobj)
.then((recmyevent) => {
sendNotif(res, myrec.idapp, req.user, recmyevent);
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id });
});
});
}
})
});
router.delete('/:id/:notify/:idapp', authenticate, (req, res) => {
console.log('DELETE myevent');
const id = req.params.id;
const notify = req.params.notify;
const idapp = req.params.idapp;
myevent.findByIdAndRemove(id).then((recmyevent) => {
if (!recmyevent) {
return res.status(404).send();
}
if (notify === '1')
sendNotif(res, idapp, req.user, recmyevent);
tools.mylog('DELETED ', recmyevent.descr, recmyevent._id);
res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmyevent._id });
}).catch((e) => {
res.status(400).send();
});
});
router.get('/:userId/:idapp/:sall', authenticate, (req, res) => {
const userId = req.params.userId;
const idapp = req.params.idapp;
const sall = req.params.sall;
// var category = req.params.category;
// tools.mylog('GET myeventS : ', req.params);
if (!ObjectID.isValid(userId)) {
return res.status(404).send();
}
if (userId !== String(req.user._id)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
// Extract all the todos of the userId only
return MyEvent.findAllByUserIdAndIdApp(userId, idapp, sall).then((recevent) => {
res.send({ recevent });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
module.exports = router;

View File

@@ -0,0 +1,108 @@
const server_constants = require('../tools/server_constants');
const express = require('express');
const router = express.Router();
const request = require('superagent');
const sendemail = require('../sendemail');
const { User } = require('../models/user');
const tools = require('../tools/general');
const { authenticate } = require('../middleware/authenticate');
const newsletter = [
{
name: 'Paolo',
mailchimpInstance: 'us16',
listUniqueId: 'e70fd8ba4c',
mailchimpApiKey: '24d1eb0e4f21dd7c52d47214b0d62cfd-us16'
// CLIENT ID 682712991042
// Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
},
{
name: 'Paolo',
mailchimpInstance: 'us16',
listUniqueId: 'e70fd8ba4c',
mailchimpApiKey: '24d1eb0e4f21dd7c52d47214b0d62cfd-us16'
// CLIENT ID 682712991042
// Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
},
{
name: 'AssShen',
mailchimpInstance: 'us4',
listUniqueId: '991c0b8321',
mailchimpApiKey: '07dd8b0bd078ae3a79e398656c276bbd-us4'
// CLIENT ID 682712991042
// Client Secret 69c627f5dad15f6072ac4f86f5312a6078c94f72a0902d2f4c
},
{
name: 'AssociazioneShen',
mailchimpInstance: '',
listUniqueId: '',
mailchimpApiKey: ''
}
];
router.post('/', (req, res) => {
idwebsite = req.body.idwebsite;
idapp = req.body.idapp;
locale = req.body.locale;
const user = {
email: req.body.email,
name: req.body.firstName,
surname: req.body.lastName,
};
sendemail.sendEmail_Notif_Added_to_Newsletter(locale, user, idapp);
request
.post('https://' + newsletter[idwebsite].mailchimpInstance + '.api.mailchimp.com/3.0/lists/' + newsletter[idwebsite].listUniqueId + '/members/')
.set('Content-Type', 'application/json;charset=utf-8')
.set('Authorization', 'Basic ' + new Buffer('any:' + newsletter[idwebsite].mailchimpApiKey).toString('base64'))
.send({
'email_address': req.body.email,
'status': server_constants.RIS_SUBSCRIBED_STR,
'merge_fields': {
'FNAME': req.body.firstName,
'LNAME': req.body.lastName
}
})
.end(function (err, response) {
console.log("STAT", response.status);
if (response.status < 300 || (response.status === 400 && response.body.title === "Member Exists")) {
if (response.status === 400 && response.body.title === "Member Exists")
res.send({result: server_constants.RIS_SUBSCRIBED_ALREADYEXIST, msg: server_constants.RIS_SUBSCRIBED_MSG_ALREADYEXIST[locale]});
else
res.send({result: server_constants.RIS_SUBSCRIBED_OK, msg: server_constants.RIS_SUBSCRIBED_MSG[locale]});
} else {
res.send({result: server_constants.RIS_SUBSCRIBED_ERR, msg: server_constants.RIS_SUBSCRIBED_MSG_FAILED[locale]});
}
});
});
router.post('/testemail', authenticate, async (req, res) => {
if (!User.isAdmin(req.user)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
idapp = req.body.idapp;
lang = req.body.locale;
const ris = await sendemail.testemail(idapp, lang);
if (ris)
return res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
else
return res.send({ code: server_constants.RIS_CODE_EMAIL_NOT_SENT, msg: '' });
});
module.exports = router;

View File

@@ -0,0 +1,223 @@
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');
// var mongoose = require('mongoose');
const { Project } = require('../models/project');
const { Todo } = require('../models/todo');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
router.post('/', authenticate, (req, res) => {
var body = _.pick(req.body, tools.allfieldProjectWithId());
tools.mylogshow('PROJ INPUT', body);
var project = new Project(body);
// project.expiring_at = new Date(project.expiring_at);
tools.mylog('ID :', project._id, project.descr, project.userId, req.user._id);
if (!('descr' in req.body)) {
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
}
const check = tools.checkUserOk(project.userId, req.user._id, res);
if (check.exit) return check.ret;
tools.mylog('PROJECT POST :', project.descr, project._id);
project.modified = false;
if (!project.descr) {
console.log('RECORD NON VALIDO !?', req.body)
}
project.save().then((writeresult) => {
let idobj = writeresult._id;
Project.findById(idobj)
.then(record => {
tools.mylog('REC SAVED :', record.descr);
tools.sendNotificationToUser(project.userId, 'Project: ' + record.descr, record.descr, '/project/' + project.category, 'project')
.then(ris => {
if (ris) {
res.send({ record });
} else {
// already sent the error on calling sendNotificationToUser
}
})
})
}).catch((e) => {
console.log('ERRORE in PROJECT POST', e.message);
res.status(400).send(e);
});
});
router.patch('/:id', authenticate, (req, res) => {
var id = req.params.id;
// ------------- EXAMPLES: -----------------------
// var mionome = req.query.name; // Esempio miosito.com?name=pippo
// const plainText = req. body.plainText; //
// ----------------------------------------------------
var body = _.pick(req.body, tools.allfieldProject());
tools.mylogshow('PATCH PROJECT: ', id);
if (!ObjectID.isValid(id)) {
tools.mylog('ERROR: id not VALID', id);
return res.status(404).send();
}
// check if you are able to modify this project
if (!Project.enabletoModify(String(req.user._id), id))
return res.status(404).send();
Project.findByIdAndUpdate(id, { $set: body }, { new: true }).then((project) => {
tools.mylogshow(' PROJECT TO MODIFY: ', project.descr);
if (!project) {
return res.status(404).send();
}
if (project.userId !== String(req.user._id)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
project.modified = false;
// Recalculate
return calcSingleProject('', project)
.then(objout => {
tools.mylog('PATCH ', project.descr, project._id, project.progressCalc);
return Project.findById(id).then((projectris) => {
// console.log('projectris progressCalc', projectris.progressCalc);
res.send({ projectris });
});
});
}).catch((e) => {
tools.mylogserr('Error patch PROJECT: ', e);
res.status(400).send();
})
});
router.get('/', (req, res) => {
tools.mylog('GET ALL PROJECTS: ');
return Project.getAllProjects('').then((objprojects) => {
if (!!objprojects.arrproj)
tools.mylog('projects', objprojects.arrproj.length);
return objprojects
}).then((objprojects) => {
res.send({ projects: objprojects.arrproj });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
router.get('/:userId', authenticate, (req, res) => {
const userId = req.params.userId;
tools.mylog('GET PROJECTS : ', req.params);
if (!ObjectID.isValid(userId)) {
return res.status(404).send();
}
if (userId !== String(req.user._id)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
// Extract all the projects of the userId only
return Project.getAllProjects(userId).then((objprojects) => {
if (!!objprojects.arrproj)
tools.mylog('projects', objprojects.arrproj.length);
return objprojects
}).then((objprojects) => {
res.send({ projects: objprojects.arrproj });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
// USATO SOLO LE PRIME VOLTE! O A RICHIESTA!
async function calcProjects(userId, obj) {
// let myarr = tools.jsonCopy(obj.arrproj);
let myarr = [...obj.arrproj];
if (myarr.length > 0) {
let promiseChain = Promise.resolve();
for (const rec of myarr) {
promiseChain = promiseChain.then(() => {
// Find the todos for this project
// Calculate the Progression of the Project // sum the progression
return Todo.calculateTreeTodo(userId, rec._id)
})
}
return promiseChain
} else {
return new Promise((resolve, reject) => {
resolve()
})
}
}
// USATO SOLO LE PRIME VOLTE! O A RICHIESTA!
async function calcSingleProject(userId, myproj) {
return await Todo.calculateTreeTodo(myproj.actualphase, userId, myproj._id, false, myproj._id, false)
}
router.delete('/:id', authenticate, (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Project.findByIdAndRemove(id).then((project) => {
if (!project) {
return res.status(404).send();
}
tools.mylog('DELETED ', project.descr, project._id);
res.send({ project });
}).catch((e) => {
res.status(400).send();
});
});
module.exports = router;

View File

@@ -0,0 +1,82 @@
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');
// const q = require('q');
const webpush = require('web-push');
router.post('/', (req, res) => {
const payload = {
title: req.body.title,
message: req.body.message,
url: req.body.url,
ttl: req.body.ttl,
icon: req.body.icon,
image: req.body.image,
badge: req.body.badge,
tag: req.body.tag
};
Subscription.find({}, (err, subscriptions) => {
if (err) {
console.error(`Error occurred while getting subscriptions`);
res.status(500).json({
error: 'Technical error occurred'
});
} else {
let parallelSubscriptionCalls = subscriptions.map((subscription) => {
return new Promise((resolve, reject) => {
const pushSubscription = {
endpoint: subscription.endpoint,
keys: {
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth
}
};
const pushPayload = JSON.stringify(payload);
const pushOptions = {
vapidDetails: {
subject: process.env.URLBASE_APP1,
privateKey: process.env.PRIVATE_VAPI_KEY,
publicKey: process.env.PUBLIC_VAPI_KEY,
},
TTL: payload.ttl,
headers: {}
};
webpush.sendNotification(
pushSubscription,
pushPayload,
pushOptions
).then((value) => {
resolve({
status: true,
endpoint: subscription.endpoint,
data: value
});
}).catch((err) => {
reject({
status: false,
endpoint: subscription.endpoint,
data: err
});
});
});
});
q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
console.info(pushResults);
});
res.json({
data: 'Push triggered'
});
}
});
});
router.get('/', (req, res) => {
res.json({
data: 'Invalid Request Bad'
});
});
module.exports = router;

View File

@@ -0,0 +1,116 @@
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 { User } = require('../models/user');
const { Operator } = require('../models/operator');
const { SendMsg } = require('../models/sendmsg');
const { ObjectID } = require('mongodb');
const sendemail = require('../sendemail');
const shared_consts = require('../tools/shared_nodejs');
const _ = require('lodash');
function checkifSendPushNotification() {
return process.env.ENABLE_PUSHNOTIFICATION === "1";
//return false;
}
async function sendNotif(res, idapp, user, recmsg) {
if (tools.isBitActive(recmsg.options, shared_consts.MessageOptions.Notify_ByPushNotification)) {
if (this.checkifSendPushNotification) {
console.log('SEND PUSH NOTIFICATION ')
//++Todo: tools.sendNotificationToUser
}
}
// Read from the operator table first
let emaildest = await Operator.getEmailByUsername(recmsg.dest.idapp, recmsg.dest.username);
if (emaildest === '')
emaildest = await User.getEmailByUsername(recmsg.dest.idapp, recmsg.dest.username);
console.log('emaildest', emaildest);
// Send Msg by EMAIL
if (emaildest && tools.isBitActive(recmsg.options, shared_consts.MessageOptions.Notify_ByEmail))
await sendemail.sendEmail_Msg(res, user.lang, emaildest, user, idapp, recmsg);
return true
}
router.post('/', authenticate, (req, res) => {
tools.mylog('INIZIO - SendMsg');
// tools.mylog('req.body', req.body);
const body = _.pick(req.body, tools.allfieldSendMsg());
tools.mylog('crea SendMsg');
const myrecmsg = new SendMsg(body);
const check = tools.checkUserOk(myrecmsg.origin.username, req.user.username, res);
if (check.exit) return check.ret;
// console.log('fieldtochange', fieldtochange);
myrecmsg._id = new ObjectID();
return myrecmsg.save()
.then((writeresult) => {
let idobj = writeresult._id;
myrecmsg._id = idobj;
return SendMsg.findById(idobj)
.then((recmsg) => {
// Add this field because I don't want to add into the database
recmsg.source.infoevent = body.source.infoevent;
return sendNotif(res, body.idapp, req.user, recmsg).then((ris) => {
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmsg._id });
})
});
}).catch((e) => {
console.log(e);
// res.status(400).send(e);
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
})
});
router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
tools.mylog('GET SendMsgS : ', req.params);
const username = req.params.username;
const lastdataread = req.params.lastdataread;
const idapp = req.params.idapp;
// var category = req.params.category;
if (req.user.idapp !== idapp) {
// I'm trying to get something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_NOT_MY_USERNAME });
}
// Extract all the todos of the userId only
return SendMsg.findAllMsgByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrmsg) => {
// const wait = new Promise((resolve, reject) => {
// setTimeout(() => {
res.send({ arrmsg });
// }, 2000);
// });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
module.exports = router;

View File

@@ -0,0 +1,101 @@
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');
const tools = require('../tools/general');
var { authenticate } = require('../middleware/authenticate');
const isValidSaveRequest = (req, res) => {
try {
if (!req.body || !req.body.subs.endpoint) {
res.status(400);
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({
error: {
id: 'no-endpoint',
message: 'Subscription must have an endpoint'
}
}));
return false
}
return true
} catch (e) {
return false
}
};
router.post('/', authenticate, (req, res) => {
// console.log('req.body.others', req.body.others);
if (!isValidSaveRequest(req, res)) {
return;
}
let subscriptionModel = new Subscription(req.body.subs);
subscriptionModel.userId = req.body.others.userId;
subscriptionModel.access = req.body.others.access;
subscriptionModel.browser = req.get('User-Agent');
// Find if already exist
Subscription.findOne( {userId: subscriptionModel.userId, access: subscriptionModel.access, browser: subscriptionModel.browser})
.then(itemsub => {
return itemsub
})
.catch(err => {
// Not found
return null
})
.then(myitem => {
if (myitem === null) {
myitem = subscriptionModel;
tools.mylogshow('Subscription NOT EXISTED IN DB, so I use this created!', myitem)
}
// else
// tools.mylogshow('Subscription already Existed!');
myitem.save((err, subscription) => {
if (err) {
console.error(`Error occurred while saving subscription. Err: ${err}`);
res.status(500).json({
error: 'Technical error occurred'
});
} else {
// Send 201 - resource created
// res.status(201).json({ data: 'Subscription saved.' });
res.send({ data: 'Subscription saved.' });
if (req.body.options !== null) {
tools.sendBackNotif(subscription, req.body.options)
}
}
});
});
});
router.delete('/del', authenticate, (req, res) => {
// tools.mylog("TOKENREM = " + req.token);
const browser = req.get('User-Agent');
Subscription.findOneAndRemove( { userId: req.user._id, access: req.access, browser } ).then(() => {
res.status(200).send();
}, () => {
res.status(400).send();
});
});
router.get('/', (req, res) => {
res.json({
data: 'Invalid Request Bad'
});
});
module.exports = router;

View File

@@ -0,0 +1,185 @@
const express = require('express');
const router = express.Router();
const tools = require('../tools/general');
var server_constants = require('../tools/server_constants');
var { Project } = require('../models/project');
var { authenticate } = require('../middleware/authenticate');
var mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');
var { Todo } = require('../models/todo');
const _ = require('lodash');
const { ObjectID } = require('mongodb');
router.post('/', authenticate, (req, res) => {
var body = _.pick(req.body, tools.allfieldTodoWithId());
tools.mylogshow('INPUT', body);
var todo = new Todo(body);
// todo.expiring_at = new Date(todo.expiring_at);
tools.mylog('ID :', todo._id, todo.descr, todo.userId, req.user._id);
if (!('descr' in req.body)) {
return res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
}
if (String(todo.userId) !== String(req.user._id)) {
// I'm trying to write something not mine!
tools.mylog('todo.userId = ', todo.userId, 'req.user._id', req.user._id)
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
tools.mylog('TODO POST :', todo.descr, todo._id);
todo.modified = false;
if (!todo.descr) {
console.log('RECORD NON VALIDO !?', req.body)
}
todo.save().then((writeresult) => {
let idobj = writeresult._id;
Todo.findById(idobj)
.then(record => {
tools.mylog('REC SAVED :', record.descr);
tools.sendNotificationToUser(todo.userId, 'Todo: ' + record.descr, record.descr, '/todo/' + todo.category, 'todo')
.then(ris => {
if (ris) {
res.send({ record });
} else {
// already sent the error on calling sendNotificationToUser
}
})
})
}).catch((e) => {
console.log('ERRORE in TODO POST', e.message);
res.status(400).send(e);
});
});
router.patch('/:id', authenticate, (req, res) => {
var id = req.params.id;
var body = _.pick(req.body, tools.allfieldTodo());
tools.mylogshow('PATCH TODO: ', id);
if (!ObjectID.isValid(id)) {
tools.mylog('ERROR: id not VALID', id);
return res.status(404).send();
}
Todo.findByIdAndUpdate(id, { $set: body }, { new: true })
.then((todo) => {
if (!todo) {
tools.mylogshow(' TODO NOT FOUND !: id:', id, 'body: ', body);
return res.status(404).send();
}
let level = 0;
return Todo.calculateTreeTodo(todo.phase, todo.userId, todo.category, true, todo.category, false)
.then(objdatacalc => {
tools.mylogshow(' TODO TO MODIFY: ', todo.descr, todo.expiring_at);
if (todo.userId !== String(req.user._id)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
todo.modified = false;
tools.mylog('PATCH ', todo.descr, todo._id);
res.send({ todo, objdatacalc });
});
}).catch((e) => {
tools.mylogserr('Error patch TODO: ', e);
res.status(400).send();
})
});
router.get('/:userId', authenticate, (req, res) => {
var userId = req.params.userId;
// var category = req.params.category;
tools.mylog('GET TODOS : ', req.params);
if (!ObjectID.isValid(userId)) {
return res.status(404).send();
}
if (userId !== String(req.user._id)) {
// I'm trying to write something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER });
}
// Extract all the todos of the userId only
Todo.getAllTodo(userId).then((objtodos) => {
if (!!objtodos.arrtodos) {
tools.mylog('todos', objtodos.arrtodos.length);
tools.mylog('categories', objtodos.arrcategories.length);
}
res.send({ todos: objtodos.arrtodos, categories: objtodos.arrcategories });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
router.get('/', (req, res) => {
// var category = req.params.category;
tools.mylog('GET ALL TODOS ');
// Extract all the todos of the userId only
Todo.getAllTodo('').then((objtodos) => {
if (!!objtodos.arrtodos) {
tools.mylog('todos', objtodos.arrtodos.length);
tools.mylog('categories', objtodos.arrcategories.length);
}
res.send({ todos: objtodos.arrtodos, categories: objtodos.arrcategories });
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
router.delete('/:id', authenticate, (req, res) => {
var id = req.params.id;
if (!ObjectID.isValid(id)) {
return res.status(404).send();
}
Todo.findByIdAndRemove(id).then((todo) => {
if (!todo) {
return res.status(404).send();
}
tools.mylog('DELETED ', todo.descr, todo._id);
res.send({ todo });
}).catch((e) => {
res.status(400).send();
});
});
module.exports = router;

View File

@@ -0,0 +1,216 @@
const express = require('express');
const router = express.Router();
var { User } = require('../models/user');
var sendemail = require('../sendemail');
const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
var server_constants = require('../tools/server_constants');
const _ = require('lodash');
var reg = require('../reg/registration');
var { authenticate } = require('../middleware/authenticate');
var mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');
function existSubScribe(userId, access, browser) {
return Subscription.findOne({ userId, access, browser })
.then(itemsub => {
return itemsub
})
.catch(err => {
return null
})
}
// POST /users
router.post('/', (req, res) => {
tools.mylog("POST /users");
const body = _.pick(req.body, ['email', 'password', 'username', 'name', 'surname', 'idapp', 'keyappid', 'lang']);
const user = new User(body);
// tools.mylog("LANG PASSATO = " + user.lang, "IDAPP", user.idapp);
user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username);
user.verified_email = false;
user.ipaddr = reg.getiPAddressUser(req);
user.lasttimeonline = new Date();
if (tools.testing()) {
user.verified_email = true;
}
user.save().then(() => {
User.findByUsername(user.idapp, user.username)
.then((usertrovato) => {
tools.mylog("TROVATO USERNAME ? ", user.username, usertrovato);
if (usertrovato !== null) {
return user.generateAuthToken(req);
} else {
res.status(11100).send();
return 0;
}
}).then((token) => {
// tools.mylog("passo il TOKEN: ", token);
res.header('x-auth', token).send(user);
// 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);
if (!tools.testing()) {
sendemail.sendEmail_Registration(user.lang, user.email, user, user.idapp, user.linkreg);
}
});
}).catch((e) => {
res.status(400).send(e);
})
});
router.get('/:username/:idapp', (req, res) => {
var username = req.params.username;
const idapp = req.params.idapp;
User.findByUsername(idapp, username).then((user) => {
if (!user) {
return res.status(404).send();
}
res.status(200).send();
}).catch((e) => {
res.status(400).send();
});
});
router.patch('/:id', authenticate, (req, res) => {
const id = req.params.id;
const body = _.pick(req.body.user, shared_consts.fieldsUserToChange());
tools.mylogshow('PATCH USER: ', id);
if (!User.isAdmin(req.user)) {
// If without permissions, exit
return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
}
User.findByIdAndUpdate(id, { $set: body }).then((user) => {
tools.mylogshow(' USER TO MODIFY: ', user);
if (!user) {
return res.status(404).send();
} else {
res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
}
}).catch((e) => {
tools.mylogserr('Error patch USER: ', e);
res.status(400).send();
})
});
router.post('/login', (req, res) => {
var body = _.pick(req.body, ['username', 'password', 'idapp', 'keyappid', 'lang']);
var user = new User(body);
// const subs = _.pick(req.body, ['subs']);
tools.mylog("LOGIN: username: " + user.username + " pwd = " + user.password);
tools.mylog("user REC:", user);
if (body.keyappid !== process.env.KEY_APP_ID)
return res.status(400).send();
let resalreadysent = false;
User.findByCredentials(user.idapp, user.username, user.password)
.then((user) => {
tools.mylog("CREDENZIALI ! ");
if (!user) {
tools.mylogshow("NOT FOUND !");
res.status(404).send({ code: server_constants.RIS_CODE_LOGIN_ERR });
}
return user
})
.then(user => {
if (user) {
return user.generateAuthToken(req).then((token) => {
var usertosend = User();
shared_consts.fieldsUserToChange().forEach((field) => {
usertosend[field] = user[field]
});
// usertosend._id = user._id.toHexString();
// if (!User.isAdmin(req.user)) {
// usertosend.ipaddr = user.ipaddr;
// }
// tools.mylog("user.verified_email:" + user.verified_email);
tools.mylog("usertosend.userId", usertosend.userId);
return { usertosend, token }
})
.then((myris) => {
const access = 'auth';
const browser = req.get('User-Agent');
// Check if already exist Subscribe
return existSubScribe(myris.usertosend._id, access, browser).then(subscribe => {
return (subscribe !== null)
}).then(subsExistonDb => {
return { usertosend: myris.usertosend, token: myris.token, subsExistonDb }
}).catch(err => {
return { usertosend: myris.usertosend, token: myris.token, subsExistonDb: false }
})
}).then(myris => {
console.log('res', myris.token, myris.usertosend);
// SEND TOKEN AND CODE RESULT
res.header('x-auth', myris.token).send({
usertosend: myris.usertosend,
code: server_constants.RIS_CODE_OK,
subsExistonDb: myris.subsExistonDb
});
// tools.mylog("TROVATOOO!");
tools.mylog('FINE LOGIN')
});
}
})
.catch((e) => {
tools.mylog("ERRORE IN LOGIN: " + e);
if (!resalreadysent)
res.status(400).send({ code: server_constants.RIS_CODE_LOGIN_ERR_GENERIC });
});
});
router.delete('/me/token', authenticate, (req, res) => {
tools.mylog("TOKENREM = " + req.token);
req.user.removeToken(req.token).then(() => {
res.status(200).send();
}, () => {
res.status(400).send();
});
});
router.post('/setperm', authenticate, (req, res) => {
const body = _.pick(req.body, ['idapp', 'username', 'perm']);
tools.mylog("SETPERM = " + req.token);
User.setPermissionsById(res.user._id, body).then(() => {
res.status(200).send();
}, () => {
res.status(400).send();
});
});
module.exports = router;

415
src/server/sendemail.js Normal file
View File

@@ -0,0 +1,415 @@
const tools = require('./tools/general');
require('./config/config');
const Email = require('email-templates');
var i18n = require("i18n");
const { ObjectID } = require('mongodb');
const { Settings } = require('./models/settings');
const previewEmail = require('preview-email');
const nodemailer = require("nodemailer");
const { MyEvent } = require('./models/myevent');
const { MailingList } = require('./models/mailinglist');
const { Newstosent } = require('./models/newstosent');
const transport_preview = nodemailer.createTransport({
jsonTransport: true
});
// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport({
service: 'Gmail',
auth: {
user: process.env.EMAIL_FROM,
pass: process.env.EMAIL_PW
}
});
function checkifSendEmail() {
return process.env.SEND_EMAIL === "1";
//return false;
}
module.exports = {
sendEmail_base: function (template, to, mylocalsconf, replyTo) {
console.log('mylocalsconf', mylocalsconf);
// console.log("check EMAIL :" + checkifSendEmail());
const email = new Email({
message: {
from: process.env.EMAIL_FROM, // sender address
headers: {
'Reply-To': replyTo
}
},
send: checkifSendEmail(),
preview: !checkifSendEmail(),
transport: {
service: 'Gmail',
auth: {
user: process.env.EMAIL_FROM,
pass: process.env.EMAIL_PW
}
},
// htmlToText: false
});
return email
.send({
template: template,
message: {
to: to,
},
locals: mylocalsconf,
})
.then((ris) => {
return !!ris
})
.catch((err) => {
console.error(err);
return false
});
},
sendEmail_Normale: function (to, subject, html, replyTo) {
// setup e-mail data with unicode symbols
var mailOptions = {
from: process.env.EMAIL_FROM, // sender address
to: to,
generateTextFromHTML: true,
subject: subject,
html: html,
};
if (replyTo)
mailOptions['reply-to'] = replyTo;
if (process.env.SEND_EMAIL === 1) {
console.log("SEND EMAIL smtpTransport");
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function (error, response) {
if (error) {
console.log(error);
} else {
console.log("Message sent: " + response);
}
});
} else {
if (process.env.PROVA_EMAIL_TEMPLATE !== "1")
previewEmail(mailOptions).then(console.log).catch(console.error);
else
transport_preview.sendMail(mailOptions).then(console.log).catch(console.error);
}
},
// getHostByIdApp: function (idapp) {
// if (idapp === 1) {
// let siteport = (process.env.PORT_APP1 !== "0") ? (':' + process.env.PORT_APP1) : "";
// return process.env.URLBASE_APP1 + siteport;
// } else {
// return ""
// }
// },
getlinkReg: function (idapp, idreg) {
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}`;
return strlinkreg;
},
sendEmail_Registration: function (lang, emailto, user, idapp, idreg) {
console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
mylocalsconf = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
strlinkreg: this.getlinkReg(idapp, idreg),
username: user.username,
name: user.name,
surname: user.surname,
forgetpwd: "",
emailto: emailto,
};
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, '');
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/registration/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
},
sendEmail_RequestNewPassword: function (lang, emailto, idapp, tokenforgot) {
mylocalsconf = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
user: user,
strlinksetpassword: this.getlinkRequestNewPassword(idapp, user, tokenforgot),
emailto: emailto,
};
this.sendEmail_base('resetpwd/' + lang, emailto, mylocalsconf, '');
},
sendEmail_Booking: function (res, lang, emailto, user, idapp, recbooking) {
tools.mylog('sendEmail_Booking');
tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp);
mylocalsconf = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
name: user.name,
surname: user.surname,
emailto: emailto,
participants: '',
msgbooking: tools.convertTexttoHtml(recbooking.msgbooking),
eventtextplain: tools.removeSpecialCharForEmail(recbooking.infoevent),
event: recbooking.infoevent,
};
return Settings.getValDbSettings(idapp, 'MSG_REPLY_AFTER_BOOKING').then((ris => {
mylocalsconf.msgreply_after_booking = ris;
if (recbooking.numpeople > 1)
mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + res.__("partecipanti");
let texthtml = '';
if (recbooking.modified) {
texthtml = 'modifybooking';
} else {
texthtml = 'makebooking';
}
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, '');
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/' + texthtml + '/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
}));
},
sendEmail_CancelBooking: function (res, lang, emailto, user, idapp, recbooking) {
tools.mylog('sendEmail_CancelBooking');
mylocalsconf = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
name: user.name,
surname: user.surname,
emailto: emailto,
event: recbooking.infoevent,
participants: '',
eventtextplain: tools.removeSpecialCharForEmail(recbooking.infoevent),
};
if (recbooking.numpeople > 1)
mylocalsconf.participants = recbooking.numpeople.toString() + ' ' + res.__("partecipanti");
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, '');
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/cancelbooking/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
},
sendEmail_Msg: function (res, lang, emailto, user, idapp, recmsg) {
tools.mylog('sendEmail_Msg');
tools.mylog('tools.getNomeAppByIdApp(idapp)', tools.getNomeAppByIdApp(idapp), idapp);
mylocalsconf = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
name: user.name,
surname: user.surname,
usernameorig: user.name + ' ' + user.surname,
emailto: emailto,
message: tools.convertTexttoHtml(recmsg.message),
infoevent: recmsg.source.infoevent,
strlinkreply: tools.getHostByIdApp(idapp) + '/messages/' + recmsg._id
};
let replyto = '';
if (mylocalsconf.infoevent !== '')
replyto = user.email;
else
replyto = tools.getreplyToEmailByIdApp(idapp);
return this.sendEmail_base('msg/sendmsg/' + lang, emailto, mylocalsconf, replyto);
// Send Email also to the Admin
// this.sendEmail_base('admin/sendmsg/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf);
},
sendEmail_Notif_Added_to_Newsletter: function (lang, user, idapp) {
console.log('idapp', idapp, tools.getNomeAppByIdApp(idapp));
mylocalsconf = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
name: user.name,
surname: user.surname,
emailto: user.email,
};
// Add to the database
myperson = new MailingList({ name: mylocalsconf.name, surname: mylocalsconf.surname, email: mylocalsconf.emailto });
myperson._id = new ObjectID();
myperson.idapp = idapp;
// Add new record to the DB MailingList
return myperson.save().then((res) => {
// Send to the Admin an Email
this.sendEmail_base('admin/added_to_newsletter/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
if (tools.isManagAndAdminDifferent(idapp)) {
this.sendEmail_base('admin/added_to_newsletter/' + lang, tools.getManagerEmailByIdApp(idapp), mylocalsconf, '');
}
});
},
sendEmail_Newsletter_Events: async function (lang, idapp, id_newstosent) {
console.log('INIZIO - sendEmail_Newsletter_Events', tools.getNomeAppByIdApp(idapp));
//++Todo Extract List Email to send
const userstosend = await MailingList.findAllIdApp(idapp);
const myarrevents = await MyEvent.getLastEvents(idapp);
mylocalsconf = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
arrevents: myarrevents
};
const mynewsrec = await Newstosent.findOne({ _id: id_newstosent });
mynewsrec.numemail_tot = userstosend.length;
for (const user of userstosend) {
mylocalsconf.name = user.name;
mylocalsconf.surname = user.surname;
mylocalsconf.emailto = user.email;
// If has already sent, don't send it again!
if (user.lastid_newstosent !== id_newstosent.toString()) {
// Send Email to the User
console.log('-> Invio Email (', mynewsrec.numemail_sent, '/', mynewsrec.numemail_tot, ')');
const esito = this.sendEmail_base('newsletter/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
//Put the result in the database, to check if is sent or not.
const updateml = await MailingList.findOneAndUpdate({
idapp,
email: user.email
}, { $set: { lastid_newstosent: ObjectID(id_newstosent) } }, { new: false });
mynewsrec.lastemailsent_Job = new Date();
mynewsrec.numemail_sent += 1;
const recsaved = await mynewsrec.save();
//Delay for send email...
await tools.snooze(process.env.DELAY_SENDEMAIL);
if (mynewsrec.numemail_sent === mynewsrec.numemail_tot) {
mynewsrec.datefinishJob = new Date();
mynewsrec.finish_job = true;
await mynewsrec.save().then((ris) => {
console.log('****', tools.getNomeAppByIdApp(idapp), mynewsrec.numemail_sent, 'Email inviate');
});
}
}
}
console.log('FINE (esco da funz) - sendEmail_Newsletter_Events', tools.getNomeAppByIdApp(idapp));
},
checkifSentNewsletter: async function (idapp) {
// Check if is the time to send the Newsletter
return Newstosent.findNewsletter_To_Send(idapp)
.then((rec) => {
if (rec)
this.sendNewsletter(rec);
});
}
,
checkifPendingNewsletter: async function (idapp) {
// Check if is the time to send the Newsletter
// Only newsletter pending en 8 hour last email sent.
return Newstosent.findNewsletterPending_To_Send(idapp)
.then((rec) => { //
this.sendNewsletter(rec)
});
},
sendNewsletter: async function (rec) {
// Start the job
myjobnews = await Newstosent.findOne({ _id: rec._id });
if (!!myjobnews) {
myjobnews.starting_job = true;
myjobnews.datestartJob = new Date();
myjobnews.save()
.then((ris) => {
this.sendEmail_Newsletter_Events("it", '2', rec._id);
})
.catch((e) => {
console.error(e);
});
}
},
testemail: async function (idapp, lang) {
const myarrevents = await MyEvent.getLastEvents(idapp);
mylocalsconf = {
locale: lang,
nomeapp: tools.getNomeAppByIdApp(idapp),
arrevents: myarrevents,
name: 'Paolo',
surname: 'Arena',
emailto: "pa.oloarena77@gmail.com",
};
console.log('-> Invio Email TEST a', mylocalsconf.emailto);
return this.sendEmail_base('newsletter/' + lang, tools.getAdminEmailByIdApp(idapp), mylocalsconf, '');
}
}
;

242
src/server/server.js Normal file
View File

@@ -0,0 +1,242 @@
require('./config/config');
const _ = require('lodash');
const cors = require('cors');
var fs = require('fs');
const port = process.env.PORT;
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const sendemail = require('./sendemail');
const cron = require('node-cron');
i18n = require("i18n");
if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')) {
var privateKey = fs.readFileSync(process.env.PATH_CERT_KEY, 'utf8');
var certificate = fs.readFileSync(process.env.PATH_SERVER_CRT, 'utf8');
var credentials = { key: privateKey, cert: certificate };
var https = require('https');
} else {
var http = require('http');
}
require('./models/todo');
require('./models/project');
require('./models/user');
require('./models/subscribers');
require('./models/cfgserver');
require('./models/booking');
require('./models/sendmsg');
require('./models/mailinglist');
require('./models/newstosent');
const mysql_func = require('./mysql/mysql_func');
const index_router = require('./router/index_router');
const push_router = require('./router/push_router');
const newsletter_router = require('./router/newsletter_router');
const booking_router = require('./router/booking_router');
const myevent_router = require('./router/myevent_router');
const subscribe_router = require('./router/subscribe_router');
const sendmsg_router = require('./router/sendmsg_router');
const email_router = require('./router/email_router');
const todos_router = require('./router/todos_router');
const projects_router = require('./router/projects_router');
const users_router = require('./router/users_router');
const admin_router = require('./router/admin_router');
const { MyEvent } = require('./models/myevent');
require('./db/mongoose');
console.log("DB: " + process.env.DATABASE);
console.log("PORT: " + port);
console.log("MONGODB_URI: " + process.env.MONGODB_URI);
var app = express();
const tools = require('./tools/general');
var mongoose = require('mongoose');
const cfgserver = mongoose.model('cfgserver');
const { ObjectID } = require('mongodb');
app.use(express.static('views'));
// app.use(express.static(path.join(__dirname, 'client')));
app.use(bodyParser.json());
// app.set('view engine', 'pug');
// Set static folder
// app.use(express.static(path.join(__dirname, 'public')));
i18n.configure({
locales: ['it', 'en', 'es'],
directory: __dirname + '/locales'
});
app.use(cors({
exposedHeaders: ['x-auth'],
}));
app.use(bodyParser.json());
app.use(i18n.init);
// Use Routes
app.use('/', index_router);
app.use('/subscribe', subscribe_router);
app.use('/sendmsg', sendmsg_router);
app.use('/push', push_router);
app.use('/signup_news', newsletter_router);
app.use('/booking', booking_router);
app.use('/event', myevent_router);
app.use('/email', email_router);
app.use('/todos', todos_router);
app.use('/projects', projects_router);
app.use('/users', users_router);
app.use('/admin', admin_router);
// catch 404 and forward to error handler
// app.use(function (req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
// });
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug');
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
console.log('Error: ', err.message);
// console.trace();
res.status(err.status || 500).send({ error: err.message });
// res.render('error', {
// message: err.message,
// error: err
// });
});
}
// *** DB CONNECTIONS ***
// mysql_func.mySqlConn_Shen.connect((err) => {
// if (!err)
// console.log('DB connection to Shen Database succeded.');
// else
// console.log('DB connection to Shen Database FAILED \n Error: ' + JSON.stringify(err, undefined, 2));
// });
if ((process.env.NODE_ENV === 'production') || (process.env.NODE_ENV === 'test')) {
var httpsServer = https.createServer(credentials, app);
console.log("httpsServer: port ", port);
httpsServer.listen(port);
} else {
console.log("httpServer: port ", port);
var httpServer = http.createServer(app);
httpServer.listen(port);
}
if (process.env.PROD !== 1) {
// testmsgwebpush();
// sendemail.testemail('2', 'it');
}
// ----------------- MAILCHIMP -----
const querystring = require('querystring');
const mailchimpClientId = 'xxxxxxxxxxxxxxxx';
app.get('/mailchimp/auth/authorize', function (req, res) {
res.redirect('https://login.mailchimp.com/oauth2/authorize?' +
querystring.stringify({
'response_type': 'code',
'client_id': mailchimpClientId,
'redirect_uri': 'http://127.0.0.1:3000/mailchimp/auth/callback'
}));
});
// -----------------
startserv();
function populateDBadmin() {
const cfgserv = [{
_id: new ObjectID(),
chiave: 'vers',
userId: 'ALL',
valore: '0.0.50'
}];
let cfg = new cfgserver(cfgserv[0]).save();
}
function startserv() {
// Check if is Empty (new Server Data)
cfgserver.count(function (err, count) {
if (!err && count === 0) {
populateDBadmin();
}
});
}
function mycron() {
for (const app of MYAPPS) {
sendemail.checkifPendingNewsletter(app.idapp);
sendemail.checkifSentNewsletter(app.idapp);
}
}
function testmsgwebpush() {
var { User } = require('./models/user');
// console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1));
// console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2));
User.findOne().then((user) => {
if (user !== null) {
tools.sendNotificationToUser(user._id, 'Titolo msg Test', 'Test Messaggio', '/', 'msg')
.then(ris => {
if (ris) {
} else {
// already sent the error on calling sendNotificationToUser
}
})
}
});
}
// Cron every 5 minutes
cron.schedule('*/5 * * * *', () => {
console.log('Running Cron Job');
mycron();
});
//app.listen(port, () => {
// console.log(`Server started at port ${port}`);
//});
module.exports = { app };

View File

@@ -0,0 +1,181 @@
const { ObjectID } = require('mongodb');
const jwt = require('jsonwebtoken');
const { Todo } = require('../../models/todo');
const { User } = require('../../models/user');
var bcrypt = require('bcryptjs');
const tools = require('../../tools/general');
let myuserIdOne = '';
const userOneId = new ObjectID();
const userTwoId = new ObjectID();
// const userThreeId = new ObjectID();
// let mypwdcrypt = bcrypt.hash(mypwdchiaro, bcrypt.genSaltSync(12))
// .then((hashedPassword) => {
// console.log('pwd=',hashedPassword);
// });
// String(mypwdcrypt)
let mypwdchiaro = 'mypassword@1A';
let mypwdcrypted = '$2b$12$mteST.isuWO0SNsfeZ0aCe.Dz3qwPh5SU8t9rc5SaPTkb3j0ywGv6'
const date_login = new Date();
// const useragent = "auth Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36"
const useragent = "node-superagent/2.3.0";
const users = [{
_id: userOneId,
keyappid: process.env.KEY_APP_ID,
lang: 'it',
idapp: '1',
email: 'paoloa.rena77@gmail.com',
username: 'paoloar77B',
name: 'Paolo',
surname: 'Arena',
password: mypwdcrypted,
tokens: [{
access: 'auth',
browser: useragent,
token: jwt.sign({ _id: userOneId, access: 'auth' }, process.env.SIGNCODE).toString(),
date_login
}]
},
{
_id: userTwoId,
keyappid: process.env.KEY_APP_ID,
lang: 'it',
idapp: '1',
email: 'pa@com',
name: 'Paolo2',
surname: 'Arena2',
password: mypwdcrypted,
username: 'paoloar77C',
tokens: [{
access: 'auth',
browser: useragent,
token: jwt.sign({ _id: userTwoId, access: 'auth' }, process.env.SIGNCODE).toString(),
date_login
}]
}, {
keyappid: process.env.KEY_APP_ID, // RECORD CHE VERRA' UTILIZZATO PER UNA NUOVA REGISTRAZIONE
lang: 'it',
idapp: '1',
email: 'pao.loarena77@gmail.com',
password: mypwdcrypted,
username: 'paoloar77A',
name: 'Paolo3',
surname: 'Arena3',
}];
const userjson = JSON.stringify(users[0]);
// console.log('userjson=', userjson)
const todos = [{
_id: new ObjectID(),
category: "personal",
statustodo: 0,
completed_at: new Date(),
created_at: new Date(),
descr: "Primo Task Esempio",
enableExpiring: false,
expiring_at: new Date(),
id_prev: null,
modified: false,
modify_at: new Date(),
pos: 1,
priority: 1,
progress: 0,
userId: users[0]._id
}, {
_id: new ObjectID(),
category: "personal",
statustodo: 0,
completed_at: new Date(),
created_at: new Date(),
descr: "Secondo Task Esempio",
enableExpiring: false,
expiring_at: new Date(),
// id_prev: "1",
modified: false,
modify_at: new Date(),
pos: 2,
priority: 1,
progress: 0,
userId: users[0]._id
}, {
_id: new ObjectID(),
category: "personal",
statustodo: 0,
completed_at: new Date(),
created_at: new Date(),
descr: "Terzo Task Esempio",
enableExpiring: false,
expiring_at: new Date(),
// id_prev: "1",
modified: false,
modify_at: new Date(),
pos: 3,
priority: 1,
progress: 0,
}, { // RECORD CHE VERRA' UTILIZZATO PER AGGIUNGERE UN NUOVO TASK
_id: new ObjectID(),
category: "personal",
statustodo: 0,
completed_at: new Date(),
created_at: new Date(),
descr: "Nuovo Quarto Task Esempio da Inserire",
enableExpiring: false,
expiring_at: new Date(),
// id_prev: "2",
modified: false,
modify_at: new Date(),
pos: 4,
priority: 1,
progress: 0,
userId: users[0]._id
}];
const populateTodos = (done) => {
Todo.deleteMany({})
.then(() => {
var TodoOne = new Todo(todos[0]).save();
var TodoTwo = new Todo(todos[1]).save();
return Promise.all([TodoOne, TodoTwo])
}).then(() => {
done()
// tools.mylogshow('todos[0]', todos[0]._id);
// tools.mylogshow('todos[1]', todos[1]._id);
});
};
const populateUsers = (done) => {
User.deleteMany({})
.then(() => {
// console.log('users[0]', users[0])
var userOne = new User(users[0]).save();
var userTwo = new User(users[1]).save();
return Promise.all([userOne, userTwo])
}).then(() => done());
};
module.exports = { todos, populateTodos, users, populateUsers, userjson, mypwdcrypted, mypwdchiaro, date_login };

View File

@@ -0,0 +1,524 @@
const expect = require('expect');
const request = require('supertest');
const { ObjectID } = require('mongodb');
const { app } = require('../server');
const { Todo } = require('../models/todo');
const { User } = require('../models/user');
const { todos, populateTodos, users, populateUsers, userjson, mypwdcrypted, mypwdchiaro, date_login } = require('./seed/seed');
const tools = require('../tools/general');
// const { debug } = require('debug');
// const log = debug('server');
let jsonUser1 = {
email: "paolo.arena77@gmail.com",
password: "$2a$12$hTv40mdq.x35Up7HQ9faae1JgHrohcvp45vt8eMkGhQv/Zv.8.MIG",
username: "paoloar77",
name: 'Paolo',
surname: 'Arena',
idapp: "1",
lang: "it",
keyappid: "KKPPAA5KJK435J3KSS9F9D8S9F8SD98F9SDF"
};
beforeEach(populateUsers);
beforeEach(populateTodos);
const IndexUserToCreate = 2;
const IndexTodoToCreate = 3;
// console.log('UserOne:', users[0]);
// console.log('UserTwo:', users[0]);
// console.log('userjson', userjson);
// const useragent = "auth Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36";
const useragent = "node-superagent/2.3.0";
const testsingolo = false;
if (testsingolo) {
describe('POST /users/login', () => {
it('should login user and return auth token', (done) => {
request(app)
.post('/users/login')
// .set('x-auth', users[0].tokens[0].token)
.send({
username: users[0].username,
name: users[0].name,
surname: users[0].surname,
password: mypwdchiaro,
idapp: users[0].idapp,
keyappid: users[0].keyappid,
lang: users[0].lang,
subs: null,
})
.expect(200)
.expect((res) => {
expect(res.headers['x-auth']).toExist();
})
.end((err, res) => {
if (err) {
return done(err);
}
User.findById(users[0]._id).then((user) => {
expect(user.tokens[0]).toInclude({
access: 'auth',
// token: res.headers['x-auth'],
date_login: date_login
});
done();
}).catch((e) => done(e));
});
});
});
} else {
describe('POST /users', () => {
it('should create a user', (done) => {
request(app)
.post('/users')
.send(users[IndexUserToCreate])
.expect(200)
.expect((res) => {
expect(res.headers['x-auth']).toExist();
expect(res.body._id).toExist();
expect(res.body.email).toBe(users[IndexUserToCreate].email);
expect(res.body.username).toBe(users[IndexUserToCreate].username);
expect(res.body.name).toBe(users[IndexUserToCreate].name);
expect(res.body.surname).toBe(users[IndexUserToCreate].surname);
})
.end((err) => {
if (err) {
console.log('ERR:', err);
return done(err);
}
User.findOne({ email: users[IndexUserToCreate].email }).then((user) => {
expect(user).toExist();
done();
}).catch((e) => done(e));
});
});
it('should return validation errors if request invalid', (done) => {
request(app)
.post('/users')
.send({
email: 'and',
password: '123'
})
.expect(400)
.end(done);
});
it('should not create user if email in use', (done) => {
request(app)
.post('/users')
.send(users[1])
.expect(400)
.end(done);
});
});
describe('GET /users/myusername', () => {
it('should return 200 if myusername exist', (done) => {
request(app)
.get('/users/' + users[0].username)
// .set('x-auth', users[0].tokens[0].token)
.expect(200)
.end(done);
});
it('should return 404 if myusername doesn\'t exist', (done) => {
request(app)
.get('/users/' + users[0].username + 'pippo')
.expect(404)
.end(done);
});
});
describe('POST /users/login', () => {
it('should login user and return auth token', (done) => {
request(app)
.post('/users/login')
// .set('x-auth', users[0].tokens[0].token)
.send({
username: users[0].username,
password: mypwdchiaro,
idapp: users[0].idapp,
keyappid: users[0].keyappid,
lang: users[0].lang,
})
.expect(200)
.expect((res) => {
expect(res.headers['x-auth']).toExist();
})
.end((err, res) => {
if (err) {
return done(err);
}
User.findById(users[0]._id).then((user) => {
expect(user.tokens[0]).toInclude({
access: 'auth',
// token: res.headers['x-auth'],
date_login: date_login
});
done();
}).catch((e) => done(e));
});
});
it('should reject invalid login', (done) => {
request(app)
.post('/users/login')
.send({
username: users[0].username,
password: mypwdchiaro + '1'
})
.expect(400)
.expect((res) => {
expect(res.headers['x-auth']).toNotExist();
})
.end((err, res) => {
if (err) {
return done(err);
}
User.findById(users[1]._id).then((user) => {
expect(user.tokens.length).toBe(1);
done();
}).catch((e) => done(e));
});
});
});
describe('DELETE /users/me/token', () => {
it('should logout user deleting auth token', (done) => {
request(app)
.delete('/users/me/token')
.set('x-auth', users[0].tokens[0].token)
.send()
.expect(200)
.expect((res) => {
expect(res.headers['x-auth']).toNotExist();
})
.end((err, res) => {
if (err) {
return done(err);
}
done();
});
});
it('should return 403 deleting with an invalid token', (done) => {
request(app)
.delete('/users/me/token')
.set('x-auth', users[0].tokens[0].token + '1')
.send()
.expect(403)
.end((err, res) => {
if (err) {
return done(err);
}
done();
});
});
});
describe('POST /todos', () => {
it('should create a new Todos', (done) => {
request(app)
.post('/todos')
.set('x-auth', users[0].tokens[0].token)
.send(todos[IndexTodoToCreate])
.expect(200)
.end((err, res) => {
if (err) {
return done(err);
}
Todo.find({ descr: todos[IndexTodoToCreate].descr }).then((arr_todos) => {
expect(arr_todos.length).toBe(1);
expect(arr_todos[0].descr).toBe(todos[IndexTodoToCreate].descr);
expect(String(arr_todos[0]._id)).toBe(String(todos[IndexTodoToCreate]._id));
expect(String(arr_todos[0].userId)).toBe(String(users[0]._id));
done();
}).catch((e) => done(e));
});
});
it('should return 404 if not authenticated', (done) => {
request(app)
.post('/todos')
.set('x-auth', users[0].tokens[0].token)
.send(todos[IndexTodoToCreate])
.expect(404)
.end((err) => {
done();
});
});
it('should not create todo with invalid body data', (done) => {
request(app)
.post('/todos')
.set('x-auth', users[0].tokens[0].token)
.send({})
.expect(400)
.end((err, res) => {
if (err) {
return done(err);
}
Todo.find().then((todos) => {
done();
}).catch((e) => done(e));
});
});
});
describe('GET /todos', () => {
it('should get all todos', (done) => {
request(app)
.get(`/todos/${users[0]._id }`)
.set('x-auth', users[0].tokens[0].token)
.expect(200)
.expect((res) => {
expect(res.body.todos.length).toBe(2);
})
.end(done);
});
});
describe('GET /todos/:id', () => {
it('should return todos of the User', (done) => {
request(app)
.get(`/todos/${todos[0].userId}`)
.set('x-auth', users[0].tokens[0].token)
.expect(200)
.expect((res) => {
let miores = res
let miadescr = miores.body.todos[0].descr
expect(res.body.todos.length).toBe(2);
expect(miadescr).toBe(todos[0].descr);
})
.end(done);
});
it('should not return todo doc created by other user', (done) => {
request(app)
.get(`/todos/${todos[2].userId}`)
.set('x-auth', users[0].tokens[0].token)
.expect(404)
.end(done);
});
it('FORBIDDEN ! should return [] if user not found', (done) => {
var hexId = new ObjectID().toHexString();
request(app)
.get(`/todos/${hexId}`)
.set('x-auth', users[0].tokens[0].token)
.expect(404)
.expect((res) => {
console.log('res', res.statustodo);
expect(res.body.todos).toBe(undefined);
})
.end(done);
});
it('should return 404 for non-object ids', (done) => {
request(app)
.get('/todos/123abc')
.set('x-auth', users[0].tokens[0].token)
.expect(404)
.end(done);
});
});
describe('DELETE /todos/:id', () => {
it('should remove a todo', (done) => {
var hexId = todos[0]._id.toHexString();
request(app)
.delete(`/todos/${hexId}`)
.set('x-auth', users[0].tokens[0].token)
.expect(200)
.expect((res) => {
expect(res.body.todo._id).toBe(hexId);
})
.end((err, res) => {
if (err) {
return done(err);
}
Todo.findById(hexId).then((todo) => {
expect(todo).toNotExist();
done();
}).catch((e) => done(e));
});
});
it('should return 404 if todo not found', (done) => {
var hexId = new ObjectID().toHexString();
request(app)
.delete(`/todos/${hexId}`)
.set('x-auth', users[0].tokens[0].token)
.expect(404)
.end(done);
});
it('should return 404 if object id is invalid', (done) => {
request(app)
.delete('/todos/123abc')
.set('x-auth', users[0].tokens[0].token)
.expect(404)
.end(done);
});
});
describe('PATCH /todos/:id', () => {
it('should update the todo', (done) => {
var hexId = todos[0]._id.toHexString();
var descr = 'This should be the new text';
request(app)
.patch(`/todos/${hexId}`)
.set('x-auth', users[0].tokens[0].token)
.send({
statustodo: 1,
descr
})
.expect(200)
.expect((res) => {
expect(res.body.todo.descr).toBe(descr);
expect(res.body.todo.statustodo).toBe(1);
// expect(res.body.todo.completedAt).toBeA('number');
})
.end(done);
});
it('should not update the todo created by other user', (done) => {
var hexId = todos[0]._id.toHexString();
var descr = 'This should be the new text';
request(app)
.patch(`/todos/${hexId}`)
.set('x-auth', users[1].tokens[0].token)
.send({
statustodo: 1,
descr
})
.expect(404)
.end(done);
});
// it('should clear completedAt when todo is not completed', (done) => {
// var hexId = todos[1]._id.toHexString();
// var text = 'This should be the new text!!';
//
// request(app)
// .patch(`/todos/${hexId}`)
// .set('x-auth', users[1].tokens[0].token)
// .send({
// completed: false,
// text
// })
// .expect(200)
// .expect((res) => {
// expect(res.body.todo.text).toBe(text);
// expect(res.body.todo.completed).toBe(false);
// expect(res.body.todo.completedAt).toNotExist();
// })
// .end(done);
// });
});
}
/*
});
describe('GET /users/me', () => {
it('should return user if authenticated', (done) => {
request(app)
.get('/users/me')
.set('x-auth', users[0].tokens[0].token)
.expect(200)
.expect((res) => {
expect(res.body._id).toBe(users[0]._id.toHexString());
expect(res.body.email).toBe(users[0].email);
})
.end(done);
});
it('should return 404 if not authenticated', (done) => {
request(app)
.get('/users/me')
.expect(404)
.expect((res) => {
expect(res.body).toEqual({});
})
.end(done);
});
});
describe('DELETE /users/me/token', () => {
it('should remove auth token on logout', (done) => {
request(app)
.delete('/users/me/token')
.set('x-auth', users[0].tokens[0].token)
.expect(200)
.end((err, res) => {
if (err) {
return done(err);
}
User.findById(users[0]._id).then((user) => {
expect(user.tokens.length).toBe(0);
done();
}).catch((e) => done(e));
});
});
});
// sendemail.sendEmail_Registration("en", "paolo.arena77@gmail.com", "paoloar77", 1, "http://provalink.com");
*/
/*
describe('slow test', function() {
// Tests will be considered slow after 1 second elapses
this.slow(1000);
// Completes after the specified 1 second elapses
it('should be complete in a second', function(done) {
setTimeout(done, 1500);
})
// Completes immediately
it('should be complete instantly', function() {})
})
*/

493
src/server/tools/general.js Normal file
View File

@@ -0,0 +1,493 @@
var os = require("os");
require('../config/config');
require('../models/subscribers');
var Url = require('url-parse');
const { ObjectID } = require('mongodb');
const mongoose = require('mongoose');
const Subscription = mongoose.model('subscribers');
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 publicVapidKey = process.env.PUBLIC_VAPI_KEY;
const privateVapidKey = process.env.PRIVATE_VAPI_KEY;
if (process.env.GCM_API_KEY !== "")
webpush.setGCMAPIKey(process.env.GCM_API_KEY);
webpush.setVapidDetails(subject, publicVapidKey, privateVapidKey);
// console.log('setVapidDetails... config...');
module.exports = {
INITDB_FIRSTIME: true,
TYPE_PROJECT: 1,
TYPE_TODO: 2,
FieldType: {
boolean: 1,
date: 2,
string: 4,
binary: 8,
html: 16,
select: 32,
number: 64,
typeinrec: 128,
multiselect: 256,
},
MAX_PHASES: 5,
FIRST_PROJ: '__PROJECTS',
EXECUTE_CALCPROJ: true,
getHostname: function () {
return os.hostname()
},
testing: function () {
return (process.env.TESTING_ON === '1')
},
mylog: function (...args) {
if (!this.testing())
console.log(args)
},
mylogoff: function (...args) {
// doing nothing
},
mylogshow: function (...args) {
console.log(args)
},
mylogserr: function (...args) {
console.error(args)
},
allfieldSendMsg: function () {
return ['userId', 'source', 'dest', 'message', 'datemsg', 'read', 'deleted', 'origin', 'idapp', 'status', 'options']
},
allfieldTodo: function () {
return ['userId', 'pos', 'category', 'descr', 'priority', 'statustodo', 'created_at', 'modify_at',
'completed_at', 'expiring_at', 'enableExpiring', 'id_prev', 'progress', 'modified', 'phase', 'assigned_to_userId', 'hoursplanned', 'hoursworked', 'start_date', 'themecolor', 'themebgcolor']
},
allfieldMyEvent: function () {
return ['userId',]
},
allfieldTodoWithId: function () {
return ['_id', ...this.allfieldTodo()]
},
// #TODO Projects++ Add fields ...
allfieldProject: function () {
return ['userId', 'pos', 'typeproj', 'id_main_project', 'id_parent', 'descr', 'longdescr', 'hoursplanned', 'hoursleft', 'themecolor', 'themebgcolor', 'hoursworked', 'priority', 'statusproj', 'created_at', 'modify_at',
'completed_at', 'expiring_at', 'enableExpiring', 'id_prev', 'progressCalc', 'modified', 'live_url', 'test_url', 'begin_development', 'begin_test', 'totalphases', 'actualphase', 'hoursweeky_plannedtowork', 'endwork_estimate'
, 'privacyread', 'privacywrite']
},
allfieldBooking: function () {
return ['idapp', 'userId', 'id_bookedevent', 'numpeople', 'msgbooking', 'modified', 'infoevent', 'datebooked', 'booked']
},
allfieldBookingChange: function () {
return ['numpeople', 'msgbooking', 'modified', 'infoevent', 'datebooked', 'booked']
},
allfieldProjectWithId: function () {
return ['_id', ...this.allfieldProject()]
},
jsonCopy(src) {
return JSON.parse(JSON.stringify(src))
},
CloneRecordToNew(src) {
const myrec = Object.assign({}, src);
delete myrec._doc['_id'];
myrec._id = new ObjectID();
return myrec._doc
},
sendBackNotif: function (subscription, payload) {
console.log('sendBackNotif:', subscription, payload);
// Pass object into sendNotification
webpush.sendNotification(subscription, JSON.stringify(payload)).catch(err => console.error(err))
.catch(err => {
if (err.statusCode === 410) {
// Gone: is not valid anymore (Expired probably!), so I have to delete from my db
return Subscription.findOneAndRemove({ _id: subscription._id })
} else {
console.log('Subscription is no longer valid: ', err);
}
})
},
sendNotificationToUser: function (userId, title, content, openUrl, tag) {
let payload = {
title: title,
message: content,
url: openUrl,
tag,
// ttl: req.body.ttl,
// icon: req.body.icon,
// image: req.body.image,
// badge: req.body.badge,
// tag: req.body.tag
};
return Subscription.find({ userId }, (err, subscriptions) => {
if (err) {
console.error(`Error occurred while getting subscriptions`);
res.status(500).json({
error: 'Technical error occurred'
});
return false;
} else {
let conta = 0
let parallelSubscriptionCalls = subscriptions.map((subscription) => {
const trovati = subscriptions.length
return new Promise((resolve, reject) => {
const pushSubscription = {
endpoint: subscription.endpoint,
keys: {
p256dh: subscription.keys.p256dh,
auth: subscription.keys.auth
}
};
conta++;
const parse = require('url-parse');
const parsedUrl = parse(subscription.endpoint);
const audience = parsedUrl.protocol + '//' + parsedUrl.hostname;
const vapidHeaders = webpush.getVapidHeaders(
audience,
process.env.URLBASE_APP1,
process.env.PUBLIC_VAPI_KEY,
process.env.PRIVATE_VAPI_KEY,
'aes128gcm'
);
const pushOptions = {
vapidDetails: {
subject: process.env.URLBASE_APP1,
privateKey: process.env.PRIVATE_VAPI_KEY,
publicKey: process.env.PUBLIC_VAPI_KEY,
},
TTL: payload.ttl,
headers: vapidHeaders
};
console.log('************ INVIO WEBPUSH.SENDNOTIFICATION N° ', conta, '/', trovati, 'A', subscription.browser);
// console.log('vapidDetails', pushOptions.vapidDetails);
payload.title = process.env.URLBASE_APP1 + ' Msg n° ' + conta + '/' + trovati;
// payload.message += subscription.browser ;
const pushPayload = JSON.stringify(payload);
// console.log('A1) SUBS: pushSubscription', pushSubscription);
// console.log('A2) OPZIONI: pushOptions', pushOptions);
// console.log('A3) MSG_TO_SEND: pushPayload', pushPayload);
webpush.sendNotification(
pushSubscription,
pushPayload,
// pushOptions
).then((value) => {
resolve({
status: true,
endpoint: subscription.endpoint,
data: value
});
}).catch((err) => {
reject({
status: false,
endpoint: subscription.endpoint,
data: err
});
});
}).catch(error => {
console.log('ERROR: sendNotificationToUser', error.data.body)
});
});
// q.allSettled(parallelSubscriptionCalls).then((pushResults) => {
// console.info(pushResults);
// });
// res.json({
// data: 'Push triggered'
// });
return true;
}
});
},
// **********************
// SORT WITH PREV_ID
// **********************
mapSort: function (linkedList) {
let sortedList = [];
let remainingList = [];
var map = new Map();
var currentId = null;
// console.log('linkedList', linkedList);
// index the linked list by previous_item_id
for (var i = 0; i < linkedList.length; i++) {
var item = linkedList[i];
if (item.id_prev === server_constants.LIST_START) {
// first item
currentId = String(item._id);
// console.log('currentId', currentId);
sortedList.push(item);
} else {
map.set(String(item.id_prev), i);
}
}
let conta = 0;
while (conta < linkedList.length) {
// get the item with a previous item ID referencing the current item
var nextItem = linkedList[map.get(currentId)];
if (nextItem === undefined) {
} else {
sortedList.push(nextItem);
currentId = String(nextItem._id);
}
conta++;
}
if (linkedList.length > sortedList.length) {
// If are not in the list, I'll put at the bottom of the list
// console.log('ATTENZIONE !!! ', sortedList.length, linkedList.length);
for (const itemlinked of linkedList) {
const elemtrov = sortedList.find((item) => item._id === itemlinked._id);
if (elemtrov === undefined) {
sortedList.push(itemlinked);
}
}
}
// console.log('DOPO sortedList', sortedList);
return sortedList;
},
checkUserOk(userpassed, userauth, res) {
this.mylog('checkUserOk', userpassed, userauth);
if (String(userpassed) !== String(userauth)) {
// I'm trying to write something not mine!
this.mylog('userId = ', userpassed, 'req.user._id', userauth);
return { exit: true, ret: res.status(404).send({ code: server_constants.RIS_CODE_TODO_CREATING_NOTMYUSER }) }
} else {
return { exit: false, ret: false }
}
},
convertHTMLtoText(myhtml) {
let msg = myhtml;
msg = msg.replace('&quot;', '"');
msg = msg.replace('&gt;', '>');
msg = msg.replace('&lt;', '<');
msg = msg.replace('&amp;', '&');
msg = msg.replace('<br>', '\n');
return msg
},
convertTexttoHtml(myhtml) {
// let msg = myhtml;
// msg = msg.replace('\n', '<br>');
// return msg
return myhtml;
},
removeSpecialCharForEmail(myhtml) {
let msg = myhtml;
msg = msg.replace(/"/g, '\'');
return msg
},
getNomeAppByIdApp: function (idapp) {
const myapp =
MYAPPS.find(item => item.idapp === idapp);
if (myapp)
return myapp.name;
else
return '';
},
getHostByIdApp: function (idapp) {
const myapp =
MYAPPS.find(item => item.idapp === idapp);
if (myapp) {
let siteport = (myapp.portapp !== "0") ? (':' + myapp.portapp) : "";
return myapp.host + siteport;
} else
return '';
},
getAdminEmailByIdApp: function (idapp) {
const myapp = MYAPPS.find((item) => item.idapp === idapp);
if (myapp)
return myapp.adminemail;
else
return '';
},
getreplyToEmailByIdApp: function (idapp) {
const myapp = MYAPPS.find((item) => item.idapp === idapp);
if (myapp)
return myapp.replyTo;
else
return '';
},
isManagAndAdminDifferent(idapp) {
const manag = this.getManagerEmailByIdApp(idapp);
return (manag !== this.getAdminEmailByIdApp(idapp)) && (manag !== '');
},
getManagerEmailByIdApp: function (idapp) {
const myapp = MYAPPS.find((item) => item.idapp === idapp);
if (myapp)
return myapp.manageremail;
else
return '';
},
getQueryTable(idapp, params) {
// console.log('idapp', idapp);
// console.table(params);
if (typeof params.startRow !== 'number') {
throw new Error('startRow must be number')
} else if (typeof params.endRow !== 'number') {
throw new Error('endRow must be number')
}
let query = [];
if (params.filter && params.fieldsearch) {
let myregexp = {};
myregexp = new RegExp(params.filter.replace(' ', '|'), "ig");
const myfilters = [];
params.fieldsearch.forEach((field) => {
const data = {};
data[field] = myregexp;
myfilters.push(data);
});
query = [
{ $match: { $or: myfilters } },
]
}
if (idapp > 0) {
query.push({ $match: { idapp } });
}
// console.log('QUERYMATCH', query[0].$match.or);
// console.log('filter', params.filter);
if (params.sortBy) {
// maybe we want to sort by blog title or something
const mysort = { $sort: params.sortBy };
// console.log('sortBy', params.sortBy);
// console.table(mysort);
query.push(mysort)
}
query.push(
{
$group: {
_id: null,
// get a count of every result that matches until now
count: { $sum: 1 },
// keep our results for the next operation
results: { $push: '$$ROOT' }
}
},
// and finally trim the results to within the range given by start/endRow
{
$project: {
count: 1,
rows: { $slice: ['$results', params.startRow, params.endRow] }
}
}
);
console.log('query', query);
return query;
},
executeQueryTable(mythistable, idapp, params) {
let query = this.getQueryTable(idapp, params);
return mythistable
.aggregate(query)
.then(([ris]) => {
if (ris) {
// console.table(ris.rows);
// console.log('ROW ', ris.count);
return ({ count: ris.count, rows: ris.rows })
} else {
return ({ count: 0, rows: [] })
}
})
.catch(err => {
console.error(err);
return {
count: 0, rows: []
}
});
},
isBitActive(bit, whattofind) {
return ((bit & whattofind) === whattofind)
},
SetBit(myval, bit) {
myval = myval & bit;
return myval
},
snooze(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
},
IncDateNow(secs) {
let mydate = new Date(new Date().getTime() + secs);
// console.log('mydate', mydate);
return mydate
}
};

View File

@@ -0,0 +1,66 @@
module.exports = Object.freeze({
RIS_CODE_TODO_CREATING_NOTMYUSER: -1001,
RIS_CODE_NOT_MY_USERNAME: -1010,
RIS_CODE_ERR: -99,
RIS_CODE_EMAIL_ALREADY_VERIFIED: -5,
RIS_CODE_EMAIL_VERIFIED: 1,
RIS_CODE_EMAIL_NOT_SENT: -40,
RIS_CODE_ERR_UNAUTHORIZED: -30,
RIS_CODE_LOGIN_ERR_GENERIC: -20,
RIS_CODE_LOGIN_ERR: -10,
RIS_CODE_OK: 1,
RIS_CODE_LOGIN_OK: 1,
RIS_CODE_HTTP_INVALID_TOKEN: 403,
RIS_SUBSCRIBED_OK: 1,
RIS_SUBSCRIBED_ALREADYEXIST: 2,
RIS_SUBSCRIBED_ERR: -1,
RIS_SUBSCRIBED_STR: 'subscribed',
MenuAction: {
DELETE: 100,
},
RIS_SUBSCRIBED_MSG: {
enUs: 'Subscription to the Newsletter Confirmed!',
es: 'Suscripción al boletín confirmado!',
it: 'Sottoscrizione alla Newsletter Confermata!',
fr: 'Inscription à la newsletter confirmée!',
de: 'Anmeldung zum Newsletter bestätigt!'
} ,
RIS_SUBSCRIBED_MSG_ALREADYEXIST: {
enUs: 'Subscription already made!',
es: 'Suscripción ya realizada!',
it: 'Sottoscrizione già effettuata!',
fr: 'Abonnement déjà fait!',
de: 'Abonnement bereits gemacht!'
} ,
RIS_SUBSCRIBED_MSG_FAILED: {
enUs: 'Sign Up Failed :(',
es: 'Suscripción al boletín fallido',
it: 'Sottoscrizione alla Newsletter Fallita',
fr: 'Abonnement à la newsletter en échec',
de: 'Abonnement des fehlgeschlagenen Newsletters',
} ,
LIST_END: '10000000',
LIST_START: null,
Privacy: {
all: 'all',
friends: 'friends',
mygroup: 'mygroup',
onlyme: 'onlyme'
},
TypeProj: {
TYPE_PROJECT: 1,
TYPE_SUBDIR: 2,
}
});

View File

@@ -0,0 +1,18 @@
module.exports = {
Permissions: {
Admin: 1,
Manager: 2,
Teacher: 4,
},
MessageOptions: {
Notify_ByEmail: 2,
Notify_ByPushNotification: 4
},
fieldsUserToChange() {
return ['_id', 'username', 'email', 'cell', 'name', 'surname', 'perm', 'date_reg', 'verified_email', 'img', 'ipaddr', 'lasttimeonline', 'profile', 'news_on']
}
};

View File

@@ -0,0 +1,10 @@
<!doctype html>
<html>
<head>
<title>Integrate MailChimp</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/spectre.css/0.1.25/spectre.min.css" rel="stylesheet" crossorigin="anonymous">
</head>
<body>
<a class="btn btn-primary" href="/mailchimp/auth/authorize">Connect with MailChimp</a>
</body>
</html>