From 0e8b99b2dbe22b45d28986547b572699a0ea1239 Mon Sep 17 00:00:00 2001 From: david Date: Sun, 21 Jul 2019 15:30:49 +0200 Subject: [PATCH] a --- core/passport.js | 21 ++-- helpers/security.helper.js | 3 +- helpers/service.helper.js | 7 -- modules/auth/user.model.js | 2 - modules/events/event.controller.js | 116 ++++++++++++++---- modules/events/event.routes.js | 2 +- modules/events/events_inscriptions.model.js | 9 +- modules/events/events_inscriptions.service.js | 12 +- script-carga-bd-event_types.sql | 21 +++- 9 files changed, 143 insertions(+), 50 deletions(-) diff --git a/core/passport.js b/core/passport.js index 07ed779..2e85be1 100644 --- a/core/passport.js +++ b/core/passport.js @@ -1,5 +1,6 @@ const _ = require('lodash'); const passport = require('passport'); +const crypto = require('crypto'); const { Strategy: LocalStrategy } = require('passport-local'); const { Strategy: CustomStrategy } = require('passport-custom'); @@ -40,11 +41,12 @@ const localEmailOptions = { passport.use('local-email', new LocalStrategy(localEmailOptions, async (email, password, done) => { try { const user = await authService.extraMethods.findUser({ email }); + if (_.isNull(user)) { return done(null, false, { message: 'User not found' }) } else { - const isPasswordValid = await user.comparePassword(password); - + var password_encoded = crypto.createHash('sha512').update(password).digest('hex'); + const isPasswordValid = await user.comparePassword(password_encoded); if (!isPasswordValid) { return done(null, false, { message: 'Wrong Password' }) } else { @@ -92,14 +94,19 @@ passport.use('local-phone', new LocalStrategy(localPhoneOptions, async (phone, f // JWT passport.use('jwt', new CustomStrategy(async (req, done) => { const token = ((req && req.headers && req.headers['x-access-token']) ? req.headers['x-access-token'] : null); - console.log(req.headers); + console.log(token); if (!token) { return done(null, false, { message: 'Unauthorized'}); } - if (securityHelper.verify(token)) { -console.log('VERIFICAAAAAAAAAAAAAAAAAAAAAAAAADO'); - } - return done(null, securityHelper.verify(token)); + if (securityHelper.verify(token, function (result, status) { + console.log(result); + console.log(status); + if (result.messenger.success) { + req.user = result.data; //auth.decode(token); + } + next(); + })); + })); diff --git a/helpers/security.helper.js b/helpers/security.helper.js index f5fda87..c2dfda6 100644 --- a/helpers/security.helper.js +++ b/helpers/security.helper.js @@ -102,7 +102,8 @@ module.exports = { }, isValidPassword: async (password, candidate) => { - return await bCrypt.compareSync(candidate, password); + result = await bCrypt.compareSync(candidate, password); + return result; }, generateToken: (payload) => { diff --git a/helpers/service.helper.js b/helpers/service.helper.js index 1c97152..acd0eae 100644 --- a/helpers/service.helper.js +++ b/helpers/service.helper.js @@ -162,14 +162,7 @@ const generateService = (model, extraMethods = {}, options = defaultOptions) => }, fetchOne: async (params, context) => { -console.log('fecccccc ONE'); -console.log(params); -console.log(context); - const findOptions = parseParamsToFindOptions(params); - console.log('fecccccc ONE- findOptions'); - console.log(findOptions); - const result = await model.scope(context.scopes).findOne(findOptions); if (extraMethods.afterFetchOne) { diff --git a/modules/auth/user.model.js b/modules/auth/user.model.js index 64e4090..7fa5790 100644 --- a/modules/auth/user.model.js +++ b/modules/auth/user.model.js @@ -86,9 +86,7 @@ module.exports = function (sequelize, DataTypes) { // InventoryLevel.prototype.someMethod = function () {...} User.prototype.comparePassword = async function (candidatePassword) { - const user = this; - if (user.password) { return await isValidPassword(user.password, candidatePassword) } else { diff --git a/modules/events/event.controller.js b/modules/events/event.controller.js index 095ba13..8208bfd 100644 --- a/modules/events/event.controller.js +++ b/modules/events/event.controller.js @@ -111,12 +111,15 @@ const extraControllers = { createInscription: async(req, res, next) => { const params = extractParamsFromRequest(req, res, {}); + console.log('usuariooooooooooooo'); + console.log(req.user); + let dataUser = { id: null, - phone: '+34686621049', + phone: '+34686333111', name: 'aaaaaaaasdasdaaaaaa', surname: 'bbbbbbb', - email: 'lqdvi2@lqdvi.com', + email: 'lqdvi333@lqdvi.com', userResult: null, } @@ -124,10 +127,11 @@ const extraControllers = { eventId: params.params.id, encodedReservationCode: req.body.code, reservationCode: req.body.code, //Buffer.from(req.body.code, 'base64').toString('ascii'); - event : null, - reservation : null, + event: null, + reservation: null, inscription: null, - ticket : null, //nº total de inscritos (libres + con reserva) - Para ticket - entrada + ticket: null, //nº total de inscritos (libres + con reserva) - Para ticket - entrada + validated: null, //si no esta validado la inscripción es a la lista de espera inscriptionsWithoutReservationCount: null, //nº total de inscritos sin reserva asignada inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada type : (req.body.code) ? 'reserva' : 'libre', @@ -188,9 +192,9 @@ const extraControllers = { //Comprobamos que el usuario no tenga ya inscripcion para ese evento dataInscription.inscription = await eventInscriptionService._getInscription(dataInscription.event.id, dataUser.userResult.user.id); if (dataInscription.inscription) { - console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>inscription existe, revisar si es con codigo vip y cambiarlo'); + console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>inscription existe, revisar si es con codigo vip y cambiarlo, su inscripcion se ha cambiado a vip'); console.log(dataInscription.inscription); - return handleResultResponse(result, null, params, res, (result === null) ? httpStatus.NOT_FOUND : httpStatus.OK); + return handleResultResponse(dataInscription.inscription, null, params, res, httpStatus.OK); } //TENEMOS QUE CREAR INSCRIPCIÓN else { @@ -202,26 +206,92 @@ const extraControllers = { if (dataInscription.reservation) { dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id); ++dataInscription.inscriptionsWithReservationCount; -//?????????????????????????????????????????????? - //En la reserva lo tengo pero me fio mas del count reservation.confirmed++ ?????????????????????????????? - - //Actualizamos aforo y creamos inscripcion - if (await eventReservationService._updateReservationEvent(dataInscription.reservation.id, dataInscription.inscriptionsWithReservationCount)) - dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, dataUser.userResult.user.id, dataInscription.ticket, dataInscription.type, true, source, null) - else - return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND); - } - //SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO + //COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DE LA RESERVA + if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) { + dataInscription.validated = true; + + //Actualizamos aforo de la lista de espera de la reserva y creamos inscripcion en la lista de espera de la reserva + if (await eventReservationService._updateReservationEvent(dataInscription.reservation.id, dataInscription.inscriptionsWithReservationCount)) + dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, + dataUser.userResult.user.id, + dataInscription.ticket, + dataInscription.type, + dataInscription.validated, + source, dataInscription.reservation.id, + null) + else + return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND); + } + //LISTA DE ESPERA DE LA RESERVA + else { + if (dataInscription.reservation.allow_overflow === true) { + dataInscription.validated = false; + dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.overflow_event_reservationId); + ++dataInscription.inscriptionsWithReservationCount; + +// if (dataInscription.reservation.assistants >= dataInscription.inscriptionsWithReservationCount) { + //Actualizamos aforo de la reserva y creamos inscripcion + if (await eventReservationService._updateReservationEvent(dataInscription.reservation.overflow_event_reservationId, dataInscription.inscriptionsWithReservationCount)) + dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, + dataUser.userResult.user.id, + dataInscription.ticket, + dataInscription.type, + dataInscription.validated, + source, + dataInscription.reservation.overflow_event_reservationId, + null) + else + return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND); + } + else + return handleResultResponse("Aforo completo de la reserva y no hay lista de espera", null, params, res, httpStatus.NOT_FOUND); + } + } + //SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO else { dataInscription.inscriptionsWithoutReservationCount = await eventInscriptionService._getCountInscriptionsWithoutReservation(dataInscription.event.id); ++dataInscription.inscriptionsWithoutReservationCount; - - //Actualizamos aforo y creamos inscripcion - if (await eventService._updateConfirmedEvent(dataInscription.event.id, dataInscription.inscriptionsWithoutReservationCount)) - dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, dataUser.userResult.user.id, dataInscription.ticket, dataInscription.type, true, source, null) - else - return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND); + + + //COMPROBAMOS SI ES VALIDO O HAY QUE APUNTARLE A LA LISTA DE ESPERA DEL EVENTO + if (dataInscription.event.assistants >= dataInscription.inscriptionsWithoutReservationCount) { + dataInscription.validated = true; + //Actualizamos aforo del evento y creamos inscripcion + if (await eventService._updateConfirmedEvent(dataInscription.event.id, dataInscription.inscriptionsWithoutReservationCount)) + dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id, + dataUser.userResult.user.id, + dataInscription.ticket, + dataInscription.type, + dataInscription.validated, + source, + null, + null) + else + return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND); + } + //LISTA DE ESPERA DE LA RESERVA + else { + if (dataInscription.event.allow_overflow === true) { + dataInscription.validated = false; + + //Actualizamos aforo de la lista de espera del evento y creamos inscripcion + if (await eventService._updateConfirmedEvent(dataInscription.event.overflow_eventId, dataInscription.inscriptionsWithoutReservationCount)) + dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.overflow_eventId, + dataUser.userResult.user.id, + dataInscription.ticket, + dataInscription.type, + dataInscription.validated, + source, + null, + dataInscription.overflow_eventId) + else + return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND); + } + else + return handleResultResponse("Aforo completo y no hay lista de espera", null, params, res, httpStatus.NOT_FOUND); + } + } } diff --git a/modules/events/event.routes.js b/modules/events/event.routes.js index d3171db..b3eeb44 100644 --- a/modules/events/event.routes.js +++ b/modules/events/event.routes.js @@ -109,7 +109,7 @@ routes.get('/events/:id/inscriptions', // Hacer una inscripción routes.post('/events/:id/inscriptions', - //isLoggedUser, + isLoggedUser, // SchemaValidator(eventValidation.InscriptionInputType, true), eventController.createInscription ); diff --git a/modules/events/events_inscriptions.model.js b/modules/events/events_inscriptions.model.js index ef37086..71f2d26 100644 --- a/modules/events/events_inscriptions.model.js +++ b/modules/events/events_inscriptions.model.js @@ -25,12 +25,17 @@ module.exports = function (sequelize, DataTypes) { type: DataTypes.STRING, }, validated: { - type: DataTypes.DATE, + type: DataTypes.BOOLEAN, }, - reservationId:{ + reservationId:{ //contendra el id de la reserva o de la lista de espera de la reserva + type: DataTypes.UUID, + foreignKey: true, + }, + overflowEventId: { //contendra el id del evento de lista de espera del evento type: DataTypes.UUID, foreignKey: true, } + }, { tableName: 'events_inscriptions', freezeTableName: true, diff --git a/modules/events/events_inscriptions.service.js b/modules/events/events_inscriptions.service.js index fc7cd6e..231ec4c 100644 --- a/modules/events/events_inscriptions.service.js +++ b/modules/events/events_inscriptions.service.js @@ -2,6 +2,7 @@ 'use strict'; const _ = require('lodash'); +const moment = require('moment'); const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const models = require('../../core/models'); @@ -44,20 +45,21 @@ const extraMethods = { }) }, - _createInscription: (eventId, userId, ticket, type, valid, source, reservationId) => { + _createInscription: (eventId, userId, ticket, type, validated, source, reservationId, overflowEventId) => { console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>< assistants), + validated: validated, reservationId: reservationId, - code_ticket: ticket, + overflowEventId: overflowEventId, }) .then(function (result) { resolve(result); diff --git a/script-carga-bd-event_types.sql b/script-carga-bd-event_types.sql index a3e145d..d532622 100644 --- a/script-carga-bd-event_types.sql +++ b/script-carga-bd-event_types.sql @@ -15,13 +15,30 @@ /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; +-- +-- Table structure for table `event_types` +-- + +DROP TABLE IF EXISTS `event_types`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `event_types` ( + `id` char(36) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL, + `name` varchar(255) DEFAULT NULL, + `title` varchar(255) DEFAULT NULL, + `createdAt` datetime NOT NULL, + `updatedAt` datetime NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Dumping data for table `event_types` -- LOCK TABLES `event_types` WRITE; /*!40000 ALTER TABLE `event_types` DISABLE KEYS */; -INSERT INTO `event_types` VALUES ('0','conference','Congreso LQDVI','2019-06-21 12:22:00','2019-06-21 12:22:00'),('1','kliquers','Congreso Kliquers','2019-06-21 12:22:00','2019-06-21 12:22:00'); +INSERT INTO `event_types` VALUES ('0','conference','Congreso LQDVI','2019-06-21 12:22:00','2019-06-21 12:22:00'),('1','kliquers','Congreso Kliquers','2019-06-21 12:22:00','2019-06-21 12:22:00'),('2','lista de espera','Lista de espera de un evento','2019-06-21 12:22:00','2019-06-21 12:22:00'); /*!40000 ALTER TABLE `event_types` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -34,4 +51,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-07-02 10:46:37 +-- Dump completed on 2019-07-21 12:21:42