public IActionResult SendMessage([Bind("Email", "Name", "PhoneNumber", "Message")] ContactMessageViewModel model)
        {
            if (ModelState.IsValid)
            {
                MailMessage message = new MailMessage("*****@*****.**", "*****@*****.**");
                message.Subject = string.Format("Message From {0}", model.Name);
                message.Body    = string.Format("Email: {0}\n", model.Email);
                message.Body   += string.Format("Phone: {0}\n\n", model.PhoneNumber);
                message.Body   += string.Format("Message: {0}\n", model.Message);
                EmailController.SendEmail(message);

                TempData["SuccessMessage"] = "We have received your message!";
                return(RedirectToAction("Index", "Home"));
            }

            return(View("Index", model));
        }
        public async Task <IActionResult> ForgotPassword([Bind("Email")] ForgotPasswordViewModel model)
        {
            ErrorMessage errorMsg = new ErrorMessage();

            errorMsg.IsSuccess = false;

            if (ModelState.IsValid)
            {
                var user = await _UserManager.FindByEmailAsync(model.Email);

                if (user != null)
                {
                    var token = await _UserManager.GeneratePasswordResetTokenAsync(user);

                    var passwordResetLink =
                        Url.Action("ResetPassword", "Account", new { Email = model.Email, Token = token }, Request.Scheme);

                    try {
                        //SENDING EMAIL (REENABLE THIS LATER)
                        MailMessage message = new MailMessage("*****@*****.**", model.Email);
                        message.Subject = "Password Reset Link";
                        message.Body    = "Hi we got your back, Click here to reset your account: \n" + passwordResetLink;
                        EmailController.SendEmail(message);
                    } catch
                    {
                        errorMsg.Message.Add("Failure in sending Email confirmation, Please try again.");
                    }
                }

                //i place it here so that people cant use this reset password for checking whether the email exist or not
                //prevent bruteforcing
                errorMsg.IsSuccess = true;
                errorMsg.Message.Add($"Email to reset your password has been sent to {model.Email}");
                return(Json(errorMsg));
            }

            var allErrors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage));

            foreach (string error in allErrors)
            {
                errorMsg.Message.Add($"{error}");
            }
            return(Json(errorMsg));
        }
Ejemplo n.º 3
0
        public async Task <IActionResult> SubmitOrder([Bind("OrderID,DeliveryOptions,FirstName,LastName,DeliveryEmail," +
                                                            "PhoneNumber,DeliveryAddress,Suburb,ZipCode,Unit,NameOnCard,CreditCardNumber,ExpiryMonth,ExpiryYear,CVV")] OrderViewModel model)
        {
            ErrorMessage errorMsg = new ErrorMessage();

            errorMsg.IsSuccess = false;
            bool            isAnonymous = true;
            ApplicationUser user        = null;

            //NOT GONNA HANDLE CARD EXCEPT CHECKING LENGTH
            if (model.CreditCardNumber != null && model.CreditCardNumber.Length != 19)
            {
                ModelState.AddModelError("", "Invalid Card Number");
            }

            if (_SignInManager.IsSignedIn(User))
            {
                user = await _UserManager.GetUserAsync(User);

                isAnonymous = false;
            }
            else
            {
                string cookie = Request.Cookies["homeSquareCookieID"];
                if (cookie != null)
                {
                    user = await _UserManager.FindByNameAsync(cookie);

                    isAnonymous = true;
                }
                else
                {
                    errorMsg.Message.Add("Unable to Locate User");
                    return(Json(errorMsg));
                }
            }

            if (ModelState.IsValid)
            {
                //SENDING EMAIL(REENABLE THIS LATER)
                try
                {
                    MailMessage message = new MailMessage("*****@*****.**", model.DeliveryEmail);
                    message.Subject = "Order Confirmation";
                    message.Body    = "Thank you for your purchase, Here is your order URL: \n" +
                                      Url.Action("Success", "Checkout", new { userID = user.Id, orderID = model.OrderID }, Request.Scheme);
                    EmailController.SendEmail(message);
                }
                catch
                {
                    errorMsg.Message.Add("Failure in sending Email confirmation, Please try again.");
                    return(Json(errorMsg));
                }

                Order order;
                try
                {
                    order = _context.Order.Where(o => o.UserID == user.Id && o.OrderStatus == "Ongoing")
                            .Include(o => o.OrderDetails)
                            .ThenInclude(od => od.Product)
                            .FirstOrDefault();
                    if (order == null || order.OrderDetails.Count() == 0)
                    {
                        errorMsg.Message.Add("Unable to locate order");
                        return(Json(errorMsg));
                    }

                    //List<OrderDetails> orderToRemove = new List<OrderDetails>();
                    List <Product> productToUpdate = new List <Product>();
                    //check availability
                    foreach (OrderDetails orderDetail in order.OrderDetails)
                    {
                        if (orderDetail.Quantity > orderDetail.Product.ProductStock)
                        {
                            errorMsg.Message.Add(string.Format($"{orderDetail.Product.ProductName} Has Been Sold Out"));
                            _context.OrderDetails.Remove(orderDetail);
                            _context.SaveChanges();
                        }
                        else
                        {
                            Product product = _context.Product.Where(p => p.ProductID == orderDetail.ProductID).FirstOrDefault();
                            product.ProductStock             -= orderDetail.Quantity;
                            product.CurrentWeekPurchaseCount += orderDetail.Quantity;
                            productToUpdate.Add(product);
                        }
                    }

                    if (errorMsg.Message.Count() > 0)
                    {
                        return(Json(errorMsg));
                    }

                    foreach (Product product in productToUpdate)
                    {
                        _context.Update(product);
                    }

                    order.OrderDateTime   = DateTime.Now;
                    order.OrderStatus     = "Preparing";
                    order.DeliveryOptions = model.DeliveryOptions;
                    order.OrderTotal      = order.OrderDetails.Sum(od => od.TotalPrice);

                    //Attach Reward
                    List <Reward> rewards = _context.Reward.Where(r => r.UserID == user.Id && r.RewardStatus == RewardStatus.Available).ToList();

                    foreach (Reward reward in rewards)
                    {
                        OrderDetails orderDetails = new OrderDetails()
                        {
                            OrderID    = order.OrderID,
                            ProductID  = reward.ProductID,
                            Quantity   = 1,
                            TotalPrice = 0,
                        };
                        _context.OrderDetails.Add(orderDetails);

                        reward.RewardStatus = RewardStatus.Claimed;
                        reward.OrderID      = order.OrderID;
                        _context.Update(reward);
                    }

                    _context.Order.Update(order);
                    _context.SaveChanges();
                }
                catch
                {
                    errorMsg.Message.Add("Failure in creating order, please try again.");
                    return(Json(errorMsg));
                }

                try
                {
                    if (isAnonymous)
                    {
                        user.LastName    = model.LastName;
                        user.FirstName   = model.FirstName;
                        user.PhoneNumber = model.PhoneNumber;
                    }
                    user.DeliveryAddress = model.DeliveryAddress;
                    user.DeliveryEmail   = model.DeliveryEmail;
                    user.Suburb          = model.Suburb;
                    user.ZipCode         = model.ZipCode;
                    user.Unit            = model.Unit;
                    if (order.OrderTotal >= 100)
                    {
                        user.RewardPlayChanceCount += (int)order.OrderTotal / 100;
                    }
                    _context.ApplicationUser.Update(user);
                    _context.SaveChanges();
                    errorMsg.IsSuccess   = true;
                    errorMsg.UrlRedirect = Url.Action("Success", "Checkout", new { userID = user.Id, orderID = model.OrderID });
                    return(Json(errorMsg));
                }
                catch
                {
                    order.OrderStatus     = "Ongoing";
                    order.DeliveryOptions = "";
                    _context.Order.Update(order);
                    _context.SaveChanges();
                    errorMsg.Message.Add("Failure in filling user information, order is not applied");
                    return(Json(errorMsg));
                }
            }

            var allErrors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage));

            foreach (string error in allErrors)
            {
                errorMsg.Message.Add($"{error}");
            }
            return(Json(errorMsg));
        }
        public async Task <JsonResult> Register([Bind("Email,FirstName,LastName,Address,PhoneNumber,ConfirmPassword,Password")] RegisterViewModel model)
        {
            ErrorMessage errorMsg = new ErrorMessage();

            errorMsg.IsSuccess = false;

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    Email              = model.Email,
                    UserName           = model.Email,
                    FirstName          = model.FirstName,
                    LastName           = model.LastName,
                    Address            = model.Address,
                    PhoneNumber        = model.PhoneNumber,
                    PictureUrl         = "blank-profile.png",
                    AccountCreatedDate = DateTime.Now,
                };

                var result = await _UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    try {
                        //GENERATE EMAIL GENERATION TOKEN
                        var token = await _UserManager.GenerateEmailConfirmationTokenAsync(user);

                        var confirmationLink =
                            Url.Action("ConfirmEmail", "Account", new { userID = user.Id, token = token }, Request.Scheme);

                        //SENDING EMAIL (REENABLE THIS LATER)
                        MailMessage message = new MailMessage("*****@*****.**", model.Email);
                        message.Subject = "Confirm your E-mail registration - HomeSquare";
                        message.Body    = "Thank you for registering with us, Click here to activate your account: \n" + confirmationLink;
                        EmailController.SendEmail(message);

                        errorMsg.IsSuccess = true;
                        errorMsg.Message.Add($"Registration Successful - To activate your account, please visit on the link that has been sent to {model.Email}");

                        await _UserManager.AddToRoleAsync(user, "CUSTOMER");
                    }
                    catch
                    {
                        await _UserManager.DeleteAsync(user);

                        errorMsg.Message.Add("Failure in sending Email confirmation, Please try again.");
                    }
                    return(Json(errorMsg));
                }


                foreach (var error in result.Errors)
                {
                    if (error.Code == "DuplicateUserName")
                    {
                        continue;
                    }
                    errorMsg.Message.Add($"{error.Description}");
                }
            }

            var allErrors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage));

            foreach (string error in allErrors)
            {
                errorMsg.Message.Add($"{error}");
            }
            return(Json(errorMsg));
        }