diff --git a/server/classes/queryclass.js b/server/classes/queryclass.js new file mode 100644 index 0000000..b0bb8e3 --- /dev/null +++ b/server/classes/queryclass.js @@ -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 }; diff --git a/server/models/user.js b/server/models/user.js index 2ba44a6..cad8ac9 100644 --- a/server/models/user.js +++ b/server/models/user.js @@ -6,6 +6,9 @@ const _ = require('lodash'); const tools = require('../tools/general'); +const shared_consts = require('../tools/shared_nodejs'); +const queryclass = require('../classes/queryclass'); + mongoose.Promise = global.Promise; mongoose.level = "F"; @@ -86,6 +89,9 @@ var UserSchema = new mongoose.Schema({ perm: { type: Number }, + ipaddr: { + type: String, + }, date_reg: { type: Date, default: Date.now() @@ -148,8 +154,7 @@ UserSchema.statics.setPermissionsById = function (id, perm) { UserSchema.statics.isAdmin = function (user) { try { - const ris = ((user.perm & tools.Permissions.Admin) === 1); - return ris; + return ((user.perm & shared_consts.Permissions.Admin) === shared_consts.Permissions.Admin); }catch (e) { return false } @@ -263,6 +268,8 @@ UserSchema.statics.findByEmail = function (idapp, email) { UserSchema.pre('save', function (next) { var user = this; + + /* if (user.isModified('password')) { bcrypt.genSalt(10, (err, salt) => { @@ -291,12 +298,73 @@ UserSchema.methods.removeToken = function (token) { UserSchema.statics.getUsersList = function (idapp) { const User = this; - return User.find({ 'idapp': idapp }, { username: 1, name: 1, surname: 1, verified_email: 1, perm:1, email: 1 }) + 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 { constructor(name, level) { diff --git a/server/reg/registration.js b/server/reg/registration.js index 7d7ad3e..d6d6072 100644 --- a/server/reg/registration.js +++ b/server/reg/registration.js @@ -15,4 +15,14 @@ module.exports = { console.error(e); } }, + + getiPAddressUser: function (req) { + try { + return req.ip; // Express + } catch (e) { + return '' + } + } + + }; diff --git a/server/router/index_router.js b/server/router/index_router.js index 25dab31..5b61da7 100644 --- a/server/router/index_router.js +++ b/server/router/index_router.js @@ -13,6 +13,8 @@ const _ = require('lodash'); var { User } = require('../models/user'); +const tools = require('../tools/general'); + 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; diff --git a/server/router/users_router.js b/server/router/users_router.js index c6f76ae..7a3f894 100644 --- a/server/router/users_router.js +++ b/server/router/users_router.js @@ -40,6 +40,7 @@ router.post('/', (req, res) => { user.linkreg = reg.getlinkregByEmail(body.idapp, body.email, body.username); user.verified_email = false; + user.ipaddr = reg.getiPAddressUser(req); if (tools.testing()) { user.verified_email = true; } @@ -95,7 +96,7 @@ router.patch('/:id', authenticate, (req, res) => { if (!User.isAdmin(req.user)) { // 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) => { @@ -147,6 +148,10 @@ router.post('/login', (req, res) => { usertosend.userId = user._id.toHexString(); usertosend.verified_email = user.verified_email; 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("usertosend.userId", usertosend.userId); @@ -155,32 +160,32 @@ router.post('/login', (req, res) => { // tools.mylog(usertosend); return { usertosend, token } - }) - .then((myris) => { - const access = 'auth'; - const browser = req.get('User-Agent'); + }) + .then((myris) => { + const access = 'auth'; + const browser = req.get('User-Agent'); - // Check if already exist Subscribe - return existSubScribe(myris.usertosend.userId, 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); + // Check if already exist Subscribe + return existSubScribe(myris.usertosend.userId, 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 + // 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') }); - // tools.mylog("TROVATOOO!"); - - tools.mylog('FINE LOGIN') - }); } }) .catch((e) => { @@ -210,4 +215,5 @@ router.post('/setperm', authenticate, (req, res) => { }); }); + module.exports = router; diff --git a/server/tools/general.js b/server/tools/general.js index a447b2c..3c44346 100644 --- a/server/tools/general.js +++ b/server/tools/general.js @@ -33,11 +33,6 @@ module.exports = { FIRST_PROJ: '__PROJECTS', EXECUTE_CALCPROJ: true, - Permissions: { - Normal: 0, - Admin: 1, - }, - getHostname: function () { return os.hostname() }, diff --git a/server/tools/server_constants.js b/server/tools/server_constants.js index edfb928..d7195c2 100644 --- a/server/tools/server_constants.js +++ b/server/tools/server_constants.js @@ -5,6 +5,7 @@ module.exports = Object.freeze({ RIS_CODE_EMAIL_ALREADY_VERIFIED: -5, RIS_CODE_EMAIL_VERIFIED: 1, + RIS_CODE_ERR_UNAUTHORIZED: -30, RIS_CODE_LOGIN_ERR_GENERIC: -20, RIS_CODE_LOGIN_ERR: -10, RIS_CODE_OK: 1, diff --git a/server/tools/shared_nodejs.js b/server/tools/shared_nodejs.js index 23d6b77..a8cd066 100644 --- a/server/tools/shared_nodejs.js +++ b/server/tools/shared_nodejs.js @@ -1,7 +1,12 @@ module.exports = { + Permissions: { + Normal: 0, + Admin: 1, + }, + fieldsUserToChange() { - return ['username', 'email', 'name', 'surname', 'perm', 'date_reg'] + return ['username', 'email', 'name', 'surname', 'perm', 'date_reg', 'verified_email'] } };