Files
freeplanet_serverside/server/router/index_router.js

390 lines
10 KiB
JavaScript

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 { SendMsg } = require('../models/sendmsg');
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.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.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;
// 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;
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;
mytablerec = new mytable(mydata);
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);
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);
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);
});
});
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;