Exemplo n.º 1
0
        public async Task CheckLot()
        {
            var lots = repository.NotCheckedLots();

            foreach (var lot in lots)
            {
                if (lot.Ending < DateTime.UtcNow)
                {
                    if (lot.WinnerName != null)
                    {
                        var winner = await userManager.FindByNameAsync(lot.WinnerName);

                        var message = $"{winner.UserName}, вы успешно приобрели лот: {lot.Name}";

                        await email.SendEmailAsync(winner.Email, "AuctionCars", message);

                        var messageToOwner = $"{lot.User.UserName}, ваш лот {lot.Name} был приобретён пользователем {winner.UserName}";

                        await email.SendEmailAsync(lot.User.Email, "AuctionCars", messageToOwner);
                    }
                    else
                    {
                        var user = await userManager.FindByNameAsync(lot.User.UserName);

                        var message = $"{user.UserName}, никто не купил ваш лот: {lot.Name}";

                        await email.SendEmailAsync(user.Email, "AuctionCars", message);
                    }

                    lot.Ended = true;
                    repository.UpdateLot(lot);
                }
            }
        }
        public async Task <IActionResult> ForgotPassword(string Email)
        {
            if (string.IsNullOrEmpty(Email))
            {
                return(View());
            }
            var user = await _userManager.FindByEmailAsync(Email);

            if (user == null)
            {
                return(View());
            }
            //generate token
            var code = await _userManager.GeneratePasswordResetTokenAsync(user);

            var url = Url.Action("ResetPassword", "Account",
                                 new{
                userId = user.Id,
                token  = code
            });


            await _emailSender.SendEmailAsync(Email, "ResetPassword", $"Parolunuz Yenilemek ucun <a href='http://localhost:5000{url}'></a> klikleyin");

            return(View());
        }
Exemplo n.º 3
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

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


            var userId = await _userManager.GetUserIdAsync(user);

            var email = await _userManager.GetEmailAsync(user);

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { userId = userId, code = code },
                protocol: Request.Scheme);
            await _emailSender.SendEmailAsync(
                email,
                "Confirm your email",
                $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

            StatusMessage = "Verification email sent. Please check your email.";
            return(RedirectToPage());
        }
Exemplo n.º 4
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (ModelState.IsValid)
            {
                var user = await _userManager.FindByEmailAsync(Input.Email);

                if (user == null || !(await _userManager.IsEmailConfirmedAsync(user)))
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    return(RedirectToPage("./ForgotPasswordConfirmation"));
                }

                // For more information on how to enable account confirmation and password reset please
                // visit https://go.microsoft.com/fwlink/?LinkID=532713
                var code = await _userManager.GeneratePasswordResetTokenAsync(user);

                var callbackUrl = Url.Page(
                    "/Account/ResetPassword",
                    pageHandler: null,
                    values: new { code },
                    protocol: Request.Scheme);

                await _emailSender.SendEmailAsync(
                    Input.Email,
                    "Reset Password",
                    $"Please reset your password by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                return(RedirectToPage("./ForgotPasswordConfirmation"));
            }

            return(Page());
        }
Exemplo n.º 5
0
        public async Task <IActionResult> OnPostSendVerificationEmailAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

            if (user == null)
            {
                return(NotFound($"Tài khoản  không tồn tại '{_userManager.GetUserId(User)}'."));
            }


            var userId = await _userManager.GetUserIdAsync(user);

            var email = await _userManager.GetEmailAsync(user);

            var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var callbackUrl = Url.Page(
                "/Account/ConfirmEmail",
                pageHandler: null,
                values: new { userId = userId, code = code },
                protocol: Request.Scheme);
            await _emailSender.SendEmailAsync(
                email,
                "Xác thực email",
                $"Yêu cầu xác thực email cho tai khoản {User.Identity.Name} <a href='{callbackUrl}'>clicking here</a>");

            StatusMessage = "Gửi email thành công , vui lòng kiểm tra hộp thư !!";
            return(RedirectToPage());
        }
Exemplo n.º 6
0
        private async Task SendConfirmationEmailAsync(string token, string email, string linkConfirmation, int opc)
        {
            switch (opc)
            {
            case 1:
                _logger.Log(LogLevel.Warning, linkConfirmation);
                _logger.LogInformation("SendEmail");

                string subject  = "Confirmação de cadastro";
                string menssage = "Obrigado por se cadastrar em nossa plataforma, " +
                                  "esperamos que você possa disfrutar o melhor do nosso serviço. Para finalizar seu cadastro, basta clicar no link a seguir:  " + linkConfirmation;

                await _email.SendEmailAsync(email, subject, menssage);

                break;

            case 2:
                _logger.Log(LogLevel.Warning, linkConfirmation);
                _logger.LogInformation("SendEmail");

                string subjectPassword = "******";
                string messagePassword = "******" + linkConfirmation;

                await _email.SendEmailAsync(email, subjectPassword, messagePassword);

                break;

            case 3:
                _logger.Log(LogLevel.Warning, linkConfirmation);
                _logger.LogInformation("SendEmail");

                string subjectDataChaged  = "Alteração de dados";
                string messageDataChanged = "Alguns dados podem ter sido alterado, qualquer duvida, contatar o suporte " + linkConfirmation;

                await _email.SendEmailAsync(email, subjectDataChaged, messageDataChanged);

                break;
            }
        }
Exemplo n.º 7
0
        public async Task <IActionResult> Register(RegistrationViewModel model)
        {
            if (ModelState.IsValid)
            {
                User user = new User
                {
                    Email        = model.Email,
                    UserName     = model.Name,
                    Registration = DateTime.Now.ToUniversalTime(),
                };

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


                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(user, "guest");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    await _signInManager.PasswordSignInAsync(user, model.Password, isPersistent : false, lockoutOnFailure : false);

                    var url = Url.Action(
                        "ConfirmEmail",
                        "Account",
                        new { userId = user.Id, code = code },
                        protocol: HttpContext.Request.Scheme);
                    await Email.SendEmailAsync(model.Email, "Confirm your account",
                                               $"Подтвердите аккаунт, перейдя по ссылке: <a href='{url}'>link</a>");

                    return(RedirectToAction("Message"));
                }

                else
                {
                    foreach (var error in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            else
            {
                var errors = ModelState.Select(x => x.Value.Errors)
                             .Where(y => y.Count > 0)
                             .ToList();
            }
            return(View(model));
        }
Exemplo n.º 8
0
        public async Task <IActionResult> Register(RegisterModel register_user)
        {
            if (!ModelState.IsValid)
            {
                return(View(register_user));
            }

            var user = new User
            {
                UserName  = register_user.UserName,
                FirstName = register_user.FirstName,
                LastName  = register_user.LastName,
                Email     = register_user.Email
            };

            ModelState.AddModelError("Password", "Your password must be at least 6 characters and contain numeric characters, lowercase characters, and special character.");

            var result = await userManager.CreateAsync(user, register_user.Password);

            if (result.Succeeded)
            {
                var cod = await userManager.GenerateEmailConfirmationTokenAsync(user);

                var url = Url.Action("ConfirmEmail", "Account", new
                {
                    userId = user.Id,
                    token  = cod,
                });

                await emailstmp.SendEmailAsync(register_user.Email, "Please confirm account", $"Please <a href='https://localhost:44374{url}'>click</a> the link for account verify");

                return(RedirectToAction("Login", "Account"));
            }

            return(View(register_user));
        }
Exemplo n.º 9
0
        public async Task <IActionResult> Bet(LotDetailtViewModel model)
        {
            CarLot lot         = carLotsRepository.GetDetailLot(model.BetId);
            User   currentUser = await _userManager.GetUserAsync(HttpContext.User);

            if (lot.Price > model.BetPrice || lot.StartPrice > model.BetPrice)
            {
                return(RedirectToAction("Detail", new { id = lot.Id }));
            }

            if (ModelState.IsValid)
            {
                User user = await _userManager.GetUserAsync(HttpContext.User);

                Bet bet = new Bet
                {
                    User     = user,
                    NewPrice = model.BetPrice,
                    CarLot   = lot,
                    Time     = DateTime.UtcNow
                };
                lot.WinnerName = user.UserName;
                if (lot.Bets.Count > 1)
                {
                    currentUser = lot.Bets.Last().User;
                }
                betRep.AddBet(bet);
                lot.Price = model.BetPrice;
                carLotsRepository.UpdateLot(lot);


                await updateHub.Clients.Group(lot.Id.ToString()).SendAsync("UpdateTable", lot.Id, bet.User.Id, bet.User.UserName, bet.NewPrice, bet.Time);

                if (lot.Bets.Count >= 1 && currentUser.Email != user.Email)
                {
                    await Email.SendEmailAsync(currentUser.Email, "CarLots",
                                               $"Ваша ставка на товар {lot.Name} была перебита ставкой в {lot.Price} пользователем {user.UserName}");
                }


                return(RedirectToAction("Detail", new { id = lot.Id }));
            }



            return(RedirectToAction("Detail", new { id = lot.Id }));
        }
Exemplo n.º 10
0
        public async Task TestEmail()
        {
            IEmail email = MailProvider.Instance;

            email.Config = new MailConfig()
            {
                ServMailAccount  = "*****@*****.**",
                ServMailSMTP     = "smtp.qq.com",
                ServMailPort     = 465,
                ServMailUserName = "******",
                ServMailUserPwd  = "nqfxginv111111111111", //私人账号信息有所改动
                ServMailIsSSL    = true,
                FromDisplayName  = "测试的"
            };
            var result = await email.SendEmailAsync("*****@*****.**", "这是一个测试", "this<br/>is<br>a<br/>test");

            Assert.AreEqual(result.isSuccess, true);
        }
Exemplo n.º 11
0
    public async Task <bool> ResetPassword(string email, Func <Object, string> getCallbackUrl)
    {
        var user = await u.FindByNameAsync(email);

        if (user != null || (await u.IsEmailConfirmedAsync(user)))
        {
            return(false);
        }

        var code = await u.GeneratePasswordResetTokenAsync(user);

        var url = getCallbackUrl(new { userId = user.Id, code = code });

        await emailer.SendEmailAsync(
            email,
            "Reset Password",
            $"Please reset your password by clicking here: <a href='{url}'>link</a>");

        return(true);
    }
Exemplo n.º 12
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");
            if (ModelState.IsValid)
            {
                var user = new IdentityUser {
                    UserName = Input.Email, Email = Input.Email
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.Page(
                        "/Account/ConfirmEmail",
                        pageHandler: null,
                        values: new { userId = user.Id, code = code },
                        protocol: Request.Scheme);

                    await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                                                      $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

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

                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 13
0
        /// <summary>
        /// Build Message object with user input and call SendGrid method.
        /// Strips any white space from the filename before upload.
        /// </summary>
        /// <returns> Redirect </returns>
        public async Task OnPostSend(IFormFile[] files)
        {
            Uris images = new Uris();


            foreach (var file in files)
            {
                if (file != null)
                {
                    string filename = file.FileName.Replace(" ", String.Empty);
                    using var stream = System.IO.File.Create(filename);
                    await file.CopyToAsync(stream);

                    stream.Position = 0;
                    images.ImageUris.Add(new ImageUri(((await _upload.UploadImage(stream, filename, file.ContentType)).Uri).ToString()));
                }
            }
            RequestForm message = new RequestForm()
            {
                Name         = RequestForm.Name,
                Email        = RequestForm.Email,
                Body         = RequestForm.Body,
                Availability = RequestForm.Availability,
                Uris         = images
            };
            EmailResponse response = await _email.SendEmailAsync(message);

            HomePage = await _admin.GetHomePage("Booking");

            if (response.WasSent)
            {
                WasSent = true;
            }

            Redirect("/Art/Booking");
        }
Exemplo n.º 14
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            var user = await _userManager.GetUserAsync(User);

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

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

            if (!changePasswordResult.Succeeded)
            {
                foreach (var error in changePasswordResult.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
                return(Page());
            }

            var emailUser = await _userManager.GetEmailAsync(user);

            await _emailService.SendEmailAsync(emailUser, "Thay đổi mật khẩu tài khoản " + emailUser, "Mật khẩu của bạn đã được thay đổi " + Input.NewPassword);

            await _signInManager.RefreshSignInAsync(user);

            _logger.LogInformation("User changed their password successfully.");
            StatusMessage = "Your password has been changed.";

            return(RedirectToPage());
        }
 public async Task Handle(QuantidadeMinimaAtingidaEvent notification, CancellationToken cancellationToken)
 {
     await _email.SendEmailAsync(notification.Email, "Produto Quantidade Insuficiente Atingida", "Produto Quantidade Insuficiente Atingida");
 }