Show data Table with pagination (startRow, endRow, filter, sorting)

This commit is contained in:
Paolo Arena
2019-10-14 20:31:57 +02:00
parent c5a19f2d70
commit 9120485939
8 changed files with 219 additions and 34 deletions

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 };

View File

@@ -6,6 +6,9 @@ const _ = require('lodash');
const tools = require('../tools/general'); const tools = require('../tools/general');
const shared_consts = require('../tools/shared_nodejs');
const queryclass = require('../classes/queryclass');
mongoose.Promise = global.Promise; mongoose.Promise = global.Promise;
mongoose.level = "F"; mongoose.level = "F";
@@ -86,6 +89,9 @@ var UserSchema = new mongoose.Schema({
perm: { perm: {
type: Number type: Number
}, },
ipaddr: {
type: String,
},
date_reg: { date_reg: {
type: Date, type: Date,
default: Date.now() default: Date.now()
@@ -148,8 +154,7 @@ UserSchema.statics.setPermissionsById = function (id, perm) {
UserSchema.statics.isAdmin = function (user) { UserSchema.statics.isAdmin = function (user) {
try { try {
const ris = ((user.perm & tools.Permissions.Admin) === 1); return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin);
return ris;
}catch (e) { }catch (e) {
return false return false
} }
@@ -263,6 +268,8 @@ UserSchema.statics.findByEmail = function (idapp, email) {
UserSchema.pre('save', function (next) { 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) => {
@@ -291,12 +298,73 @@ UserSchema.methods.removeToken = function (token) {
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 }) return User.find({ 'idapp': idapp }, { username: 1, name: 1, surname: 1, verified_email: 1, perm:1, email: 1, date_reg: 1 })
}; };
var User = mongoose.model('User', UserSchema); 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 })
};
/**
* Query blog posts by user -> paginated results and a total count.
* @returns {Object} Object -> `{ rows, count }`
*/
UserSchema.statics.queryTable = function (idapp, params) {
const User = this;
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')
}
const query = [
{ $match: Object.assign({ idapp }, 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] }
} }
);
return User
.aggregate(query)
.then(([{ count, rows }]) => ({ count, rows }))
};
const User = mongoose.model('User', UserSchema);
class Hero { class Hero {
constructor(name, level) { constructor(name, level) {

View File

@@ -15,4 +15,14 @@ module.exports = {
console.error(e); console.error(e);
} }
}, },
getiPAddressUser: function (req) {
try {
return req.ip; // Express
} catch (e) {
return ''
}
}
}; };

View File

@@ -13,6 +13,8 @@ const _ = require('lodash');
var { User } = require('../models/user'); var { User } = require('../models/user');
const tools = require('../tools/general');
var server_constants = require('../tools/server_constants'); var server_constants = require('../tools/server_constants');
@@ -147,4 +149,26 @@ router.post(process.env.LINK_UPDATE_PASSWORD, (req, res) => {
}); });
router.post('/gettable', authenticate, (req, res) => {
const params = req.body;
tools.mylog('GET ALL USERS: ', params);
let mytable = null;
if (params.table === 'users')
mytable = User;
else if (params.table === 'booking')
mytable = Booking;
return mytable.queryTable(req.user.idapp, params).then(ris => {
tools.mylog('list', ris);
return res.send(ris);
}).catch((e) => {
console.log(e);
res.status(400).send(e);
});
});
module.exports = router; module.exports = router;

View File

@@ -40,6 +40,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);
if (tools.testing()) { if (tools.testing()) {
user.verified_email = true; user.verified_email = true;
} }
@@ -95,7 +96,7 @@ router.patch('/:id', authenticate, (req, res) => {
if (!User.isAdmin(req.user)) { if (!User.isAdmin(req.user)) {
// If without permissions, exit // If without permissions, exit
return res.status(404).send(); return res.status(404).send({ code: server_constants.RIS_CODE_ERR_UNAUTHORIZED, msg: '' });
} }
User.findByIdAndUpdate(id, { $set: body }).then((user) => { User.findByIdAndUpdate(id, { $set: body }).then((user) => {
@@ -147,6 +148,10 @@ router.post('/login', (req, res) => {
usertosend.userId = user._id.toHexString(); usertosend.userId = user._id.toHexString();
usertosend.verified_email = user.verified_email; usertosend.verified_email = user.verified_email;
usertosend.idapp = user.idapp; usertosend.idapp = user.idapp;
usertosend.perm = user.perm;
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);
@@ -155,32 +160,32 @@ router.post('/login', (req, res) => {
// tools.mylog(usertosend); // tools.mylog(usertosend);
return { usertosend, token } return { usertosend, token }
}) })
.then((myris) => { .then((myris) => {
const access = 'auth'; const access = 'auth';
const browser = req.get('User-Agent'); const browser = req.get('User-Agent');
// Check if already exist Subscribe // Check if already exist Subscribe
return existSubScribe(myris.usertosend.userId, access, browser).then(subscribe => { return existSubScribe(myris.usertosend.userId, access, browser).then(subscribe => {
return (subscribe !== null) return (subscribe !== null)
}).then(subsExistonDb => { }).then(subsExistonDb => {
return { usertosend: myris.usertosend, token: myris.token, subsExistonDb } return { usertosend: myris.usertosend, token: myris.token, subsExistonDb }
}).catch(err => { }).catch(err => {
return { usertosend: myris.usertosend, token: myris.token, subsExistonDb:false } return { usertosend: myris.usertosend, token: myris.token, subsExistonDb: false }
}) })
}).then(myris => { }).then(myris => {
console.log('res', myris.token, myris.usertosend); console.log('res', myris.token, myris.usertosend);
// SEND TOKEN AND CODE RESULT // SEND TOKEN AND CODE RESULT
res.header('x-auth', myris.token).send({ res.header('x-auth', myris.token).send({
usertosend: myris.usertosend, usertosend: myris.usertosend,
code: server_constants.RIS_CODE_OK, code: server_constants.RIS_CODE_OK,
subsExistonDb: myris.subsExistonDb subsExistonDb: myris.subsExistonDb
});
// tools.mylog("TROVATOOO!");
tools.mylog('FINE LOGIN')
}); });
// tools.mylog("TROVATOOO!");
tools.mylog('FINE LOGIN')
});
} }
}) })
.catch((e) => { .catch((e) => {
@@ -210,4 +215,5 @@ router.post('/setperm', authenticate, (req, res) => {
}); });
}); });
module.exports = router; module.exports = router;

View File

@@ -33,11 +33,6 @@ module.exports = {
FIRST_PROJ: '__PROJECTS', FIRST_PROJ: '__PROJECTS',
EXECUTE_CALCPROJ: true, EXECUTE_CALCPROJ: true,
Permissions: {
Normal: 0,
Admin: 1,
},
getHostname: function () { getHostname: function () {
return os.hostname() return os.hostname()
}, },

View File

@@ -5,6 +5,7 @@ module.exports = Object.freeze({
RIS_CODE_EMAIL_ALREADY_VERIFIED: -5, RIS_CODE_EMAIL_ALREADY_VERIFIED: -5,
RIS_CODE_EMAIL_VERIFIED: 1, RIS_CODE_EMAIL_VERIFIED: 1,
RIS_CODE_ERR_UNAUTHORIZED: -30,
RIS_CODE_LOGIN_ERR_GENERIC: -20, RIS_CODE_LOGIN_ERR_GENERIC: -20,
RIS_CODE_LOGIN_ERR: -10, RIS_CODE_LOGIN_ERR: -10,
RIS_CODE_OK: 1, RIS_CODE_OK: 1,

View File

@@ -1,7 +1,12 @@
module.exports = { module.exports = {
Permissions: {
Normal: 0,
Admin: 1,
},
fieldsUserToChange() { fieldsUserToChange() {
return ['username', 'email', 'name', 'surname', 'perm', 'date_reg'] return ['username', 'email', 'name', 'surname', 'perm', 'date_reg', 'verified_email']
} }
}; };