Step 2: Creating page Messages: userlist last messages + a page for all the messages received and sent.

This commit is contained in:
Paolo Arena
2019-10-27 00:37:10 +02:00
parent e6c4053ccf
commit 5307c04151
9 changed files with 106 additions and 60 deletions

View File

@@ -18,12 +18,18 @@ const authenticate = (req, res, next) => {
return Promise.reject(server_constants.RIS_CODE_HTTP_INVALID_TOKEN); return Promise.reject(server_constants.RIS_CODE_HTTP_INVALID_TOKEN);
// res.status().send(); // 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); // tools.mylog('userid', user._id);
req.user = user;
req.token = token;
req.access = access;
next();
}).catch((e) => { }).catch((e) => {
tools.mylog("ERR =", e); tools.mylog("ERR =", e);
res.status(server_constants.RIS_CODE_HTTP_INVALID_TOKEN).send(); res.status(server_constants.RIS_CODE_HTTP_INVALID_TOKEN).send();

View File

@@ -19,15 +19,6 @@ const OperatorSchema = new Schema({
username: { username: {
type: String, type: String,
}, },
name: {
type: String,
},
surname: {
type: String,
},
email: {
type: String,
},
cell: { cell: {
type: String, type: String,
}, },
@@ -54,14 +45,6 @@ const OperatorSchema = new Schema({
}, },
}); });
OperatorSchema.statics.getEmailByUsername = async function (idapp, username) {
const Operator = this;
return await Operator.findOne({idapp, username}, (err, arrrec) => {
return (arrrec) ? arrrec.email : '';
});
};
OperatorSchema.statics.executeQueryTable = function (idapp, params) { OperatorSchema.statics.executeQueryTable = function (idapp, params) {
return tools.executeQueryTable(this, idapp, params); return tools.executeQueryTable(this, idapp, params);
}; };

View File

@@ -32,6 +32,12 @@ const sendmsgSchema = new Schema({
datemsg: { datemsg: {
type: Date, type: Date,
}, },
status: {
type: Number,
},
options: {
type: Number,
},
read: { read: {
type: Boolean, type: Boolean,
default: false default: false
@@ -53,7 +59,7 @@ sendmsgSchema.statics.findAllMsgByUsernameIdAndIdApp = function (username, lastd
{ idapp } { idapp }
] ]
}).then((arrmsg) => { }).then((arrmsg) => {
console.log('arrmsg', arrmsg); console.log('arrmsg', arrmsg.length);
return arrmsg return arrmsg
}).catch((err) => { }).catch((err) => {
console.error('err', err); console.error('err', err);
@@ -88,8 +94,12 @@ sendmsgSchema.statics.findLastGroupByUserIdAndIdApp = function (userId, username
}, },
]) ])
.then((arrmsg) => { .then((arrmsg) => {
console.table(arrmsg); // Remove duplicate
return arrmsg // Exclude my chat
const myarr = arrmsg.filter((ris) => ris._id !== username);
console.table(myarr);
return myarr
}).catch((err) => { }).catch((err) => {
console.error(err); console.error(err);
}); });

View File

@@ -105,6 +105,9 @@ var UserSchema = new mongoose.Schema({
tokenforgot: { tokenforgot: {
type: String, type: String,
}, },
lasttimeonline: {
type: Date
}
}); });
@@ -133,6 +136,8 @@ UserSchema.methods.generateAuthToken = function (req) {
}); });
user.tokens.push({ access, browser, token, date_login }); user.tokens.push({ access, browser, token, date_login });
user.lasttimeonline = new Date();
return user.save() return user.save()
.then(() => { .then(() => {
console.log("TOKEN CREATO IN LOGIN : " + token); console.log("TOKEN CREATO IN LOGIN : " + token);
@@ -158,7 +163,7 @@ UserSchema.statics.setPermissionsById = function (id, perm) {
UserSchema.statics.isAdmin = function (user) { UserSchema.statics.isAdmin = function (user) {
try { try {
return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin); return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
}catch (e) { } catch (e) {
return false return false
} }
}; };
@@ -166,7 +171,7 @@ UserSchema.statics.isAdmin = function (user) {
UserSchema.statics.isManager = function (user) { UserSchema.statics.isManager = function (user) {
try { try {
return ((user.perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager); return ((user.perm & shared_consts.Permissions.Manager) === shared_consts.Permissions.Manager);
}catch (e) { } catch (e) {
return false return false
} }
}; };
@@ -280,7 +285,6 @@ UserSchema.pre('save', function (next) {
var user = this; var user = this;
/* /*
if (user.isModified('password')) { if (user.isModified('password')) {
bcrypt.genSalt(10, (err, salt) => { bcrypt.genSalt(10, (err, salt) => {
@@ -306,10 +310,31 @@ UserSchema.methods.removeToken = function (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) { UserSchema.statics.getUsersList = function (idapp) {
const User = this; 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 }) return User.find({ 'idapp': idapp }, {
username: 1,
name: 1,
surname: 1,
verified_email: 1,
perm: 1,
email: 1,
date_reg: 1,
img: 1
})
}; };
@@ -324,7 +349,7 @@ UserSchema.statics.getUsersListByParams = function (params) {
return User.find( return User.find(
{ $match: filterMatchBefore }, { $match: filterMatchBefore },
{ 'idapp': idapp }, { 'idapp': idapp },
{ username: 1, name: 1, surname: 1, verified_email: 1, perm:1, email: 1, date_reg: 1, img: 1 }) { username: 1, name: 1, surname: 1, verified_email: 1, perm: 1, email: 1, date_reg: 1, img: 1, lasttimeonline: 1 })
}; };

View File

@@ -45,6 +45,7 @@ router.post(process.env.LINKVERIF_REG, (req, res) => {
}); });
} else { } else {
user.verified_email = true; user.verified_email = true;
user.lasttimeonline = new Date();
user.save().then(() => { user.save().then(() => {
//console.log("TROVATOOOOOO!"); //console.log("TROVATOOOOOO!");
res.send({ code: server_constants.RIS_CODE_EMAIL_VERIFIED, msg: res.__('Email Verificata!') }); res.send({ code: server_constants.RIS_CODE_EMAIL_VERIFIED, msg: res.__('Email Verificata!') });
@@ -73,6 +74,7 @@ router.post(process.env.LINK_REQUEST_NEWPASSWORD, (req, res) => {
// Creo il tokenforgot // Creo il tokenforgot
user.tokenforgot = jwt.sign(user._id.toHexString(), process.env.SIGNCODE).toString(); user.tokenforgot = jwt.sign(user._id.toHexString(), process.env.SIGNCODE).toString();
user.date_tokenforgot = new Date(); user.date_tokenforgot = new Date();
user.lasttimeonline = new Date();
user.save().then(() => { user.save().then(() => {
sendemail.sendEmail_RequestNewPassword(res.locale, user.email, user.idapp, user.tokenforgot); sendemail.sendEmail_RequestNewPassword(res.locale, user.email, user.idapp, user.tokenforgot);
res.send({ code: server_constants.RIS_CODE_OK, msg: '' }); res.send({ code: server_constants.RIS_CODE_OK, msg: '' });
@@ -103,6 +105,7 @@ router.post(process.env.LINK_UPDATE_PASSWORD, (req, res) => {
} else { } else {
// aggiorna la nuova password // aggiorna la nuova password
user.password = password; user.password = password;
user.lasttimeonline = new Date();
// Crea token // Crea token
user.generateAuthToken(req).then(token => { user.generateAuthToken(req).then(token => {
@@ -318,6 +321,7 @@ router.get('/loadsite/:userId/:idapp/:sall', authenticate_noerror, (req, res) =>
const wheres = Where.findAllIdApp(idapp); const wheres = Where.findAllIdApp(idapp);
const contribtype = Contribtype.findAllIdApp(idapp); const contribtype = Contribtype.findAllIdApp(idapp);
return Promise.all([bookedevent, eventlist, operators, wheres, contribtype]) return Promise.all([bookedevent, eventlist, operators, wheres, contribtype])
.then((arrdata) => { .then((arrdata) => {
// console.table(arrdata); // console.table(arrdata);
@@ -357,7 +361,6 @@ router.get(process.env.LINK_CHECK_UPDATES, authenticate, (req, res) => {
// msgs = SendMsg.findAllByUserIdAndIdApp(userId, req.user.username, req.user.idapp); // msgs = SendMsg.findAllByUserIdAndIdApp(userId, req.user.username, req.user.idapp);
last_msgs = SendMsg.findLastGroupByUserIdAndIdApp(userId, req.user.username, req.user.idapp); last_msgs = SendMsg.findLastGroupByUserIdAndIdApp(userId, req.user.username, req.user.idapp);
let usersList = null; let usersList = null;
if (req.user) { if (req.user) {

View File

@@ -6,26 +6,32 @@ const server_constants = require('../tools/server_constants');
const { authenticate } = require('../middleware/authenticate'); const { authenticate } = require('../middleware/authenticate');
const { Operator } = require('../models/operator'); const { User } = require('../models/user');
const { SendMsg } = require('../models/sendmsg'); const { SendMsg } = require('../models/sendmsg');
const { ObjectID } = require('mongodb'); const { ObjectID } = require('mongodb');
const sendemail = require('../sendemail'); const sendemail = require('../sendemail');
const shared_consts = require('../tools/shared_nodejs');
const _ = require('lodash'); const _ = require('lodash');
async function sendNotif(res, idapp, user, recmsg) { async function sendNotif(res, idapp, user, recmsg) {
//++Todo: tools.sendNotificationToUser if (tools.isBitActive(recmsg.options, shared_consts.MessageOptions.Notify_ByPushNotification)) {
//++Todo: tools.sendNotificationToUser
console.log('SEND PUSH NOTIFICATION ')
}
// Extract the Email Destination // Extract the Email Destination
const emaildest = await Operator.getEmailByUsername(recmsg.dest.idapp, recmsg.dest.username); const emaildest = await User.getEmailByUsername(recmsg.dest.idapp, recmsg.dest.username);
console.log('emaildest', emaildest); console.log('emaildest', emaildest);
// Send Msg by EMAIL // Send Msg by EMAIL
if (emaildest) if (emaildest && tools.isBitActive(recmsg.options, shared_consts.MessageOptions.Notify_ByEmail))
return await sendemail.sendEmail_Msg(res, user.lang, emaildest, user, idapp, recmsg); await sendemail.sendEmail_Msg(res, user.lang, emaildest, user, idapp, recmsg);
return true
} }
router.post('/', authenticate, (req, res) => { router.post('/', authenticate, (req, res) => {
@@ -36,7 +42,7 @@ router.post('/', authenticate, (req, res) => {
tools.mylog('crea SendMsg'); tools.mylog('crea SendMsg');
const myrecmsg = new SendMsg(body); const myrecmsg = new SendMsg(body);
const check = tools.checkUserOk(myrecmsg.origin.userId, req.user._id); const check = tools.checkUserOk(myrecmsg.origin.username, req.user.username);
if (check.exit) return check.ret; if (check.exit) return check.ret;
// console.log('fieldtochange', fieldtochange); // console.log('fieldtochange', fieldtochange);
@@ -54,36 +60,38 @@ router.post('/', authenticate, (req, res) => {
recmsg.origin.infoevent = body.origin.infoevent; recmsg.origin.infoevent = body.origin.infoevent;
return sendNotif(res, body.idapp, req.user, recmsg).then((ris) => { return sendNotif(res, body.idapp, req.user, recmsg).then((ris) => {
if (ris) return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmsg._id });
return res.send({ code: server_constants.RIS_CODE_OK, msg: '', id: recmsg._id });
else
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
}) })
}); });
}).catch((e) => { }).catch((e) => {
console.log(e); console.log(e);
res.status(400).send(e); // res.status(400).send(e);
return res.send({ code: server_constants.RIS_CODE_ERR, msg: '' });
}) })
}); });
router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => { router.get('/:username/:lastdataread/:idapp', authenticate, (req, res) => {
tools.mylog('GET SendMsgS : ', req.params);
const username = req.params.username; const username = req.params.username;
const lastdataread = req.params.lastdataread; const lastdataread = req.params.lastdataread;
const idapp = req.params.idapp; const idapp = req.params.idapp;
// var category = req.params.category; // var category = req.params.category;
tools.mylog('GET SendMsgS : ', req.params);
if (req.user.idapp !== idapp) { if (req.user.idapp !== idapp) {
// I'm trying to get something not mine! // I'm trying to get something not mine!
return res.status(404).send({ code: server_constants.RIS_CODE_NOT_MY_USERNAME }); return res.status(404).send({ code: server_constants.RIS_CODE_NOT_MY_USERNAME });
} }
// Extract all the todos of the userId only // Extract all the todos of the userId only
return SendMsg.findAllMsgByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrmsg) => { return SendMsg.findAllMsgByUsernameIdAndIdApp(username, lastdataread, idapp).then((arrmsg) => {
// const wait = new Promise((resolve, reject) => {
// setTimeout(() => {
res.send({ arrmsg }); res.send({ arrmsg });
// }, 2000);
// });
}).catch((e) => { }).catch((e) => {
console.log(e); console.log(e);
res.status(400).send(e); res.status(400).send(e);

View File

@@ -41,6 +41,7 @@ router.post('/', (req, res) => {
user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username); user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username);
user.verified_email = false; user.verified_email = false;
user.ipaddr = reg.getiPAddressUser(req); user.ipaddr = reg.getiPAddressUser(req);
user.lasttimeonline = new Date();
if (tools.testing()) { if (tools.testing()) {
user.verified_email = true; user.verified_email = true;
} }
@@ -141,24 +142,19 @@ router.post('/login', (req, res) => {
if (user) { if (user) {
return user.generateAuthToken(req).then((token) => { return user.generateAuthToken(req).then((token) => {
var usertosend = User(); var usertosend = User();
usertosend.username = user.username;
usertosend.name = user.name; shared_consts.fieldsUserToChange().forEach((field) => {
usertosend.surname = user.surname; usertosend[field] = user[field]
usertosend.email = user.email; });
usertosend._id = user._id.toHexString();
usertosend.verified_email = user.verified_email; // usertosend._id = user._id.toHexString();
usertosend.idapp = user.idapp; // if (!User.isAdmin(req.user)) {
usertosend.perm = user.perm; // usertosend.ipaddr = user.ipaddr;
usertosend.img = user.img; // }
if (!User.isAdmin(req.user)) {
usertosend.ipaddr = user.ipaddr;
}
// tools.mylog("user.verified_email:" + user.verified_email); // tools.mylog("user.verified_email:" + user.verified_email);
tools.mylog("usertosend.userId", usertosend.userId); tools.mylog("usertosend.userId", usertosend.userId);
// tools.mylog("usertosend:");
// tools.mylog(usertosend);
return { usertosend, token } return { usertosend, token }
}) })

View File

@@ -60,7 +60,7 @@ module.exports = {
}, },
allfieldSendMsg: function () { allfieldSendMsg: function () {
return ['userId', 'dest', 'message', 'datemsg', 'read', 'deleted', 'origin', 'idapp'] return ['userId', 'source', 'dest', 'message', 'datemsg', 'read', 'deleted', 'origin', 'idapp', 'status', 'options']
}, },
allfieldTodo: function () { allfieldTodo: function () {
@@ -417,5 +417,15 @@ module.exports = {
} }
}); });
},
isBitActive(bit, whattofind) {
return ((bit & whattofind) === whattofind)
},
SetBit(myval, bit) {
myval = myval & bit;
return myval
} }
}; };

View File

@@ -6,8 +6,13 @@ module.exports = {
Manager: 2, Manager: 2,
}, },
MessageOptions: {
Notify_ByEmail: 2,
Notify_ByPushNotification: 4
},
fieldsUserToChange() { fieldsUserToChange() {
return ['username', 'email', 'name', 'surname', 'perm', 'date_reg', 'verified_email', 'img', 'ipaddr'] return ['username', 'email', 'name', 'surname', 'perm', 'date_reg', 'verified_email', 'img', 'ipaddr', 'lasttimeonline']
} }
}; };