Example #1
0
        public async Task <IActionResult> LinkLoginCallback()
        {
            var execRes = new ExecutionResult();
            var user    = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var info = await _signInManager.GetExternalLoginInfoAsync(user.Id);

            if (info == null)
            {
                throw new ApplicationException($"Unexpected error occurred loading external login info for user with ID '{user.Id}'.");
            }

            var result = await _userManager.AddLoginAsync(user, info);

            if (!result.Succeeded)
            {
                throw new ApplicationException($"Unexpected error occurred adding external login for user with ID '{user.Id}'.");
            }

            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            execRes.AddInfo("The external login was added.").PushTo(TempData);
            return(RedirectToAction(nameof(ExternalLogins)));
        }
Example #2
0
        public async Task <IActionResult> ChangePassword(ChangePasswordViewModel model)
        {
            var execRes = new ExecutionResult();

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var changePasswordResult = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword);

            if (!changePasswordResult.Succeeded)
            {
                AddErrors(changePasswordResult);
                return(View(model));
            }

            await _signInManager.SignInAsync(user, isPersistent : false);

            _logger.LogInformation("User changed their password successfully.");
            execRes.AddInfo(_localizer["Your password has been changed."]).PushTo(TempData);

            return(RedirectToAction(nameof(ChangePassword)));
        }
Example #3
0
        public async Task <IActionResult> SetPassword(SetPasswordViewModel model)
        {
            var execRes = new ExecutionResult();

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var addPasswordResult = await _userManager.AddPasswordAsync(user, model.NewPassword);

            if (!addPasswordResult.Succeeded)
            {
                AddErrors(addPasswordResult);
                return(View(model));
            }

            await _signInManager.SignInAsync(user, isPersistent : false);

            execRes.AddInfo("Your password has been set.").PushTo(TempData);

            return(RedirectToAction(nameof(SetPassword)));
        }
Example #4
0
        public async Task <IActionResult> Index(IndexViewModel model)
        {
            var execRes = new ExecutionResult();

            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var email = user.Email;

            if (model.Email != email)
            {
                var setEmailResult = await _userManager.SetEmailAsync(user, model.Email);

                if (!setEmailResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting email for user with ID '{user.Id}'.");
                }
            }

            var phoneNumber = user.PhoneNumber;

            if (model.PhoneNumber != phoneNumber)
            {
                var setPhoneResult = await _userManager.SetPhoneNumberAsync(user, model.PhoneNumber);

                if (!setPhoneResult.Succeeded)
                {
                    throw new ApplicationException($"Unexpected error occurred setting phone number for user with ID '{user.Id}'.");
                }
            }
            var adress = user.Address;

            if (model.Address != adress)
            {
                user.Address = model.Address;
                await _context.SaveChangesAsync();
            }

            if (user.EmailSendPromotional != model.EmailSendPromotional ||
                user.EmailSendUpdates != model.EmailSendUpdates)
            {
                user.EmailSendPromotional = model.EmailSendPromotional;
                user.EmailSendUpdates     = model.EmailSendUpdates;
                await _context.SaveChangesAsync();
            }

            execRes.AddInfo(_localizer["Your profile has been updated"]).PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Example #5
0
        public async Task <IActionResult> SendVerificationEmail(IndexViewModel model)
        {
            var execRes = new ExecutionResult();

            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Index)));
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            }

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Action("ConfirmEmail", "Account", new
            {
                userid = user.Id,
                token  = code
            }, HttpContext.Request.Scheme);

            var    subject = _localizer["Confirm email"];
            string text;

            using (var sourceReader = System.IO.File.OpenText("Templates/EmailTemplate/Confirm_Email.html"))
            {
                text = sourceReader.ReadToEnd();
            }

            //{0} : Username
            //{1} : _localizer["Thank you for registering"]
            //{2} : Token URL
            //{3} : Confirm email

            var messageBody = string.Format(text,
                                            user.UserName,
                                            _localizer["thank you for registering"],
                                            callbackUrl,
                                            _localizer["Confirm email"]
                                            );

            await _emailSender.SendEmailAsync(model.Email, subject, messageBody);

            execRes.AddInfo(_localizer["Verification email sent. Please check your email."]).PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Example #6
0
        public async Task <IActionResult> Redeem([Bind("Id")] RedeemViewModel model)
        {
            var execRes = new ExecutionResult();

            if (!ModelState.IsValid)
            {
                return(View());
            }

            var code = _context.PrepaidCodes.SingleOrDefault(c => c.Id == Guid.Parse(model.Id));

            if (code == null)
            {
                execRes.AddError(_localizer["Provided code doesn't exist."]).PushTo(TempData);
                return(View());
            }
            if (code.RedemptionDate != null)
            {
                execRes.AddError(_localizer["Provided code has already been used."]).PushTo(TempData);
                return(View());
            }

            var user = _context.Users.Single(u => u.Id == User.GetId());

            code.Redeemer       = user ?? throw new ApplicationException($"Unable to load user with ID '{_userManager.GetUserId(User)}'.");
            code.RedemptionDate = DateTime.Now;

            user.Coins += code.Amount;

            _cache.Remove(user.UserName);

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddInfo(
                    _localizer["Code has been succesfully redeemed. Added {0} to the acccount balance. New balance: {1}!", code.Amount, user.Coins]);
            }
            else
            {
                execRes.AddError(_localizer["Failed to use the code. Try again later."]);
            }

            execRes.PushTo(TempData);
            return(View());
        }
Example #7
0
        public async Task <IActionResult> DeleteConfirmed(string id)
        {
            var pizza = await _context.Pizzas.SingleOrDefaultAsync(m => m.NameLt == id);

            _context.Pizzas.Remove(pizza);

            var execRes = new ExecutionResult();

            try
            {
                if (await _context.SaveChangesAsync() > 0)
                {
                    execRes.AddSuccess("Pizza deleted successfully.");
                }
                else
                {
                    execRes.AddError("Database error. Pizza was not deleted.");
                }
            }
            catch (DbUpdateException)
            {
                _context.Entry(pizza).State = EntityState.Unchanged;
                pizza.IsDepricated          = true;
                if (await _context.SaveChangesAsync() > 0)
                {
                    execRes.AddInfo("Pizza could not be fully deleted. Changed to depricated.");
                }
                else
                {
                    execRes.AddError("Database error. Pizza was not deleted.");
                }
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }
Example #8
0
        public async Task <IActionResult> Continue(ConfirmCheckoutViewModel model)
        {
            var execRes = new ExecutionResult();

            var clientId = User.GetId();
            var user     = _context.Users.Single(u => u.Id == clientId);

            if (!ModelState.IsValid)
            {
                var requestCulture = HttpContext.Features.Get <IRequestCultureFeature>();
                var cultCode       = requestCulture.RequestCulture.UICulture.Name;
                model.CheckoutList = GetCheckoutOrders(clientId, cultCode);
                model.Price        = model.CheckoutList.Sum(o => o.Price * o.Quantity);

                return(View(model));
            }

            var orders = await _context.Orders.Include(o => o.Pizza)
                         .Where(o => o.Client.Id == clientId)
                         .Where(o => o.Status == OrderStatus.Unpaid)
                         .Where(o => o.PlacementDate > DateTime.Now.AddDays(-7)) // Each item is only valid for 7 days
                         .ToArrayAsync();

            var price = orders.Sum(o => o.Price * o.Quantity);

            if (price > user.Coins)
            {
                // insufficient PizzaCoins
                execRes.AddError(_localizer["Insufficient amount of coins in the balance."]).PushTo(TempData);
                return(RedirectToAction("Index"));
            }

            // looks good, go ahead

            foreach (var checkoutEntry in orders)
            {
                var order = _context.Orders.Single(o => o.Id == checkoutEntry.Id);
                order.Status          = OrderStatus.Queued;
                order.IsPaid          = true;
                order.DeliveryAddress = model.ConfirmAddress;
                order.DeliveryComment = model.Comment;
                order.PaymentDate     = DateTime.Now;
                order.PhoneNumber     = model.PhoneNumber;
            }

            user.Coins -= price;

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddSuccess(_localizer["Pizza was ordered successfully."]);
            }
            else
            {
                execRes.AddError(_localizer["Order could not be processed. Please try again."]).PushTo(TempData);
                return(RedirectToAction("Index"));
            }

            if (user.EmailSendUpdates)
            {
                await SendEmail(user, orders.ToArray());

                execRes.AddInfo(_localizer["Email was sent to {0}", user.Email]);
            }

            _cache.Remove(user.UserName);

            execRes.PushTo(TempData);
            return(RedirectToAction("Index", "Order"));
        }
Example #9
0
        public async Task <IActionResult> Create(string id, OrderCreateViewModel model)
        {
            var execRes = new ExecutionResult();

            var pizza = _context.Pizzas.SingleOrDefault(i => i.NameEn == id);

            if (pizza == null)
            {
                execRes.AddError(_localizer["Requested pizza was not found. Please try again."]).PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            if (!ModelState.IsValid)
            {
                model.Prices   = _context.PizzaPriceInfo.Where(info => info.PriceCategoryId == pizza.PriceCategoryId);
                model.MinPrice = model.Prices.Min(p => p.Price);
                return(View(model));
            }

            if (pizza.IsDepricated)
            {
                execRes.AddError(_localizer["Pizza no longer exists. Please try another pizza."]).PushTo(TempData);
                return(RedirectToAction(nameof(Index)));
            }

            var ppi = _context.PizzaPriceInfo.SingleOrDefault(g => g.Id == model.SizeId);

            if (ppi == null || pizza.PriceCategoryId != ppi.PriceCategoryId)
            {
                execRes.AddError(_localizer["Unexpected size was selected. Please try again."]).PushTo(TempData);
                return(RedirectToAction(nameof(Create), new { Id = id }));
            }

            var userId = User.GetId();

            if (string.IsNullOrEmpty(userId))
            {
                execRes.AddError(_localizer["You are logged out. Please log in to add the order."]).PushTo(TempData);
                return(RedirectToAction(nameof(Create), new { Id = id }));
            }

            // Check if there is an order in the basket already
            var order = await _context.Orders.SingleOrDefaultAsync(o => !o.IsPaid && o.PizzaId == pizza.Id && o.ClientId == userId && o.Size == ppi.Size);

            if (order != null)
            {
                order.Price         = ppi.Price;
                order.Quantity     += model.Quantity;
                order.PlacementDate = DateTime.Now;
                // Adds a new line to the comment with the new comment.
                order.CookingComment = string.IsNullOrEmpty(order.CookingComment)
                    ? model.Comment : string.IsNullOrEmpty(model.Comment)
                        ? order.CookingComment : $"{order.CookingComment}\n-----\n{model.Comment}";
            }
            else
            {
                order = new Order
                {
                    Id             = Guid.NewGuid(),
                    Pizza          = pizza,
                    ClientId       = userId,
                    CookingComment = model.Comment,
                    Quantity       = model.Quantity,
                    Price          = ppi.Price,
                    Size           = ppi.Size,
                    PlacementDate  = DateTime.Now
                };
                _context.Add(order);
            }

            if (await _context.SaveChangesAsync() > 0)
            {
                execRes.AddInfo(_localizer["Pizza was succesfully added to the cart."]);
            }
            else
            {
                execRes.AddError(_localizer["Pizza could not be added to the cart. Please try again."]);
            }

            execRes.PushTo(TempData);
            return(RedirectToAction(nameof(Index)));
        }