This commit is contained in:
David Arranz 2019-07-21 15:30:49 +02:00
parent 0236c9b76e
commit 0e8b99b2db
9 changed files with 143 additions and 50 deletions

View File

@ -1,5 +1,6 @@
const _ = require('lodash'); const _ = require('lodash');
const passport = require('passport'); const passport = require('passport');
const crypto = require('crypto');
const { Strategy: LocalStrategy } = require('passport-local'); const { Strategy: LocalStrategy } = require('passport-local');
const { Strategy: CustomStrategy } = require('passport-custom'); const { Strategy: CustomStrategy } = require('passport-custom');
@ -40,11 +41,12 @@ const localEmailOptions = {
passport.use('local-email', new LocalStrategy(localEmailOptions, async (email, password, done) => { passport.use('local-email', new LocalStrategy(localEmailOptions, async (email, password, done) => {
try { try {
const user = await authService.extraMethods.findUser({ email }); const user = await authService.extraMethods.findUser({ email });
if (_.isNull(user)) { if (_.isNull(user)) {
return done(null, false, { message: 'User not found' }) return done(null, false, { message: 'User not found' })
} else { } 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) { if (!isPasswordValid) {
return done(null, false, { message: 'Wrong Password' }) return done(null, false, { message: 'Wrong Password' })
} else { } else {
@ -92,14 +94,19 @@ passport.use('local-phone', new LocalStrategy(localPhoneOptions, async (phone, f
// JWT // JWT
passport.use('jwt', new CustomStrategy(async (req, done) => { passport.use('jwt', new CustomStrategy(async (req, done) => {
const token = ((req && req.headers && req.headers['x-access-token']) ? req.headers['x-access-token'] : null); 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) { if (!token) {
return done(null, false, { message: 'Unauthorized'}); return done(null, false, { message: 'Unauthorized'});
} }
if (securityHelper.verify(token)) { if (securityHelper.verify(token, function (result, status) {
console.log('VERIFICAAAAAAAAAAAAAAAAAAAAAAAAADO'); console.log(result);
console.log(status);
if (result.messenger.success) {
req.user = result.data; //auth.decode(token);
} }
return done(null, securityHelper.verify(token)); next();
}));
})); }));

View File

@ -102,7 +102,8 @@ module.exports = {
}, },
isValidPassword: async (password, candidate) => { isValidPassword: async (password, candidate) => {
return await bCrypt.compareSync(candidate, password); result = await bCrypt.compareSync(candidate, password);
return result;
}, },
generateToken: (payload) => { generateToken: (payload) => {

View File

@ -162,14 +162,7 @@ const generateService = (model, extraMethods = {}, options = defaultOptions) =>
}, },
fetchOne: async (params, context) => { fetchOne: async (params, context) => {
console.log('fecccccc ONE');
console.log(params);
console.log(context);
const findOptions = parseParamsToFindOptions(params); const findOptions = parseParamsToFindOptions(params);
console.log('fecccccc ONE- findOptions');
console.log(findOptions);
const result = await model.scope(context.scopes).findOne(findOptions); const result = await model.scope(context.scopes).findOne(findOptions);
if (extraMethods.afterFetchOne) { if (extraMethods.afterFetchOne) {

View File

@ -86,9 +86,7 @@ module.exports = function (sequelize, DataTypes) {
// InventoryLevel.prototype.someMethod = function () {...} // InventoryLevel.prototype.someMethod = function () {...}
User.prototype.comparePassword = async function (candidatePassword) { User.prototype.comparePassword = async function (candidatePassword) {
const user = this; const user = this;
if (user.password) { if (user.password) {
return await isValidPassword(user.password, candidatePassword) return await isValidPassword(user.password, candidatePassword)
} else { } else {

View File

@ -111,12 +111,15 @@ const extraControllers = {
createInscription: async(req, res, next) => { createInscription: async(req, res, next) => {
const params = extractParamsFromRequest(req, res, {}); const params = extractParamsFromRequest(req, res, {});
console.log('usuariooooooooooooo');
console.log(req.user);
let dataUser = { let dataUser = {
id: null, id: null,
phone: '+34686621049', phone: '+34686333111',
name: 'aaaaaaaasdasdaaaaaa', name: 'aaaaaaaasdasdaaaaaa',
surname: 'bbbbbbb', surname: 'bbbbbbb',
email: 'lqdvi2@lqdvi.com', email: 'lqdvi333@lqdvi.com',
userResult: null, userResult: null,
} }
@ -128,6 +131,7 @@ const extraControllers = {
reservation: null, reservation: null,
inscription: 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 inscriptionsWithoutReservationCount: null, //nº total de inscritos sin reserva asignada
inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada inscriptionsWithReservationCount: null, //nº total de inscritos a la reserva asignada
type : (req.body.code) ? 'reserva' : 'libre', type : (req.body.code) ? 'reserva' : 'libre',
@ -188,9 +192,9 @@ const extraControllers = {
//Comprobamos que el usuario no tenga ya inscripcion para ese evento //Comprobamos que el usuario no tenga ya inscripcion para ese evento
dataInscription.inscription = await eventInscriptionService._getInscription(dataInscription.event.id, dataUser.userResult.user.id); dataInscription.inscription = await eventInscriptionService._getInscription(dataInscription.event.id, dataUser.userResult.user.id);
if (dataInscription.inscription) { 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); 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 //TENEMOS QUE CREAR INSCRIPCIÓN
else { else {
@ -202,27 +206,93 @@ const extraControllers = {
if (dataInscription.reservation) { if (dataInscription.reservation) {
dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id); dataInscription.inscriptionsWithReservationCount = await eventInscriptionService._getCountInscriptionsWithReservation(dataInscription.reservation.id);
++dataInscription.inscriptionsWithReservationCount; ++dataInscription.inscriptionsWithReservationCount;
//??????????????????????????????????????????????
//En la reserva lo tengo pero me fio mas del count reservation.confirmed++ ??????????????????????????????
//Actualizamos aforo y creamos inscripcion //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)) 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) dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id,
dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type,
dataInscription.validated,
source, dataInscription.reservation.id,
null)
else else
return handleResultResponse("No se ha podido actualizar el aforo de la reserva", null, params, res, httpStatus.NOT_FOUND); 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 //SIN CODIGO DE RESERVA SE MODIFICA EL CONFIRMED DEL EVENTO, YA QUE SE DESCONTARA DEL AFORO DEL EVENTO
else { else {
dataInscription.inscriptionsWithoutReservationCount = await eventInscriptionService._getCountInscriptionsWithoutReservation(dataInscription.event.id); dataInscription.inscriptionsWithoutReservationCount = await eventInscriptionService._getCountInscriptionsWithoutReservation(dataInscription.event.id);
++dataInscription.inscriptionsWithoutReservationCount; ++dataInscription.inscriptionsWithoutReservationCount;
//Actualizamos aforo y creamos inscripcion
//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)) 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) dataInscription.inscription = await eventInscriptionService._createInscription(dataInscription.event.id,
dataUser.userResult.user.id,
dataInscription.ticket,
dataInscription.type,
dataInscription.validated,
source,
null,
null)
else else
return handleResultResponse("No se ha podido actualizar el aforo del evento", null, params, res, httpStatus.NOT_FOUND); 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);
}
}
} }
} catch (error) { } catch (error) {

View File

@ -109,7 +109,7 @@ routes.get('/events/:id/inscriptions',
// Hacer una inscripción // Hacer una inscripción
routes.post('/events/:id/inscriptions', routes.post('/events/:id/inscriptions',
//isLoggedUser, isLoggedUser,
// SchemaValidator(eventValidation.InscriptionInputType, true), // SchemaValidator(eventValidation.InscriptionInputType, true),
eventController.createInscription eventController.createInscription
); );

View File

@ -25,12 +25,17 @@ module.exports = function (sequelize, DataTypes) {
type: DataTypes.STRING, type: DataTypes.STRING,
}, },
validated: { 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, type: DataTypes.UUID,
foreignKey: true, foreignKey: true,
} }
}, { }, {
tableName: 'events_inscriptions', tableName: 'events_inscriptions',
freezeTableName: true, freezeTableName: true,

View File

@ -2,6 +2,7 @@
'use strict'; 'use strict';
const _ = require('lodash'); const _ = require('lodash');
const moment = require('moment');
const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper'); const { generateService, parseParamsToFindOptions } = require('../../helpers/service.helper');
const models = require('../../core/models'); 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('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion'); console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>><<valores de la inscripcion');
console.log(eventId, userId, ticket, type, valid, source, reservationId); console.log(eventId, userId, ticket, type, validated, source, reservationId, overflowEventId);
return new Promise(function (resolve, reject) { return new Promise(function (resolve, reject) {
models.EventInscription.create({ models.EventInscription.create({
eventId: eventId, eventId: eventId,
date: moment().utc(),
userId: userId, userId: userId,
type: type, type: type,
source: source,
valid: valid,
// valid: !(tickets > assistants),
reservationId: reservationId,
code_ticket: ticket, code_ticket: ticket,
source: source,
validated: validated,
reservationId: reservationId,
overflowEventId: overflowEventId,
}) })
.then(function (result) { .then(function (result) {
resolve(result); resolve(result);

View File

@ -15,13 +15,30 @@
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; /*!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` -- Dumping data for table `event_types`
-- --
LOCK TABLES `event_types` WRITE; LOCK TABLES `event_types` WRITE;
/*!40000 ALTER TABLE `event_types` DISABLE KEYS */; /*!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 */; /*!40000 ALTER TABLE `event_types` ENABLE KEYS */;
UNLOCK TABLES; UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
@ -34,4 +51,4 @@ UNLOCK TABLES;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; /*!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