diff --git a/back/methods/vn-user/sign-in.js b/back/methods/vn-user/sign-in.js index 9c2d568f4..782046641 100644 --- a/back/methods/vn-user/sign-in.js +++ b/back/methods/vn-user/sign-in.js @@ -49,13 +49,7 @@ module.exports = Self => { if (vnUser.twoFactor) throw new ForbiddenError(null, 'REQUIRES_2FA'); } - const validateLogin = await Self.validateLogin(user, password); - await Self.app.models.SignInLog.create({ - token: validateLogin.token, - userFk: vnUser.id, - ip: ctx.req.ip - }); - return validateLogin; + return Self.validateLogin(user, password, ctx); }; Self.passExpired = async vnUser => { diff --git a/back/methods/vn-user/specs/sign-in.spec.js b/back/methods/vn-user/specs/sign-in.spec.js index ac2dfe2b2..1c4b4af51 100644 --- a/back/methods/vn-user/specs/sign-in.spec.js +++ b/back/methods/vn-user/specs/sign-in.spec.js @@ -2,7 +2,7 @@ const {models} = require('vn-loopback/server/server'); describe('VnUser Sign-in()', () => { const employeeId = 1; - const unauthCtx = { + const unAuthCtx = { req: { headers: {}, connection: { @@ -15,20 +15,21 @@ describe('VnUser Sign-in()', () => { const {VnUser, AccessToken, SignInLog} = models; describe('when credentials are correct', () => { it('should return the token if user uses email', async() => { - let login = await VnUser.signIn(unauthCtx, 'salesAssistant@mydomain.com', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'salesAssistant@mydomain.com', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; let signInLog = await SignInLog.find({where: {token: accessToken.id}}); expect(signInLog.length).toEqual(1); expect(signInLog[0].userFk).toEqual(accessToken.userId); + expect(signInLog[0].owner).toEqual(true); expect(login.token).toBeDefined(); await VnUser.logout(ctx.req.accessToken.id); }); it('should return the token', async() => { - let login = await VnUser.signIn(unauthCtx, 'salesAssistant', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'salesAssistant', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; @@ -38,7 +39,7 @@ describe('VnUser Sign-in()', () => { }); it('should return the token if the user doesnt exist but the client does', async() => { - let login = await VnUser.signIn(unauthCtx, 'PetterParker', 'nightmare'); + let login = await VnUser.signIn(unAuthCtx, 'PetterParker', 'nightmare'); let accessToken = await AccessToken.findById(login.token); let ctx = {req: {accessToken: accessToken}}; @@ -53,7 +54,7 @@ describe('VnUser Sign-in()', () => { let error; try { - await VnUser.signIn(unauthCtx, 'IDontExist', 'TotallyWrongPassword'); + await VnUser.signIn(unAuthCtx, 'IDontExist', 'TotallyWrongPassword'); } catch (e) { error = e; } @@ -74,7 +75,7 @@ describe('VnUser Sign-in()', () => { const options = {transaction: tx}; await employee.updateAttribute('twoFactor', 'email', options); - await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options); + await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options); await tx.rollback(); } catch (e) { await tx.rollback(); @@ -99,7 +100,7 @@ describe('VnUser Sign-in()', () => { const options = {transaction: tx}; await employee.updateAttribute('passExpired', yesterday, options); - await VnUser.signIn(unauthCtx, 'employee', 'nightmare', options); + await VnUser.signIn(unAuthCtx, 'employee', 'nightmare', options); await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/back/models/vn-user.js b/back/models/vn-user.js index 719e96cbf..e14cd30ea 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -124,20 +124,42 @@ module.exports = function(Self) { return email.send(); }); - Self.signInValidate = (user, userToken) => { + + /** + * Sign-in validate + * @param {String} user The user + * @param {Object} userToken Options + * @param {Object} token accessToken + * @param {Object} ctx context + */ + Self.signInValidate = async(user, userToken, token, ctx) => { const [[key, value]] = Object.entries(Self.userUses(user)); - if (userToken[key].toLowerCase().trim() !== value.toLowerCase().trim()) { - console.error('ERROR!!! - Signin with other user', userToken, user); + const isOwner = Self.rawSql(`SELECT ? = ? `, [userToken[key], value]); + await Self.app.models.SignInLog.create({ + userName: user, + token: token.id, + userFk: userToken.id, + ip: ctx.req.ip, + owner: isOwner + }); + if (!isOwner) throw new UserError('Try again'); - } }; - Self.validateLogin = async function(user, password) { + /** + * Validate login params + * @param {String} user The user + * @param {String} password + * @param {Object} ctx context + */ + Self.validateLogin = async function(user, password, ctx) { const loginInfo = Object.assign({password}, Self.userUses(user)); const token = await Self.login(loginInfo, 'user'); const userToken = await token.user.get(); - Self.signInValidate(user, userToken); + + if (ctx) + await Self.signInValidate(user, userToken, token, ctx); try { await Self.app.models.Account.sync(userToken.name, password); @@ -187,8 +209,8 @@ module.exports = function(Self) { }; Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls = - Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls - .filter(acl => acl.property != 'changePassword'); + Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls + .filter(acl => acl.property != 'changePassword'); Self.userSecurity = async(ctx, userId, options) => { const models = Self.app.models; @@ -226,10 +248,12 @@ module.exports = function(Self) { const env = process.env.NODE_ENV; const liliumUrl = await Self.app.models.Url.findOne({ - where: {and: [ - {appName: 'lilium'}, - {environment: env} - ]} + where: { + and: [ + {appName: 'lilium'}, + {environment: env} + ] + } }); class Mailer { diff --git a/db/changes/234604/00-createSignInLogTable.sql b/db/changes/234802/00-createSignInLogTable.sql similarity index 91% rename from db/changes/234604/00-createSignInLogTable.sql rename to db/changes/234802/00-createSignInLogTable.sql index 525348135..942f651c9 100644 --- a/db/changes/234604/00-createSignInLogTable.sql +++ b/db/changes/234802/00-createSignInLogTable.sql @@ -1,5 +1,4 @@ - -- -- Table structure for table `signInLog` -- Description: log to debug cross-login error @@ -13,7 +12,9 @@ CREATE TABLE `account`.`signInLog` ( `token` varchar(255) NOT NULL , `userFk` int(10) unsigned DEFAULT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), + `userName` varchar(30) NOT NULL, `ip` varchar(100) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci NOT NULL, + `owner` tinyint(1) DEFAULT 1, KEY `userFk` (`userFk`), CONSTRAINT `signInLog_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index d9eed401e..32c7eef8c 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2347,9 +2347,11 @@ INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `weekDays`) (8, 'indefinitely', 'mon,tue,wed,thu,fri,sat,sun'), (10, 'indefinitely', 'mon,tue,wed,thu,fri,sat,sun'); -INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `started`, `ended`) +INSERT INTO `vn`.`zoneEvent`(`zoneFk`, `type`, `started`, `ended`, `weekDays`) VALUES - (9, 'range', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 YEAR), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 YEAR)); + (9, 'range', DATE_ADD(util.VN_CURDATE(), INTERVAL -1 YEAR), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 YEAR), 'mon'), + (9, 'range', util.VN_CURDATE(), NULL, 'tue'), + (9, 'range', NULL, util.VN_CURDATE(), 'wed'); INSERT INTO `vn`.`workerTimeControl`(`userFk`, `timed`, `manual`, `direction`, `isSendMail`) VALUES diff --git a/modules/account/back/models/sign_in-log.json b/modules/account/back/models/sign_in-log.json index c5c014e60..8656e92dc 100644 --- a/modules/account/back/models/sign_in-log.json +++ b/modules/account/back/models/sign_in-log.json @@ -25,7 +25,15 @@ "type": "number" }, "ip": { - "type": "string" + "type": "string" + }, + "userName": { + "type": "string" + }, + "owner": { + "type": "boolean", + "required": true, + "default": true } }, "relations": { diff --git a/modules/route/back/methods/route/getExternalCmrs.js b/modules/route/back/methods/route/getExternalCmrs.js index 4750e53a1..3fc9798b0 100644 --- a/modules/route/back/methods/route/getExternalCmrs.js +++ b/modules/route/back/methods/route/getExternalCmrs.js @@ -3,99 +3,101 @@ const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; module.exports = Self => { - Self.remoteMethod('getExternalCmrs', { - description: 'Returns an array of external cmrs', - accessType: 'READ', - accepts: [ - { - arg: 'filter', - type: 'object', - description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', - }, - { - arg: 'cmrFk', - type: 'integer', - description: 'Searchs the route by id', - }, - { - arg: 'ticketFk', - type: 'integer', - description: 'The worker id', - }, - { - arg: 'routeFk', - type: 'integer', - description: 'The route id', - }, - { - arg: 'country', - type: 'string', - description: 'The agencyMode id', - }, - { - arg: 'clientFk', - type: 'integer', - description: 'The vehicle id', - }, - { - arg: 'hasCmrDms', - type: 'boolean', - description: 'The vehicle id', - }, - { - arg: 'shipped', - type: 'date', - description: 'The to date filter', - }, - ], - returns: { - type: ['object'], - root: true - }, - http: { - path: `/getExternalCmrs`, - verb: 'GET' - } - }); + Self.remoteMethod('getExternalCmrs', { + description: 'Returns an array of external cmrs', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + }, + { + arg: 'cmrFk', + type: 'integer', + description: 'Searchs the route by id', + }, + { + arg: 'ticketFk', + type: 'integer', + description: 'The worker id', + }, + { + arg: 'routeFk', + type: 'integer', + description: 'The route id', + }, + { + arg: 'country', + type: 'string', + description: 'The agencyMode id', + }, + { + arg: 'clientFk', + type: 'integer', + description: 'The vehicle id', + }, + { + arg: 'hasCmrDms', + type: 'boolean', + description: 'The vehicle id', + }, + { + arg: 'shipped', + type: 'date', + description: 'The to date filter', + }, + ], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/getExternalCmrs`, + verb: 'GET' + } + }); - Self.getExternalCmrs = async( - filter, - cmrFk, - ticketFk, - routeFk, - country, - clientFk, - hasCmrDms, - shipped, - options - ) => { - const params = { - cmrFk, - ticketFk, - routeFk, - country, - clientFk, - hasCmrDms, - shipped, - }; - const conn = Self.dataSource.connector; + Self.getExternalCmrs = async( + filter, + cmrFk, + ticketFk, + routeFk, + country, + clientFk, + hasCmrDms, + shipped, + options + ) => { + const params = { + cmrFk, + ticketFk, + routeFk, + country, + clientFk, + hasCmrDms, + shipped, + }; + const conn = Self.dataSource.connector; - let where = buildFilter(params, (param, value) => {return {[param]: value}}); - filter = mergeFilters(filter, {where}); + let where = buildFilter(params, (param, value) => { + return {[param]: value}; + }); + filter = mergeFilters(filter, {where}); - if (!filter.where) { - const yesterday = new Date(); - yesterday.setDate(yesterday.getDate() - 1); - filter.where = {'shipped': yesterday.toISOString().split('T')[0]} - } + if (!filter.where) { + const yesterday = new Date(); + yesterday.setDate(yesterday.getDate() - 1); + filter.where = {'shipped': yesterday.toISOString().split('T')[0]}; + } - const myOptions = {}; + const myOptions = {}; - if (typeof options == 'object') - Object.assign(myOptions, options); + if (typeof options == 'object') + Object.assign(myOptions, options); - let stmts = []; - const stmt = new ParameterizedSQL(` + let stmts = []; + const stmt = new ParameterizedSQL(` SELECT * FROM ( SELECT t.cmrFk, @@ -129,13 +131,13 @@ module.exports = Self => { AND dm.code = 'DELIVERY' AND t.cmrFk ) sub - `); + `); - stmt.merge(conn.makeSuffix(filter)); - const itemsIndex = stmts.push(stmt) - 1; + stmt.merge(conn.makeSuffix(filter)); + const itemsIndex = stmts.push(stmt) - 1; - const sql = ParameterizedSQL.join(stmts, ';'); - const result = await conn.executeStmt(sql); - return itemsIndex === 0 ? result : result[itemsIndex]; - }; + const sql = ParameterizedSQL.join(stmts, ';'); + const result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; }; diff --git a/modules/zone/back/methods/zone/getEventsFiltered.js b/modules/zone/back/methods/zone/getEventsFiltered.js index b7875785d..85db76a58 100644 --- a/modules/zone/back/methods/zone/getEventsFiltered.js +++ b/modules/zone/back/methods/zone/getEventsFiltered.js @@ -35,44 +35,39 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - query = ` - SELECT * - FROM vn.zoneEvent - WHERE zoneFk = ? - AND ((type = 'indefinitely') - OR (type = 'day' AND dated BETWEEN ? AND ?) - OR (type = 'range' - AND ( - (started BETWEEN ? AND ?) - OR - (ended BETWEEN ? AND ?) - OR - (started <= ? AND ended >= ?) - ) - ) - ) - ORDER BY type='indefinitely' DESC, type='range' DESC, type='day' DESC;`; - const events = await Self.rawSql(query, - [zoneFk, started, ended, started, ended, started, ended, started, ended], myOptions); + ended = simpleDate(ended); + started = simpleDate(started); query = ` - SELECT e.* - FROM vn.zoneExclusion e - LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id - WHERE e.zoneFk = ? - AND e.dated BETWEEN ? AND ? - AND eg.zoneExclusionFk IS NULL;`; + SELECT * + FROM vn.zoneEvent + WHERE zoneFk = ? + AND (IFNULL(started, ?) <= ? AND IFNULL(ended,?) >= ?) + ORDER BY type='indefinitely' DESC, type='range' DESC, type='day' DESC;`; + const events = await Self.rawSql(query, + [zoneFk, started, ended, ended, started], myOptions); + + query = ` + SELECT e.* + FROM vn.zoneExclusion e + LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id + WHERE e.zoneFk = ? + AND e.dated BETWEEN ? AND ? + AND eg.zoneExclusionFk IS NULL;`; const exclusions = await Self.rawSql(query, [zoneFk, started, ended], myOptions); query = ` - SELECT eg.*, e.zoneFk, e.dated, e.created, e.userFk - FROM vn.zoneExclusion e - LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id - WHERE e.zoneFk = ? - AND e.dated BETWEEN ? AND ? - AND eg.zoneExclusionFk IS NOT NULL;`; + SELECT eg.*, e.zoneFk, e.dated, e.created, e.userFk + FROM vn.zoneExclusion e + LEFT JOIN vn.zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id + WHERE e.zoneFk = ? + AND e.dated BETWEEN ? AND ? + AND eg.zoneExclusionFk IS NOT NULL;`; const geoExclusions = await Self.rawSql(query, [zoneFk, started, ended], myOptions); return {events, exclusions, geoExclusions}; }; + function simpleDate(date) { + return date.toISOString().split('T')[0]; + } }; diff --git a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js index 6fd6bb994..7167b83de 100644 --- a/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js +++ b/modules/zone/back/methods/zone/specs/getEventsFiltered.spec.js @@ -30,7 +30,7 @@ describe('zone getEventsFiltered()', () => { const result = await models.Zone.getEventsFiltered(9, today, today, options); - expect(result.events.length).toEqual(1); + expect(result.events.length).toEqual(3); expect(result.exclusions.length).toEqual(0); await tx.rollback(); @@ -47,11 +47,12 @@ describe('zone getEventsFiltered()', () => { const options = {transaction: tx}; const date = Date.vnNew(); date.setFullYear(date.getFullYear() - 2); - const dateTomorrow = new Date(date.setDate(date.getDate() + 1)); + const dateTomorrow = new Date(date); + dateTomorrow.setDate(dateTomorrow.getDate() + 1); const result = await models.Zone.getEventsFiltered(9, date, dateTomorrow, options); - expect(result.events.length).toEqual(0); + expect(result.events.length).toEqual(1); expect(result.exclusions.length).toEqual(0); await tx.rollback();