- Create Newsletter Page: MailingList (without the class style, using Gulp tasks)#94
This commit is contained in:
26
src/server/router/admin_router.js
Normal file
26
src/server/router/admin_router.js
Normal 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;
|
||||
29
src/server/router/api/actions.js
Normal file
29
src/server/router/api/actions.js
Normal 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;
|
||||
}
|
||||
};
|
||||
136
src/server/router/booking_router.js
Normal file
136
src/server/router/booking_router.js
Normal 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;
|
||||
20
src/server/router/email_router.js
Normal file
20
src/server/router/email_router.js
Normal 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;
|
||||
434
src/server/router/index_router.js
Normal file
434
src/server/router/index_router.js
Normal 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;
|
||||
114
src/server/router/myevent_router.js
Normal file
114
src/server/router/myevent_router.js
Normal 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;
|
||||
108
src/server/router/newsletter_router.js
Normal file
108
src/server/router/newsletter_router.js
Normal 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;
|
||||
223
src/server/router/projects_router.js
Normal file
223
src/server/router/projects_router.js
Normal 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;
|
||||
82
src/server/router/push_router.js
Normal file
82
src/server/router/push_router.js
Normal 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;
|
||||
116
src/server/router/sendmsg_router.js
Normal file
116
src/server/router/sendmsg_router.js
Normal 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;
|
||||
101
src/server/router/subscribe_router.js
Normal file
101
src/server/router/subscribe_router.js
Normal 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;
|
||||
185
src/server/router/todos_router.js
Normal file
185
src/server/router/todos_router.js
Normal 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;
|
||||
216
src/server/router/users_router.js
Normal file
216
src/server/router/users_router.js
Normal 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;
|
||||
Reference in New Issue
Block a user