Esempio n. 1
0
        public virtual IActionResult CreateUser([FromBody] User user)
        {
            // TODO ftn: Add validation to the user parameter!!!
            // Return 400 - BadRequest if not valid!
            if (_context.Users.FirstOrDefault(u => u.Username == user.Username) != null)
            {
                return(StatusCode(StatusCodes.Status409Conflict, user)); // 409 already exists!
            }

            try
            {
                // QUICK DIRTY FIX AS SEED HAVE FIXED ID's so USER will get used one!:
                Random r    = new Random();
                int    rInt = r.Next(1, 1000000000);
                user.Id = rInt;
                // END OF QUICK DIRTY FIX.

                user.Password = _hasher.HashPassword(null, user.Password);
                // Ensure token is created:
                if (user.RefreshToken == null)
                {
                    user.RefreshToken = Guid.NewGuid();
                }
                _context.Users.Add(user);
                _context.SaveChanges();
                user.Password = null;
                return(Created(Request.Host.ToString(), user)); // 201 Created successfuly.
            }
            catch (Exception)
            {
                _logger.LogError(LoggingEvents.INSERT_ITEM, "CreateUser({user}) NOT ADDED", user);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Esempio n. 2
0
        public virtual IActionResult AddPurchaseCode([FromBody] PurchaseCode purchaseCode)
        {
            // TODO ftn: Add validation to the purchaseCode parameter!!!
            // Return 400 - BadRequest if not valid!
            if (_context.Codes.FirstOrDefault(c => c.Code == purchaseCode.Code) != null)
            {
                return(StatusCode(StatusCodes.Status409Conflict, purchaseCode)); // 409 already exists!
            }

            try
            {
                _context.Codes.Add(purchaseCode);
                _context.SaveChanges();
                return(Created(Request.Host.ToString(), purchaseCode)); // 201 Created successfuly.
            }
            catch (Exception)
            {
                _logger.LogError(LoggingEvents.INSERT_ITEM, "AddPurchaseCode({purchaseCode}) NOT ADDED", purchaseCode);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Esempio n. 3
0
        public virtual IActionResult AddTicketValidation([FromBody] TicketValidation ticketValidation)
        {
            // TODO ftn: Add validation to the ticketValidation parameter!!!
            // Return 400 - BadRequest if not valid!

            if (_context.Validations.FirstOrDefault(t => t.Id == ticketValidation.Id) != null)
            {
                return(StatusCode(StatusCodes.Status409Conflict)); // 409 already exists!
            }

            TicketPurchase ticket = _context.Purchases.FirstOrDefault(p => p.Code == ticketValidation.Ticket.Code);

            if (ticket == null)
            {
                return(StatusCode(StatusCodes.Status404NotFound));
            }

            if (ticket.EndDateTime < DateTime.Now)
            {
                return(StatusCode(StatusCodes.Status406NotAcceptable, ticket));
            }

            try
            {
                ticketValidation.Ticket             = ticket;
                ticketValidation.IsValid            = true;
                ticketValidation.ValidationDateTime = DateTime.Now.ToUniversalTime();

                Random r    = new Random();
                int    rInt = r.Next(1, 1000000000);
                ticketValidation.Id = rInt;

                _context.Validations.Add(ticketValidation);
                _context.Entry(ticketValidation.Controller).State = Microsoft.EntityFrameworkCore.EntityState.Unchanged;
                _context.SaveChanges();
                return(new ObjectResult(ticket));
                //return Created(Request.Host.ToString(), ticketValidation); // 201 Created successfuly.
            }
            catch (Exception)
            {
                _logger.LogError(LoggingEvents.INSERT_ITEM, "AddTicketType({ticketValidation}) NOT ADDED", ticketValidation);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Esempio n. 4
0
        public IActionResult AddTicketType([FromBody] TicketType ticketType)
        {
            // TODO ftn: Add validation to the ticketType parameter!!!
            // Return 400 - BadRequest if not valid!
            if (_context.Types.FirstOrDefault(t => t.Id == ticketType.Id) != null)
            {
                return(StatusCode(StatusCodes.Status409Conflict, ticketType)); // 409 already exists!
            }

            try
            {
                _context.Types.Add(ticketType);
                _context.SaveChanges();
                return(Created(Request.Host.ToString(), ticketType)); // 201 Created successfuly.
            }
            catch (Exception)
            {
                _logger.LogError(LoggingEvents.INSERT_ITEM, "AddTicketType({ticketType}) NOT ADDED", ticketType);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }
        }
Esempio n. 5
0
        public virtual async Task <IActionResult> AddTicketPurchase([FromBody] TicketPurchase ticketPurchase)
        {
            // TODO FTN: Add validation!
            var    loggedInUserId      = long.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value);
            var    buyerUsername       = User.FindFirst(ClaimTypes.Name).Value;
            var    buyerFirstName      = User.FindFirst(ClaimTypes.GivenName).Value;
            string deviceId            = null;
            bool   enableNotifications = true;

            var hasTypeAndUser = ticketPurchase != null &&
                                 ticketPurchase.TypeId != null &&
                                 ticketPurchase.TypeId > 0 &&
                                 ticketPurchase.UserId != null &&
                                 ticketPurchase.UserId > 0 &&
                                 ticketPurchase.NumberOfPassangers > 0;

            if (!hasTypeAndUser)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, ticketPurchase));
            }

            if (loggedInUserId != ticketPurchase.UserId)
            {
                return(StatusCode(StatusCodes.Status400BadRequest, ticketPurchase));
            }

            try
            {
                if (_context.Purchases.FirstOrDefault(p => p.Id == ticketPurchase.Id) != null)
                {
                    return(StatusCode(StatusCodes.Status409Conflict, ticketPurchase)); // 409 already exists!
                }

                deviceId            = Request.Headers["DeviceID"];
                enableNotifications = Request.Headers["Notifications"].Any() ? Request.Headers["Notifications"] != "false" : true;

                var type = _context.Types.First(t => t.Id == ticketPurchase.TypeId);
                var user = _context.Users.First(u => u.Id == ticketPurchase.UserId);

                if (user.Balance - type.Price * ticketPurchase.NumberOfPassangers < 0.0d)
                {
                    return(StatusCode(StatusCodes.Status402PaymentRequired, ticketPurchase));
                }

                ticketPurchase.Code          = Guid.NewGuid();
                ticketPurchase.StartDateTime = DateTime.Now.ToUniversalTime().AddMinutes(_configuration.GetSection(Startup.AppSettingsConfigurationSectionKey).GetValue <int>(Startup.AppSettingsMinutesUntilTicketStartKey));
                ticketPurchase.EndDateTime   = DateTime.Now.ToUniversalTime().AddMinutes(type.Duration.Value * 60 + _configuration.GetSection(Startup.AppSettingsConfigurationSectionKey).GetValue <int>(Startup.AppSettingsMinutesUntilTicketStartKey));
                ticketPurchase.Price         = type.Price;
                user.Balance = user.Balance - type.Price * ticketPurchase.NumberOfPassangers;

                _context.Purchases.Add(ticketPurchase);
                _context.SaveChanges();

                ticketPurchase = _context.Purchases.Include(u => u.User).First(p => p.Id == ticketPurchase.Id);
            }
            catch (Exception)
            {
                _logger.LogError(LoggingEvents.INSERT_ITEM, "AddTicketPurchase({ticketPurchase}) NOT ADDED", ticketPurchase);
                return(StatusCode(StatusCodes.Status500InternalServerError));
            }

            string notificationSent = "[ALL: False1 ; Device ID: False2]";

            if (_newBuyerIsBIGNews)
            {
                var notification = new Notification()
                {
                    Title   = "We have a new ticket buyer!",
                    Message = $"User: {buyerUsername} have bought a ticket of type id: '{ticketPurchase.TypeId}'! YEEEAAAH!",
                    Topic   = "news"
                };

                var result = await _notificationService.Send(notification);

                notificationSent = notificationSent.Replace("False1", result.ToString());
            }

            if (!string.IsNullOrEmpty(deviceId) && enableNotifications)
            {
                var notification = new Notification()
                {
                    Title    = "Your have bought a ticket. Congrats!",
                    Message  = $"Hello {buyerFirstName}. Your ticket '{ticketPurchase.Code}' is ready!",
                    DeviceID = deviceId
                };

                var result = await _notificationService.Send(notification);

                notificationSent = notificationSent.Replace("False2", result.ToString());
            }

            Response.Headers.Add("DeviceID", deviceId);
            Response.Headers.Add("Notifications", enableNotifications.ToString());
            Response.Headers.Add("NotificationSent", notificationSent.ToString());
            return(StatusCode(StatusCodes.Status201Created, ticketPurchase));
        }