コード例 #1
0
 public ActionResult Detail(Question model, HttpPostedFileBase fileInput)
 {
     if (ModelState.IsValid)
     {
         try
         {
             if (fileInput.ContentLength > 0)
             {
                 string _fileName = Path.GetFileName(fileInput.FileName);
                 bool   exists    = System.IO.Directory.Exists(Server.MapPath("~/FileAttach"));
                 if (!exists)
                 {
                     Directory.CreateDirectory(Server.MapPath("~/FileAttach"));
                 }
                 string _path = Path.Combine(Server.MapPath("~/FileAttach"), _fileName);
                 fileInput.SaveAs(_path);
                 model.attachment = _fileName;
             }
         }
         catch (Exception ex)
         {
         }
         MvcCaptcha.ResetCaptcha("ExampleCaptcha");
         model.createTime = DateTime.Now;
         _Service.Add(model);
         _Service.Save();
         return(Content("<script language='javascript' type='text/javascript'>alert('Câu hỏi đã được gửi đi thành công!');window.location = '/hoi-dap';</script>"));
     }
     return(View(model));
 }
コード例 #2
0
ファイル: ClueController.cs プロジェクト: wachara-yanu/OCPB
 public ActionResult Index(Clue obj, bool captchaValid, List <HttpPostedFileBase> Filename)
 {
     if (captchaValid)
     {
         if (ModelState.IsValid)
         {
             ClueMapDao clueMap = new ClueMapDao();
             if (obj.ID == 0)
             {
                 obj.Active     = true;
                 obj.CreateDate = DateTime.Now;
                 obj.Keygen     = Guid.NewGuid().ToString();
             }
             obj.Complain_Channel_id = 1;//เรื่องร้องทุกข์ Online
             clueMap.Add(obj);
             clueMap.CommitChange();
             SaveUtility.SaveClueFileUpload(Filename, "Clue", obj.Keygen);
             return(RedirectToAction("ClueModal", "Clue"));
         }
     }
     TempData.Clear();
     ModelState.AddModelError("", "ข้อมูลไม่ถูกต้อง");
     MvcCaptcha.ResetCaptcha("ClueCaptcha");
     return(View(obj));
 }
コード例 #3
0
        public ActionResult LoginComCaptcha(AutenticacaoModel usuario)
        {
            MvcCaptcha.ResetCaptcha("LoginCaptcha");
            ViewBag.IncluirCaptcha = Convert.ToBoolean(ConfigurationManager.AppSettings["AD:DMZ"]);

            try
            {
                if (ModelState.IsValid)
                {
                    AutorizacaoProvider.Logar(usuario);

                    if (!string.IsNullOrWhiteSpace(usuario.Nome))
                    {
                        return(Json(new { url = usuario.Nome.Replace("$", "&") }));
                    }
                    else
                    {
                        return(Json(new { url = Url.Action(ConfigurationManager.AppSettings["Web:DefaultAction"], ConfigurationManager.AppSettings["Web:DefaultController"]) }));
                    }
                }

                return(View("Login", usuario));
            }
            catch (Exception ex)
            {
                return(Json(new { alerta = ex.Message, titulo = "Oops! Problema ao realizar login..." }));
            }
        }
コード例 #4
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (!_authRepository.AlreadyExists(model.Email))
                {
                    // Try and send the confirmation email first. If that works, and the email is valid, then add it here.

                    var result = _authRepository.Register(model.Email, model.Password);
                    if (result.Success)
                    {
                        // Generate an email confirmation token for this account
                        var token = AuthEncryption.RandomSalt(6);
                        result = _authRepository.SetEmailConfirmationToken(model.Email, token);
                        var secureUrl = Url.Action("ConfirmEmail", "Account", new { e = model.Email, c = token }, "https");

                        string mailBody = MailCommonStrings.RegisteredBody(secureUrl);
                        Mailer.SendEmail_NoWait(model.Email, MailCommonStrings.RegisteredSubject, mailBody);
                        _logger.Debug($"{model.Email} has successfully registered an account from {ClientIpAddress.GetIPAddress(Request)}");

                        MvcCaptcha.ResetCaptcha("regoCaptcha");
                        return(RedirectToAction("ConfirmationRequired"));
                    }

                    ModelState.AddModelError("", result.Message);
                }
                else
                {
                    ModelState.AddModelError("", "An account with this email address already exists!");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #5
0
        public async Task <ActionResult> ResetPassword(PasswordResetViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (!string.IsNullOrEmpty(model.Email) && !string.IsNullOrEmpty(model.Code))
                {
                    if (_authRepository.CanResetPassword(model.Email, model.Code))
                    {
                        var result = _authRepository.ResetPassword(model.Email, model.Password);
                        if (result.Success)
                        {
                            MvcCaptcha.ResetCaptcha("ChangePasswordCaptcha");
                            _logger.Debug(string.Format("The password for {0} has successfully been reset.", model.Email));
                            return(RedirectToAction("ResetPasswordConfirmation"));
                        }
                    }

                    MvcCaptcha.ResetCaptcha("ChangePasswordCaptcha");
                    return(RedirectToAction("ResetFailed"));
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #6
0
        public ActionResult SendFeedBack(FeedBackViewModel feedBackViewModel)
        {
            if (ModelState.IsValid)
            {
                var newFeedBack = new FeedBack();
                newFeedBack.UpdateFeedBack(feedBackViewModel);
                _feedBackSerive.Create(newFeedBack);
                _feedBackSerive.Save();

                ViewData["SuccessMsg"] = "Gửi phản hồi thành công";

                string content = System.IO.File.ReadAllText(Server.MapPath("/Assets/client/templates/contact_template.html"));
                content = content.Replace("{{Name}}", feedBackViewModel.Name);
                content = content.Replace("{{Email}}", feedBackViewModel.Email);
                content = content.Replace("{{Message}}", feedBackViewModel.Message);

                var adminEmail = ConfigHelper.GetByKey("AdminEmail");
                MailHelper.SendMail(adminEmail, "Thông tin liên hệ từ website", content);

                feedBackViewModel.Name    = "";
                feedBackViewModel.Email   = "";
                feedBackViewModel.Message = "";
            }
            else
            {
                MvcCaptcha.ResetCaptcha("contactCaptcha");
            }

            feedBackViewModel.ContactDetailViewModel = GetContactDetail();

            return(View("Index", feedBackViewModel));
        }
コード例 #7
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (!ValidateGmail(model.Email, model.Password))
                {
                    ModelState.AddModelError("", "Gmail account doesn't exist");

                    return(View(model));
                }

                var user = new ApplicationUser
                {
                    UserName = model.Email,
                    Email    = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, false, false);

                    MvcCaptcha.ResetCaptcha("SampleCaptcha");

                    Session[Settings.KEYS.PSW_SESSION_KEY] = model.Password;

                    return(RedirectToAction("Index", "Mailbox"));
                }

                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #8
0
        public IActionResult ContatoAcao([FromForm] Contato contato)
        {
            try
            {
                string     userInput  = HttpContext.Request.Form["CaptchaCode"];
                MvcCaptcha mvcCaptcha = new MvcCaptcha("ExampleCaptcha");
                if (!mvcCaptcha.Validate(userInput))
                {
                    ViewData["CONTATO"] = contato;
                    return(View("Contato", contato));
                }

                ModelState.Remove("captchacode");

                if (ModelState.IsValid)
                {
                    _gerenciarEmail.EnviarContatoPorEmail(contato);
                    ViewData["MSG_S"] = Mensagem.MSG_S003;
                    ViewData["MSG_E"] = "";
                    MvcCaptcha.ResetCaptcha("ExampleCaptcha");
                    return(View("Contato"));
                }
                else
                {
                    ViewData["CONTATO"] = contato;
                    return(View("Contato", contato));
                }
            }
            catch (Exception)
            {
                ViewData["MSG_E"] = Mensagem.MSG_E000;
            }
            return(View("Contato"));
        }
コード例 #9
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            try
            {
                MvcCaptcha.ResetCaptcha("captcha");

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

                // 這不會計算為帳戶鎖定的登入失敗
                // 若要啟用密碼失敗來觸發帳戶鎖定,請變更為 shouldLockout: true
                var result = await SignInManager.PasswordSignInAsync(model.Username, model.Password, model.RememberMe, shouldLockout : false);

                _logger.Information("Login_Model:{0}", JsonConvert.SerializeObject(model));
                _logger.Information("Login_Result:{0}", JsonConvert.SerializeObject(result));

                switch (result)
                {
                case SignInStatus.Success:
                    var user = _aspNetUsersService.GetUserModelByName(model.Username);
                    if (user.IsStopAuthority.HasValue)
                    {
                        if (user.IsStopAuthority.Value)
                        {
                            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
                            ModelState.AddModelError("", "該帳號已停權!");
                            TempData["LoginResult"] = "該帳號已停權!";
                            return(View("Login", model));
                        }
                        else
                        {
                            return(RedirectToLocal(returnUrl));
                        }
                    }
                    else
                    {
                        return(RedirectToLocal(returnUrl));
                    }

                case SignInStatus.LockedOut:
                    return(View("Lockout"));

                case SignInStatus.RequiresVerification:
                    return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

                case SignInStatus.Failure:
                default:
                    ModelState.AddModelError("", "登入嘗試失敗。");
                    TempData["LoginResult"] = "嘗試登入失敗!";
                    return(View(model));
                }
            }
            catch (Exception ex)
            {
                _logger.Information("Login_Error({0}) ", JsonConvert.SerializeObject(ex.Message));
                throw ex;
            }
        }
コード例 #10
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            try
            {
                var result = await _client.RegisterAsync(model.FullName, model.Email, model.Password);

                if (result.Body.RegisterResult.Success)
                {
                    MembershipHelper.SignIn(result.Body.RegisterResult.Result);

                    MvcCaptcha.ResetCaptcha(ControlHelper.CAPTCHA_KEY);

                    return(RedirectToLocal());
                }
                else
                {
                    ModelState.AddModelError("", result.Body.RegisterResult.Error);
                }
            }
            catch (StockException exception)
            {
                ModelState.AddModelError("", exception.Message);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
コード例 #11
0
        public ActionResult Contacto(Contacto cont)
        {
            bool prueba = MvcCaptcha.Validate("CaptchaCode", "Captcha", "Incorrect CAPTCHA code!");

            MvcCaptcha.ResetCaptcha("Captcha");
            return(View());
        }
コード例 #12
0
ファイル: NavController.cs プロジェクト: drobotjv/Uh365898_db
        public ActionResult Contacts(Offer offer, HttpPostedFileBase image)
        {
            logger.Error("Oтправка формы Контакт админстратору ");

            if (ModelState.IsValid)
            {
                // TODO: Captcha validation failed, show error message


                if (image != null)
                {
                    offer.ImageMimeType = image.ContentType;
                    offer.ImageData     = new byte[image.ContentLength];
                    image.InputStream.Read(offer.ImageData, 0, image.ContentLength);
                }
                offer.DateAdded = DateTime.Now;

                //[email protected]
                MailAddress fromMailAddress = new MailAddress("*****@*****.**", "UPR");
                MailAddress toAddress       = new MailAddress("*****@*****.**", "UPR");
                // MailAddress toAddress = new MailAddress("*****@*****.**", "UPR");
                using (MailMessage mailMessage = new MailMessage(fromMailAddress, toAddress))
                    using (SmtpClient smtpClient = new SmtpClient())
                    {
                        mailMessage.Subject = "Форма обратная связь c сайта upr.kh.ua";


                        mailMessage.Body = "Имя: " + offer.Name.ToString() + "\r" +
                                           "Телефон: " + offer.Phone.ToString() + "\r" +
                                           "Почта: " + offer.Email.ToString() + "\r" +
                                           "Дата: " + offer.DateAdded.ToString() + "\r" +
                                           "Тема сообщения: " + offer.Title.ToString() + "\r" +
                                           "Сообщение: " + offer.Description.ToString() + "\r";

                        smtpClient.Host                  = "smtp.gmail.com";
                        smtpClient.Port                  = 587;
                        smtpClient.EnableSsl             = true;
                        smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                        smtpClient.UseDefaultCredentials = false;
                        smtpClient.Credentials           = new NetworkCredential(fromMailAddress.Address, "1234567upr");

                        smtpClient.Send(mailMessage);
                    }


                repository.SaveOffer(offer);
                TempData["message"] = string.Format("{0}, Ваше сообщение отправлено", offer.Name);
                MvcCaptcha.ResetCaptcha("SampleCaptcha");

                return(RedirectToAction("Contacts"));
            }
            else
            {
                return(View(offer));
            }

            // there is something wrong with the data values
        }
コード例 #13
0
        [SimpleCaptchaValidation("CaptchaCode", "registerCaptcha", "Mã xác nhận không đúng!")] // adđ sử dụng capcha(botdetect- Nugetpacket) https://captcha.com/asp.net-captcha.html
        // viết bất đồng bộ để check nhanh hơn
        public async Task <ActionResult> Register(RegisterViewModel registerViewModel)
        {
            if (ModelState.IsValid)
            {
                // check thông tin trùng
                var userCheckEmail = await _userManager.FindByEmailAsync(registerViewModel.Email);

                if (userCheckEmail != null)
                {
                    ModelState.AddModelError("Email", "Email đã tồn tại");
                    return(View(registerViewModel));
                }

                var userCheckName = await _userManager.FindByNameAsync(registerViewModel.UserName);

                if (userCheckName != null)
                {
                    ModelState.AddModelError("UserName", "tài khoản đã tồn tại");
                    return(View(registerViewModel));
                }

                // thêm mới tài khoản
                var user = new ApplicationUser()
                {
                    UserName       = registerViewModel.UserName,
                    Email          = registerViewModel.Email,
                    EmailConfirmed = true,
                    FullName       = registerViewModel.FullName,
                    Address        = registerViewModel.Address
                };
                await _userManager.CreateAsync(user, registerViewModel.Password);


                // add tài khoản vào db
                var addUser = await _userManager.FindByIdAsync(registerViewModel.Email);

                if (addUser != null)
                {
                    await _userManager.AddToRolesAsync(addUser.Id, new string[] { "User" });
                }

                // gửi mail báo thành công
                string content = System.IO.File.ReadAllText(Server.MapPath("/Assets/client/template/newUser.html"));
                content = content.Replace("{{UserName}}", addUser.FullName);
                // nhớ cấu hình lại CurrentLink trong appsetting
                var LinkWeb = ConfigHelper.GetByKey("CurrentLink");
                content = content.Replace("{{Link}}", LinkWeb + "dang-nhap.html");
                MailHelper.SendMail(addUser.Email, "đăng ký thành công", content);

                TempData["Ketqua"] = "Đăng ký thành công";
            }
            else
            {
                MvcCaptcha.ResetCaptcha("registerCaptcha");
            }

            return(View());
        }
コード例 #14
0
 public ActionResult Registration()
 {
     MvcCaptcha.ResetCaptcha("SampleCaptcha");
     ViewData["cities"] = db.City.Select(x => new SelectListItem()
     {
         Text = x.Name, Value = x.CCode.ToString()
     }).ToList();
     return(View());
 }
コード例 #15
0
 public virtual ActionResult Contact(string model)
 {
     if (ModelState.IsValid)
     {
         // You should call ResetCaptcha as demonstrated in the following example.
         MvcCaptcha.ResetCaptcha("SampleCaptcha");
     }
     return(Json(model));
 }
コード例 #16
0
        //[CaptchaValidation("CaptchaCode", "UserRegisterCaptcha","Incorrect CAPTCHA code!")]
        public async Task <IActionResult> Register(RegisterViewModel model)
        {
            MvcCaptcha mvcCaptcha           = new MvcCaptcha("UserRegisterCaptcha");
            string     validatingInstanceId = mvcCaptcha.WebCaptcha.ValidatingInstanceId;

            if (mvcCaptcha.Validate(model.CaptchaCode, validatingInstanceId))
            {
                if (ModelState.IsValid)
                {
                    UserDTO userDto = new UserDTO
                    {
                        Email    = model.Email,
                        Year     = model.Year,
                        Password = model.Password,
                        UserName = model.Email
                    };
                    MvcCaptcha.ResetCaptcha("UserRegisterCaptcha");


                    OperationDetails operationDetails = await userService.Create(userDto);

                    if (operationDetails.Succeeded)
                    {
                        var claims = await userService.Authenticate(userDto);

                        string token = await GenerateJwtToken(claims);

                        Response.Cookies.Append("Authorization", "Bearer " + token, new CookieOptions()
                        {
                            IsEssential = true
                        });
                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError(operationDetails.Property, operationDetails.Message);
                    }
                }
                else
                {
                    MvcCaptcha.ResetCaptcha("UserRegisterCaptcha");
                    ModelState.AddModelError("", "Wrong email or password");
                }
            }
            else
            {
                MvcCaptcha.ResetCaptcha("UserRegisterCaptcha");
                ModelState.AddModelError("CaptchaCode", "Incorrect!");
            }

            return(View(model));
        }
コード例 #17
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // This needs to be tested to see if it actually encodes the data for preventing XSS attacks.
            model.Email    = Encoder.HtmlEncode(model.Email);
            model.Password = Encoder.HtmlEncode(model.Password);

            // This doesn't count login failures towards account lockout
            // To enable password failures to trigger account lockout, change to shouldLockout: true
            var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout : false);


            if (MvcCaptcha.IsCaptchaSolved("CustomCaptcha"))
            {
                // Use this to reset the captcha after the submit button has been pressed... This may need to be moved to the SignInStatus.Success case.
                MvcCaptcha.ResetCaptcha("CustomCaptcha");

                switch (result)
                {
                case SignInStatus.Success:
                    return(RedirectToLocal(returnUrl));

                case SignInStatus.LockedOut:
                    return(View("Lockout"));

                case SignInStatus.RequiresVerification:
                    return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }));

                case SignInStatus.Failure:
                default:

                    ModelState.AddModelError("", "Invalid login attempt.");
                    return(View(model));
                }
            }
            else
            {
                // Use this to reset the captcha after the submit button has been pressed... This may need to be moved to the SignInStatus.Success case.
                MvcCaptcha.ResetCaptcha("CustomCaptcha");


                ModelState.AddModelError("", "Invalid login attempt.");
                return(View(model));
            }
        }
コード例 #18
0
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                var dao = new UserDAO();
                if (dao.CheckUserName(model.UserName)) //nếu check user từ model truyền vào trùng với DAO thì xuất mã lỗi
                {
                    ModelState.AddModelError("", "Tên đăng nhập đã tồn tại!");
                }
                else if (dao.CheckEmail(model.Email)) //nếu check Email từ model truyền vào trùng với DAO thì xuất mã lỗi
                {
                    ModelState.AddModelError("", "Email đã tồn tại!");
                }
                else //không có lỗi thì ta tạo tài khoản
                {
                    var user = new User(); //tạo đối tượng và truyền từ model vào EF
                    user.UserName    = model.UserName;
                    user.Name        = model.Name;
                    user.Password    = model.Password;
                    user.Phone       = model.Phone;
                    user.Email       = model.Email;
                    user.Address     = model.Address;
                    user.CreatedDate = DateTime.Now;
                    user.Status      = true;

                    if (!string.IsNullOrEmpty(model.ProvinceID)) //model khác rỗng
                    {
                        user.ProvinceID = int.Parse(model.ProvinceID);
                    }
                    if (!string.IsNullOrEmpty(model.DistrictID))
                    {
                        user.DistrictID = int.Parse(model.DistrictID);
                    }
                    var result = dao.Insert(user); //insert user
                    if (result > 0)                //nếu > 0 thì có tài khoản
                    {
                        ViewBag.Success = "Đăng kí thành công :) ";
                        model           = new RegisterModel(); //reset toàn bộ model lại cho lần tạo tài khoản tiếp theo
                    }
                    else
                    {
                        ModelState.AddModelError("", "Đăng kí không thành công :( ");
                        MvcCaptcha.ResetCaptcha("registerCapcha");
                    }
                }
            }
            return(View(model));
        }
コード例 #19
0
        public ActionResult form1(Form1VM model)
        {
            if (!ModelState.IsValid)
            {
                // TODO: Captcha validation failed, show error message
                return(View(model));
            }
            else
            {
                // TODO: captcha validation succeeded; execute the protected action

                // Reset the captcha if your app's workflow continues with the same view
                MvcCaptcha.ResetCaptcha("ExampleCaptcha");
                return(Content("captcha is Correct"));
            }
        }
コード例 #20
0
 public ActionResult Register(RegisterModel model)
 {
     MvcCaptcha.ResetCaptcha("ExampleCaptcha");
     if (ModelState.IsValid)
     {
         var dao = new UserDao();
         if (dao.CheckUserName(model.UserName))
         {
             ModelState.AddModelError("", "Tên đăng nhập đã tồn tại");
         }
         else if (dao.CheckEmail(model.Email))
         {
             ModelState.AddModelError("", "Email đã tồn tại");
         }
         else
         {
             var user = new User();
             user.UserName   = model.UserName;
             user.Name       = model.Name;
             user.Password   = Encryptor.MD5Hash(model.Password);
             user.Phone      = model.Phone;
             user.Email      = model.Email;
             user.Address    = model.Address;
             user.CreateDate = DateTime.Now;
             user.Status     = true;
             if (!string.IsNullOrEmpty(model.ProvinceID.ToString()))
             {
                 user.ProvinceID = model.ProvinceID;
             }
             if (!string.IsNullOrEmpty(model.DistrictID.ToString()))
             {
                 user.DistrictID = model.DistrictID;
             }
             var result = dao.Insert(user);
             if (result > 0)
             {
                 ViewBag.Success = "Đăng ký thành công";
                 model           = new RegisterModel();
             }
             else
             {
                 ModelState.AddModelError("", "Đăng ký không thành công");
             }
         }
     }
     return(View(model));
 }
コード例 #21
0
 public ActionResult Register(Register model)
 {
     if (ModelState.IsValid)
     {
         var result = this.db.Users.SingleOrDefault(x => x.UserName == model.UserName);
         if (result == null)
         {
             if (model.PassWord == model.ConfirmPassWord)
             {
                 if (model.PassWord.Length >= 6 && model.PassWord.Any(char.IsUpper))
                 {
                     var data      = new UserData();
                     var encryptor = Encryptor.SHA256Hash(model.PassWord);
                     model.PassWord = encryptor;
                     var user = new User();
                     user.UserName    = model.UserName;
                     user.Email       = model.Email;
                     user.Password    = model.PassWord;
                     user.Name        = model.Name;
                     user.DateOfBirth = model.DateOfBirth;
                     user.Sex         = model.Sex;
                     user.Address     = model.Address;
                     user.Phone       = model.Phone;
                     user.GroupID     = "CLIENT";
                     user.Status      = true;
                     data.insert(user);
                     SetAlert("Dang ky thanh cong", "success");
                     return(RedirectToAction("Login", "Login"));
                 }
                 else
                 {
                     ViewBag.ThongBao = "Mật khẩu phải chứa ít nhất một chữ in hoa và có ít nhất 6 ký tự";
                 }
             }
             else
             {
                 ViewBag.ThongBao = "Mật khẩu không khớp";
             }
         }
         else
         {
             ViewBag.ThongBao = "Tài khoản đã tồn tại";
         }
     }
     MvcCaptcha.ResetCaptcha("registerCaptcha");
     return(View());
 }
コード例 #22
0
ファイル: NavController.cs プロジェクト: drobotjv/Uh365898_db
        public ActionResult Question(Guestbook guestbookID, string actName)
        {
            logger.Error("Форма вопрос технологу - отправка вопроса");

            if (ModelState.IsValid)
            {
                actName = "Вопросы";
                guestbookID.DateAdded = DateTime.Now;
                repository.SaveGuestbook(guestbookID);
                MvcCaptcha.ResetCaptcha("SampleCaptcha");
                TempData["message"] = string.Format("{0}, Ваше сообщение отправлено", guestbookID.Name);

                //[email protected]
                MailAddress fromMailAddress = new MailAddress("*****@*****.**", "UPR");
                // MailAddress toAddress = new MailAddress("*****@*****.**", "Tom");
                MailAddress toAddress = new MailAddress("*****@*****.**", "UPR");
                using (MailMessage mailMessage = new MailMessage(fromMailAddress, toAddress))
                    using (SmtpClient smtpClient = new SmtpClient())
                    {
                        mailMessage.Subject = "Вопрос технологу c сайта upr.kh.ua";


                        mailMessage.Body = "Тема сообщения: " + guestbookID.Name.ToString() + "\r" +
                                           "Дата: " + guestbookID.DateAdded.ToString() + "\r" +
                                           "Сообщение: " + guestbookID.Message.ToString() + "\r";

                        smtpClient.Host                  = "smtp.gmail.com";
                        smtpClient.Port                  = 587;
                        smtpClient.EnableSsl             = true;
                        smtpClient.DeliveryMethod        = SmtpDeliveryMethod.Network;
                        smtpClient.UseDefaultCredentials = false;
                        smtpClient.Credentials           = new NetworkCredential(fromMailAddress.Address, "1234567upr");

                        smtpClient.Send(mailMessage);
                    }



                return(RedirectToAction("Question", guestbookID));
            }
            else
            {
                return(View());
            }
        }
コード例 #23
0
        public ActionResult Index(CaptchaViewModel model)
        {
            string msg = null;

            if (!ModelState.IsValid)
            {
                msg = string.Join(";", ModelState.Values.SelectMany(e => e.Errors).Select(gh => gh.ErrorMessage));
            }
            else
            {
                msg = "驗證成功!";
                //重啟Captcha
                MvcCaptcha.ResetCaptcha("ExampleCaptcha");
            }
            TempData["msg"] = msg;

            return(RedirectToAction(nameof(this.Index)));
        }
コード例 #24
0
 public ActionResult Register(RegisterModel model)
 {
     if (ModelState.IsValid)
     {
         var dao = new UserDAO();
         //validate them
         if (dao.CheckUserName(model.UserName))
         {
             ModelState.AddModelError("", "Tài khoản đã tồn tại");
         }
         else if (dao.CheckEmail(model.Email))
         {
             ModelState.AddModelError("", "Email đã tồn tại");
         }
         else
         {
             //tao user
             var user = new User()
             {
                 UserName    = model.UserName,
                 Password    = Encryptor.MD5Hash(model.Password),
                 Email       = model.Email,
                 Name        = model.Name,
                 Address     = model.Address,
                 Phone       = model.Phone,
                 CreatedDate = DateTime.Now,
                 Status      = true,
                 ProvinceID  = model.ProvinceID,
                 DistrictID  = model.DistrictID,
             };
             var result = dao.Insert(user);
             if (result > 0)
             {
                 SetAlert("Đăng ký thành công", "success");
             }
             else
             {
                 ModelState.AddModelError("", "Có lỗi xảy ra, thử lại sau");
             }
         }
     }
     MvcCaptcha.ResetCaptcha("ExampleCaptcha");
     return(View(model));
 }
コード例 #25
0
        public bool CheckCaptcha(string userInput)
        {
            // init mvcCaptcha instance with captchaId
            MvcCaptcha mvcCaptcha = new MvcCaptcha("CaptchaCode");

            if (mvcCaptcha.Validate(userInput))
            {
                // TODO: captcha validation succeeded; execute the protected action

                // Reset the captcha if your app's workflow continues with the same view
                MvcCaptcha.ResetCaptcha("CaptchaCode");
                return(true);
            }
            else
            {
                ModelState.AddModelError("", "Mã Captcha không đúng!");
            }
            return(false);
        }
コード例 #26
0
        public ActionResult Reverify(ReverifyViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (_authRepository.AlreadyExists(model.Email))
                {
                    var token     = AuthEncryption.RandomSalt(6);
                    var result    = _authRepository.SetEmailConfirmationToken(model.Email, token);
                    var secureUrl = Url.Action("ConfirmEmail", "Account", new { e = model.Email, c = token }, "https");
                    //var linkUrl = Url.AbsoluteAction("ConfirmEmail", "Account", new { e = model.Email, c = token });
                    string mailBody = MailCommonStrings.RegisteredBody(secureUrl);
                    Mailer.SendEmail_NoWait(model.Email, MailCommonStrings.RegisteredSubject, mailBody);
                    _logger.Debug(string.Format("{0} has requested another verification email from {1}", model.Email, ClientIpAddress.GetIPAddress(Request)));
                }
                MvcCaptcha.ResetCaptcha("ReverifyCaptcha");
                return(RedirectToAction("ReverificationSent"));
            }

            return(View());
        }
コード例 #27
0
        public ActionResult Contact(ContactCaptcha contactCaptcha)
        {
            Contact contact = new Contact();

            if (ModelState.IsValid)
            {
                contact.Name       = contactCaptcha.Name;
                contact.Email      = contactCaptcha.Email;
                contact.Address    = contactCaptcha.Address;
                contact.Phone      = contactCaptcha.Phone;
                contact.Request    = contactCaptcha.Request;
                contact.CreateDate = DateTime.Now;

                var db = DataProvider.GetInstance();
                db.Contacts.Add(contact);
                db.SaveChanges();

                ViewBag.Success = "Success!";

                MvcCaptcha.ResetCaptcha("ContactCaptcha");

                string content = System.IO.File.ReadAllText(Server.MapPath("~/Views/Shared/NewContact.html"));

                content = content.Replace("{{Name}}", contact.Name);
                content = content.Replace("{{Email}}", contact.Email);
                content = content.Replace("{{Phone}}", contact.Phone);
                content = content.Replace("{{Address}}", contact.Address);
                content = content.Replace("{{Request}}", contact.Request);
                content = content.Replace("{{CreateDate}}", contact.CreateDate.ToString());

                var mailHelper = new MailHelper();
                mailHelper.SendMail(contact.Email, "Send contact success", content);
                var toEmail = ConfigurationManager.AppSettings["ToEmailAddress"].ToString();
                mailHelper.SendMail(toEmail, "New Contact", content);

                return(View());
            }


            return(View(contactCaptcha));
        }
コード例 #28
0
 public ActionResult Register(RegisterModel model)
 {
     if (ModelState.IsValid)
     {
         var dao = new UserDao();
         if (dao.CheckUserName(model.UserName))
         {
             ModelState.AddModelError("", "Tên đăng nhập đã tồn tại");
         }
         else if (dao.CheckEmail(model.Email))
         {
             ModelState.AddModelError("", "Email đã tồn tại");
         }
         else
         {
             var user = new User();
             user.UserName   = model.UserName;
             user.Password   = Encryptor.MD5Hash(model.Password);
             user.GroupID    = "MEMBER";
             user.Name       = model.Name;
             user.Phone      = model.Phone;
             user.Email      = model.Email;
             user.Address    = model.Address;
             user.CreateDate = DateTime.Now;
             user.Status     = true;
             var result = dao.Insert(user);
             if (result > 0)
             {
                 ViewBag.Success = "Đăng ký thành công";
                 MvcCaptcha.ResetCaptcha("registerCapcha");
                 model = new RegisterModel();
                 ModelState.Clear();
             }
             else
             {
                 ModelState.AddModelError("", "Đăng ký không thành công");
             }
         }
     }
     return(View());
 }
コード例 #29
0
        public ActionResult ForgotPassword(ForgotPasswordViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (_authRepository.AlreadyExists(model.Email))
                {
                    var token     = AuthEncryption.RandomSalt(6);
                    var result    = _authRepository.SetPasswordResetToken(model.Email, token);
                    var userIp    = ClientIpAddress.GetIPAddress(Request);
                    var secureUrl = Url.Action("TryResetPassword", "Account", new { e = model.Email, c = token }, "https");
                    //var linkUrl = Url.AbsoluteAction("TryResetPassword", "Account", new { e = model.Email, c = token });
                    string mailBody = MailCommonStrings.PasswordResetBody(userIp, secureUrl);
                    Mailer.SendEmail_NoWait(model.Email, MailCommonStrings.ResetPasswordSubject, mailBody);
                    _logger.Debug(string.Format("{0} has requested to reset their password from {1}", model.Email, ClientIpAddress.GetIPAddress(Request)));
                }
                MvcCaptcha.ResetCaptcha("ResetPasswordCaptcha");
                return(RedirectToAction("PasswordResetSent"));
            }

            return(View());
        }
コード例 #30
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //A falg if the user captcha code is correc
            bool validCaptcha = false;

            //Try to get the model from the request
            if (filterContext.ActionArguments != null && filterContext.ActionArguments.TryGetValue("model", out object data))
            {
                //If the data is the same type or derived from baseviewmodel
                if (data is BaseViewModel)
                {
                    if (((dynamic)data).Captcha is CaptchaModel captcha)
                    {
                        MvcCaptcha mvcCaptcha = new MvcCaptcha(CaptchaId);

                        if (mvcCaptcha.Validate(captcha.CaptchaCode))
                        {
                            MvcCaptcha.ResetCaptcha(CaptchaId);

                            validCaptcha = true;
                        }
                    }
                }
            }

            //If not vaild then add the error to the model state
            if (!validCaptcha)
            {
                //Clear the erros
                filterContext.ModelState.Clear();
                //Add only the captcha
                filterContext.ModelState.TryAddModelError("Capatcha", ErrorMessage);
            }

            base.OnActionExecuting(filterContext);
        }