Ejemplo n.º 1
0
        public ActionResult SelectionSetting(string level_1_id /*selection_id*/, string board_list)
        {
            if (!Util.IsAjaxRequest(Request))
            {
                Util.ThrowBadRequestException("Not ajax post.");
            }
            if (!ReCaptcha.Validate())
            {
                Util.ThrowBadRequestException("驗證碼不正確。");
            }

            int cnt = SandId.CountBoardList(board_list);

            if (cnt == -1)
            {
                Util.ThrowBadRequestException("留言板ID格式不正確。");
            }
            else if (cnt == 0)
            {
                Util.ThrowBadRequestException("未包含任何留言板ID。");
            }
            else if (cnt > HeartsConfiguration.MAX_NUM_OF_BOARDS_IN_A_SELECTION)
            {
                Util.ThrowBadRequestException("留言板數量超過" + HeartsConfiguration.MAX_NUM_OF_BOARDS_IN_A_SELECTION + "個。");
            }

            SelectionInfoStore.SetSelectionSetting(level_1_id, board_list);

            return(Json(new { ok = true }));
        }
Ejemplo n.º 2
0
    protected void send_ticket(object sender, EventArgs e)
    {
        var           encodedResponse  = Request.Form["g-Recaptcha-Response"];
        var           isCaptchaValid   = ReCaptcha.Validate(encodedResponse);
        var           connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        SqlConnection connection       = new SqlConnection(connectionString);

        connection.Open();
        if (isCaptchaValid)
        {
            try
            {
                if (connection.State == ConnectionState.Open)
                {
                    string     query = "INSERT INTO [dbo].[Ticket]([TManagerID],[Email],[Subject],[Description],[Date],[category]) VALUES(" + 1 + ",'" + email.Text + "','" + konu.Text + "','" + aciklama.Text + "','" + dateTime.ToShortDateString() + "','" + kategori.SelectedItem + "')";
                    SqlCommand cmd   = new SqlCommand(query, connection);
                    cmd.ExecuteNonQuery();
                    errorbox.Text = "Başarıyla Gönderildi.";
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex);
                errorbox.Text = "Başarıyla Gönderilmedi.";
                goto close;
            }
        }
        else
        {
            errorbox.Text = "Başarıyla Gönderilmedi.";
        }

close:
        connection.Close();
    }
Ejemplo n.º 3
0
        public ActionResult Contact(ContactPageModel model)
        {
            if (!ReCaptcha.Validate(DataUtils.GetConfig("reCaptcha:SecretKey")))
            {
                ModelState.AddModelError("", "Captcha cannot be empty");
            }

            if (ModelState.IsValid)
            {
                EMail mail = new EMail()
                {
                    Name        = model.Name,
                    SenderEmail = model.EmailAddress,
                    Body        = model.Message,
                    ToAddress   = model.EmailAddressTo,
                    Subject     = "New message",
                    IsHtml      = true
                };

                EmailUtils.SendEmail(mail);

                return(Redirect($"/{CurrentUser.LanguageCode}/contact/confirm-contact/"));
            }
            return(CurrentUmbracoPage());
        }
        public ActionResult Feedback(FeedbackModel feedback)
        {
            bool validRecaptcha = false;

            //check if user is logged in, if so set validRecaptcha to true as we don't want users having to use recap
            if (WebSecurity.IsAuthenticated)
            {
                validRecaptcha = true;
            }
            //else check the recap froma non logged in user and make sure it is ok before sending email.
            //TODO: reset recaptcha PRIVATE key here if domains change
            else if (ReCaptcha.Validate(privateKey: "6Ld_kt0SAAAAAAWadUrgyxHuqAlp2fjS5RXjdyn9"))
            {
                validRecaptcha = true;
            }

            if (validRecaptcha)
            {
                if (ModelState.IsValid)
                {
                    string      from    = feedback.Email;
                    string      to      = "*****@*****.**";
                    string      subject = "Feedback from WATW";
                    string      body    = feedback.Message;
                    MailMessage message = new MailMessage(from, to, subject, body);

                    SmtpClient client = new SmtpClient();
                    client.Send(message);

                    //TODO: http://stackoverflow.com/questions/10022498/setting-up-email-settings-in-appsettings-web-config
                }
                return(View());
            }
            return(View(feedback));
        }
Ejemplo n.º 5
0
 public ActionResult Register(User user)
 {
     if (ModelState.IsValid)
     {
         string encodedResponse = Request.Form["g-Recaptcha-Response"];
         bool   isCaptchaValid  = (ReCaptcha.Validate(encodedResponse) == "True");
         if (!isCaptchaValid)
         {
             TempData["recaptcha"] = "Please verify that you are not a robot";
             return(View());
         }
         using (MyDbContext db = new MyDbContext())
         {
             if (db.Users.FirstOrDefault(a => a.Username == user.Username) != null)
             {
                 ViewBag.ErrorMessage = "Username is taken." + Environment.NewLine;
                 return(View());
             }
             if (db.Users.FirstOrDefault(a => a.Email == user.Email) != null)
             {
                 ViewBag.ErrorMessage = "Email is taken." + Environment.NewLine;
                 return(View());
             }
             db.Users.Add(user);
             db.SaveChanges();
         }
         ModelState.Clear();
         ViewBag.Message = user.Username + " successfully registred.";
     }
     return(View());
 }
        public ActionResult SubmitContactUsForm(ContactUs model)
        {
            if (ModelState.IsValid)
            {
                string encodedResponse = Request.Form["g-Recaptcha-Response"];
                var    response        = ReCaptcha.Validate(encodedResponse, SensativeInformation.ReCaptchaKeys.ReCaptchaSecretKey);
                bool   isCaptchaValid  = response.ToLower() == "true"
                        ? true
                        : false;
                if (!isCaptchaValid)
                {
                    ModelState.AddModelError("", "Please verify you are not a robot");
                    return(CurrentUmbracoPage());
                }

                ContactUsEmailModel emailModel = new ContactUsEmailModel();
                emailModel.Info    = model;
                emailModel.BaseUri = UrlHelpers.GetBaseUrl();
                ViewData.Model     = emailModel;
                var html         = RazorHelpers.RenderRazorViewToString("~/Views/Emails/ContactUsEmail.cshtml", ControllerContext, ViewData, TempData);
                var emailService = new EmailService.EmailHelpers();
                emailService.SendEmail("*****@*****.**", "Query from contact form", html);
                TempData["Success"] = "That is winging its way to us now. We will be in contact as soon as we can.";
                return(RedirectToCurrentUmbracoPage());
            }
            return(CurrentUmbracoPage());
        }
 public ActionResult Index(ContactModel c)
 {
     if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
     {
         try
         {
             MailMessage   msg  = new MailMessage();
             SmtpClient    smtp = new SmtpClient();
             MailAddress   from = new MailAddress(c.Email.ToString());
             StringBuilder sb   = new StringBuilder();
             msg.To.Add("*****@*****.**");
             msg.Subject    = c.Subject;
             msg.IsBodyHtml = false;
             sb.Append("Name: " + c.Name);
             sb.Append(Environment.NewLine);
             sb.Append("Email: " + c.Email);
             sb.Append(Environment.NewLine);
             sb.Append(Environment.NewLine);
             sb.Append("Comments: " + c.Message);
             msg.Body = sb.ToString();
             smtp.Send(msg);
             msg.Dispose();
             return(View(c));
         }
         catch (Exception ex)
         {
             string msg = ex.ToString();
             return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
         }
     }
     return(View(c));
 }
Ejemplo n.º 8
0
        public RespuestaOperacionServicio AutenticarUsuario(UsuarioAuth data)
        {
            RespuestaOperacionServicio rpta      = new RespuestaOperacionServicio();
            RespuestaCerbero           respuesta = new RespuestaCerbero();

            try
            {
                string user    = data.user;
                string pass    = data.pass;
                string captcha = data.captcha;

                bool bValidacionCaptcha = ReCaptcha.Validate(captcha);
                if (!bValidacionCaptcha)
                {
                    rpta.Resultado = Constants.RESPUESTA_CAPTCHA_ERROR;
                    rpta.Error     = "La validación CAPTCHA no ha sido correcta.";
                    return(rpta);
                }

                CerberoResult resultValidate = CerberoService.ValidarVersion(Constants.CERBERO_SYSTEM_CODE, Constants.CERBERO_VERSION, Constants.CERBERO_TYPE_INFORMATION);

                if (resultValidate.respuesta == 1)
                {
                    CerberoResult resultAuntenticar = CerberoService.AutenticarUsuario(Constants.CERBERO_SYSTEM_CODE, user, pass, 0);

                    if (resultAuntenticar.respuesta == 1)
                    {
                        string tokenString = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}{1}{2}", user, DateTime.Now.Millisecond, DateTime.Now.ToShortTimeString())));

                        List <string>    opciones = resultAuntenticar.opciones.Split('|').ToList();
                        UsuarioRespuesta usuario  = new UsuarioRespuesta(user, tokenString, opciones);

                        RestDataResponse response = new RestDataResponse(user, tokenString, opciones, RestDataResponse.STATUS_OK, "Usuario logueado correctamente");
                        respuesta.response = response;

                        Usuarios ObjUsuario      = new Usuarios();
                        string   IDUsuarioPerfil = ObjUsuario.obtenerIdUsuario(respuesta.response.usuario.ToUpper());
                        respuesta.response.idUsuario = Convert.ToInt32(IDUsuarioPerfil.Split('|')[0]);
                        respuesta.response.perfil    = IDUsuarioPerfil.Split('|')[1];

                        rpta.Resultado = Constants.RESPUESTA_KERBERO_OK;
                        rpta.data      = respuesta;
                    }
                    else
                    {
                        throw new Exception(resultAuntenticar.mensaje);
                    }
                }
                else
                {
                    throw new Exception(resultValidate.mensaje);
                }
            }
            catch (Exception ex)
            {
                rpta.Resultado = Constants.RESPUESTA_KERBERO_ERROR;
                rpta.Error     = ex.Message;
            }
            return(rpta);
        }
Ejemplo n.º 9
0
        public ActionResult ConfirmResetAccount(ChangePasswordModel model)
        {
            ViewBag.Token = model.ConfirmationToken;
            ViewBag.User  = model.UserName;
            string recaptchaprivatekey = BgResources.Recaptcha_PrivateKeyHttp;

            try
            {
                if (!ReCaptcha.Validate(privateKey: recaptchaprivatekey))
                {
                    ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha);
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha_Key);
            }

            if (ModelState.IsValid)
            {
                if (CodeFirstSecurity.ResetPassword(model.ConfirmationToken, model.NewPassword))
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false);
                    return(RedirectToRoute("Default", new { controller = "Account", action = "ResetAccountSuccesfull" }));
                }
                else
                {
                    ModelState.AddModelError("", Resources.AppMessages.Error_ResetAccount);
                }
                ViewBag.Token    = model.ConfirmationToken;
                ViewBag.UserName = model.UserName;
            }
            return(View());
        }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        var encodedResponse = Request.Form["g-Recaptcha-Response"];
        var isCaptchaValid  = ReCaptcha.Validate(encodedResponse);

        if (!isCaptchaValid)
        {
            lblStatus.Text = "Lütfen Kodu Doğrulayınız!!";
        }
        else
        {
            string image = "x.jpg";
            if (FileUpload1.HasFile)
            {
                try
                {
                    string gui            = Guid.NewGuid().ToString();
                    string fileName       = FileUpload1.FileName;
                    string properFileName = gui + "-" + fileName;
                    FileUpload1.PostedFile.SaveAs(Server.MapPath("~/ProductImages/") + properFileName);
                    image = "/ProductImages/" + properFileName;
                }
                catch (Exception)
                {
                    throw;
                }
            }
            bool stat = CatalogAccess.CustomerSendMessage(txtName.Text, txtSurname.Text, txtEmail.Text, txtSubject.Text, image, txtText.Text);
            Response.Redirect("index.aspx?SendMessage=ok");
        }
    }
Ejemplo n.º 11
0
        public ActionResult UnSubscribe(UnsubscribeViewModel model)
        {
            string recaptchaprivatekey = BgResources.Recaptcha_PrivateKeyHttp;

            try
            {
                if (!ReCaptcha.Validate(privateKey: recaptchaprivatekey))
                {
                    ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha);
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha_Key);
            }
            if (ModelState.IsValid)
            {
                try
                {
                    SubscriptionServices.Unsubscribe(model.Email);
                }
                catch (ApplicationValidationErrorsException ex)
                {
                    foreach (string str in ex.ValidationErrors)
                    {
                        ModelState.AddModelError("", str);
                    }
                }
            }
            return(View());
        }
Ejemplo n.º 12
0
        public ActionResult RequestRecoverPassword(RequestRecoverPasswordModel requestRecoverPasswordModel)
        {
            if (!ReCaptcha.Validate(privateKey: "6LccQ-ISAAAAADW9ZY30RQnCWpCHCYUrNulK9JWz"))
            {
                ModelState.AddModelError("_FORM", "You did not type the verification word correctly. Please try again.");
            }

            if (ModelState.IsValid)
            {
                string passwordVerifiationToken = accountService.SelectPasswordVerifiationToken(requestRecoverPasswordModel.EmailAddress);
                string url = "http://www2.betteryinc.com/Account/RecoverPassword/" + passwordVerifiationToken;

                // Add any tokens you want to find/replace within your template file
                var tokens = new Dictionary <string, string>()
                {
                    { "##EMAILADDRESS##", requestRecoverPasswordModel.EmailAddress },
                    { "##URL##", url }
                };

                // Fetch template body from disk
                var template = TemplateHelper.GetEmailTemplate("http://www2.betteryinc.com/content/htmlpasswordrecovery.htm");
                //var template = TemplateHelper.GetEmailTemplate("http://127.0.0.1:444/content/htmlpasswordrecovery.htm");

                // Specify addresses (CC and BCC are optional)
                var to  = new MailAddress(requestRecoverPasswordModel.EmailAddress);
                var fr  = new MailAddress("*****@*****.**");
                var bcc = new MailAddress("*****@*****.**");
                // Send the mail
                TemplateHelper.Send(to, fr, bcc, "Thank you for using BETTERY", tokens, template, true);

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

            return(View());
        }
Ejemplo n.º 13
0
        public ActionResult Contact(ContactModel model, string ReturnUrl)
        {
            var privateKey = ConfigurationManager.AppSettings.Get("reCaptchaPrivateKey");

            if (ReCaptcha.Validate(privateKey))
            {
                bool result = _contactManager.AddNewContact(model.Name, model.Surname, model.Email, model.Message);

                if (result)
                {
                    TempData["Alert"] = SetAlert.Set("Dziękujemy za wiadomość!", "Sukces", AlertType.Success);

                    return(RedirectToLocal(ReturnUrl));
                }
                else
                {
                    TempData["Alert"] = SetAlert.Set("Wystąpił błąd, prosimy spróbwać ponownie później.", "Błąd", AlertType.Danger);

                    return(RedirectToAction("Contact"));
                }
            }
            else
            {
                TempData["Alert"] = SetAlert.Set("Musisz udowodnić że nie jesteś robotem poprzez captcha!", "Błąd", AlertType.Danger);
                return(View());
            }
        }
Ejemplo n.º 14
0
        public async Task <ActionResult> Contact([Bind(Include = "customerName,emailAddress,contactNumber,message")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                string EncodedResponse = Request.Form["g-Recaptcha-Response"];
                bool   IsCaptchaValid  = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
                if (IsCaptchaValid)
                {
                    //send email
                    var    body        = "<p>Name: {0}</p><p>Email address: {1}</p><p>Contact number: {2}</p><p>Message: {3}</p>";
                    string messageBody = string.Format(body, contact.customerName.ToString(), contact.emailAddress.ToString(), contact.contactNumber.ToString(), contact.message.ToString());
                    string to          = "*****@*****.**";
                    string from        = "*****@*****.**";
                    string subject     = "PC Plumbing Online Enquiry";

                    await SendMessage(to, from, messageBody, subject);

                    return(RedirectToAction("Contact", new { success = "Your message has been sent to PC Plumbing" }));
                }
                else
                {
                    TempData["recaptcha"] = "Please verify that you are not a robot";
                }
            }

            return(View(contact));
        }
Ejemplo n.º 15
0
        public ActionResult HandleContactUs(ContactPageModel model)
        {
            if (!ReCaptcha.Validate(DataUtils.GetConfig("ReCaptcha:SecretKey")))
            {
                ModelState.AddModelError("", "Captcha cannot be empty");
            }

            if (ModelState.IsValid)
            {
                EMail mail = new EMail()
                {
                    Name        = model.Name,
                    SenderEmail = model.EmailAddress,
                    Body        = model.Message,
                    ToAddress   = SnuffoSettings.Create(model.Content).SupportEmail,
                    Subject     = model.Subject,
                    IsHtml      = true
                };

                EmailUtils.SendEmail(mail);

                return(Redirect($"/{CurrentUser.LanguageCode}/contact/submitted"));
            }

            return(CurrentUmbracoPage());
        }
Ejemplo n.º 16
0
        public ActionResult CreateSelection(string selection_name)
        {
            if (!Util.IsAjaxRequest(Request))
            {
                Util.ThrowBadRequestException("Not ajax post.");
            }

            if (!ReCaptcha.Validate())
            {
                Util.ThrowBadRequestException("驗證碼不正確。");
            }

            if (selection_name.Length < HeartsConfiguration.BOARD_NAME_FIELD_MIN_LEN)
            {
                Util.ThrowBadRequestException("區域名長度過短。");
            }
            else if (selection_name.Length > HeartsConfiguration.BOARD_NAME_FIELD_MAX_LEN)
            {
                Util.ThrowBadRequestException("區域名長度過長。");
            }
            else if (!Util.WithinCharSetUserName(selection_name))
            {
                Util.ThrowBadRequestException("區域名含有不合法的字元。");
            }
            else if (selection_name == "RETURN_FAIL")
            {
                Util.ThrowBadRequestException("區域名為RETURN_FAIL。");
            }

            string selection_id = SelectionInfoStore.CreateSelection(selection_name + '區');

            return(Json(new { selection_id = selection_id }));
        }
Ejemplo n.º 17
0
        public ActionResult Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
#if DEBUG
                if (true)
#else
                if (ReCaptcha.Validate(ReCaptchaPrivateKey))
#endif
                {
                    if (_dbContext.Users.Any(x => x.Email == model.Email))
                    {
                        ModelState.AddModelError(string.Empty, Messages.EMAIL_ALREADY_EXISTS);
                    }
                    else
                    {
                        WebSecurity.CreateUserAndAccount(model.Email, model.Password);
                        WebSecurity.Login(model.Email, model.Password, false);

                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError(string.Empty, Messages.RECAPTCHA_INVALID);
                }
            }

            return(View(model));
        }
Ejemplo n.º 18
0
        public ActionResult Login(LoginViewModel lvm)
        {
            if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
            {
                string userToken = MVCUtils.GetUserToken(lvm.Email, lvm.Psw);

                if (userToken != null)
                {
                    Session["userToken"] = userToken;

                    HttpClient client = MVCUtils.GetClient("");
                    client = MVCUtils.GetClient(Session["userToken"].ToString());
                    ApplicationUserViewModel appUser = JsonConvert.DeserializeObject <ApplicationUserViewModel>(client.GetStringAsync("api/ApplicationUser/GetLoggedUser").Result);

                    Session["userId"]    = appUser.Id;
                    Session["userPhoto"] = appUser.ImgUrl;
                    Session["userName"]  = appUser.UserName;
                    return(RedirectToAction("Home", "User"));
                }

                ViewBag.Message   = "Senha incorreta ou usuário não encontrado";
                ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                return(View(lvm));
            }

            ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);
            ViewBag.publicKey           = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];

            return(View());
        }
Ejemplo n.º 19
0
        public ActionResult CheckUserModel(UserModel viewModel)
        {
            //Checks if the user is valid and has agreed to the terms and validated the captcha
            if (viewModel.Agreement && ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
            {
                UserDTO userDTO = new UserDTO
                {
                    Password     = ComputeHash(viewModel.Password),    //Put Hash of password in the database
                    SecretAnswer = ComputeHash(viewModel.SecretAnswer) //Put Hash of secret answer in the database
                };
                foreach (PropertyInfo property in userDTO.GetType()
                         .GetProperties()
                         .Where(property => property.Name != "ID" && property.Name != "Password" && property.Name != "SecretAnswer"))
                {
                    property.SetValue(userDTO, viewModel.GetType().GetProperty(property.Name).GetValue(viewModel).ToString());
                }

                //Submits the user to the database via the service
                _service.Insert(userDTO);

                return(View());
            }
            //User info was not valid, so the model is stored and you are prompted to create the user
            else
            {
                ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);

                ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];

                TempData["agreement"] = "You have not agreed to our terms and conditions";
                TempData["userModel"] = viewModel;
                return(RedirectToAction("Create"));
            }
        }
Ejemplo n.º 20
0
        public virtual async Task <ActionResult> Index(ContactUsModel model)
        {
            if (CurrentSettings.UseGoogleRecaptchaForContactUs)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;
                if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                {
                    ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                    return(View(model));
                }
            }

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

            await _userMessagingService.AddAsync(new TblUserMessages()
            {
                Email       = model.Email,
                Message     = model.Message,
                Name        = model.Name,
                ReceiveDate = DateTime.Now,
                Subject     = model.Subject,
                UserId      = WorkContext.CurrentUser?.Id
            });

            SuccessNotification(_localizationService.GetResource("YourMessageHasBeenReceived"));

            return(RedirectToAction("Index"));
        }
Ejemplo n.º 21
0
        public virtual async Task <ActionResult> ResetPassword(ResetPasswordModel model)
        {
            var currentLanguage = WorkContext.CurrentLanguage;

            model.Settings        = CurrentSettings;
            model.CurrentLanguage = currentLanguage;

            if (CurrentSettings.UseGoogleRecaptchaForResetPassword && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;


                if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts)
                {
                    if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                    {
                        IncreaseFailedAttempts();
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                        return(View(model));
                    }
                }
            }

            if (ModelState.IsValid)
            {
                var user = await UserManager.FindByIdAsync(model.UserId);

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    IncreaseFailedAttempts();
                    ModelState.AddModelError("Email", _localizationService.GetResource("UserNotExist"));
                    return(View(model));
                }

                var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

                if (result.Succeeded)
                {
                    EventPublisher.Publish(new UserResetPasswordEvent(user));
                    return(View("ResetPasswordConfirmation"));
                }

                foreach (var error in result.Errors)
                {
                    if (error.ToLower().Trim() == "Invalid token.".ToLower())
                    {
                        ModelState.AddModelError("", _localizationService.GetResource("InvalidToken"));
                    }
                    else
                    {
                        ModelState.AddModelError("", error);
                    }
                }
            }

            IncreaseFailedAttempts();
            return(View(model));
        }
Ejemplo n.º 22
0
        public void ValidateReturnsFalseWhenChallengeNotPosted()
        {
            HttpContextBase context = GetContext();

            context.Request.ServerVariables["REMOTE_ADDR"] = "127.0.0.1";

            Assert.IsFalse(ReCaptcha.Validate(context, privateKey: "PRIVATE_KEY"));
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            bool isValid = ReCaptcha.Validate(privateKey: "6LeJ0sASAAAAAMs9p7y2-3HtYkHIC3_IpGkVIXMq");

            filterContext.ActionParameters["captchaValid"] = isValid;

            base.OnActionExecuting(filterContext);
        }
Ejemplo n.º 24
0
        public ActionResult Register(RegisterModel model)
        {
            string recaptchaprivatekey = BgResources.Recaptcha_PrivateKeyHttp;

            try
            {
                if (!ReCaptcha.Validate(privateKey: recaptchaprivatekey))
                {
                    ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha);
                }
            }
            catch (Exception)
            {
                ModelState.AddModelError("recaptcha", Resources.AppMessages.Error_Recaptcha_Key);
            }

            if (ModelState.IsValid)
            {
                string token = null;
                try
                {
                    token = CodeFirstSecurity.CreateAccount(model.UserName, model.Password, model.Email, model.FirstName, model.LastName, model.TimeZone, model.Culture, requireConfirmationToken: true);
                    SmtpClient client = new SmtpClient {
                        Host = BgResources.Email_Server, Port = Int32.Parse(BgResources.Email_SmtpPort), EnableSsl = BgResources.Email_SSL, Credentials = new NetworkCredential(BgResources.Email_UserName, BgResources.Email_Password)
                    };
                    UserMailer.Register(token, model.Email, AccountServices.FindUser(usr => usr.Username == model.UserName)).Send(new SmtpClientWrapper {
                        InnerSmtpClient = client
                    });
                    ViewBag.Email = model.Email;
                    return(View("CompleteRegister"));
                }
                catch (MembershipCreateUserException ex)
                {
                    if ((ex.StatusCode == MembershipCreateStatus.DuplicateUserName) || (ex.StatusCode == MembershipCreateStatus.InvalidUserName))
                    {
                        ModelState.AddModelError("UserName", ErrorCodeToString(ex.StatusCode));
                    }
                    else if ((ex.StatusCode == MembershipCreateStatus.DuplicateEmail) || (ex.StatusCode == MembershipCreateStatus.InvalidEmail))
                    {
                        ModelState.AddModelError("Email", ErrorCodeToString(ex.StatusCode));
                    }
                    else if (ex.StatusCode == MembershipCreateStatus.InvalidPassword)
                    {
                        ModelState.AddModelError("Password", ErrorCodeToString(ex.StatusCode));
                    }
                    else
                    {
                        ModelState.AddModelError("", ErrorCodeToString(ex.StatusCode));
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(Resources.AppMessages.Error_SendMail);
                }
            }
            return(View(model));
        }
Ejemplo n.º 25
0
        public ActionResult Create(RegisterModel model)
        {
            string restrictedErr = "Sorry, access from your host is restricted. It is possible this restriction is no longer valid. If you think this is the case, please contact support.";

            if (!ModelState.IsValidField("Extra"))
            {
                log.Warn(string.Format("An attempt was made to fill the bot decoy field from {0}.", Hostname));
                ipRuleManager.TempBannedIPs.Add(Hostname);
                return(View(model));
            }

            if (config.SiteSettings.SignupsDisabled)
            {
                ModelState.AddModelError(string.Empty, "Signups are disabled");
            }

            if (!ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCAPTCHAKey"]))
            {
                var captchaResponse = Request.Params["recaptcha_response_field"] ?? string.Empty;
                ErrorLogger.LogMessage(Request, string.Format("Invalid CAPTCHA (response was {0})", captchaResponse), LogLevel.Warn);
                otherService.AuditLog("failed CAPTCHA", Hostname, AuditLogCategory.UserCreateFailCaptcha);
                ModelState.AddModelError("CAPTCHA", ViewRes.User.CreateStrings.CaptchaInvalid);
            }

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

            if (!ipRuleManager.IsAllowed(Hostname))
            {
                ModelState.AddModelError("Restricted", restrictedErr);
                return(View(model));
            }

            var time = TimeSpan.FromTicks(DateTime.Now.Ticks - model.EntryTime);

            // Attempt to register the user
            try {
                var url  = VocaUriBuilder.CreateAbsolute(Url.Action("VerifyEmail", "User")).ToString();
                var user = Data.Create(model.UserName, model.Password, model.Email ?? string.Empty, Hostname, time, ipRuleManager.TempBannedIPs, url);
                FormsAuthentication.SetAuthCookie(user.Name, false);
                return(RedirectToAction("Index", "Home"));
            } catch (UserNameAlreadyExistsException) {
                ModelState.AddModelError("UserName", ViewRes.User.CreateStrings.UsernameTaken);
                return(View(model));
            } catch (UserEmailAlreadyExistsException) {
                ModelState.AddModelError("Email", ViewRes.User.CreateStrings.EmailTaken);
                return(View(model));
            } catch (InvalidEmailFormatException) {
                ModelState.AddModelError("Email", ViewRes.User.MySettingsStrings.InvalidEmail);
                return(View(model));
            } catch (TooFastRegistrationException) {
                ModelState.AddModelError("Restricted", restrictedErr);
                return(View(model));
            }
        }
Ejemplo n.º 26
0
        public void ValidateThrowsWhenRemoteAddressNotAvailable()
        {
            HttpContextBase        context            = GetContext();
            VirtualPathUtilityBase virtualPathUtility = GetVirtualPathUtility();

            context.Request.Form["recaptcha_challenge_field"] = "CHALLENGE";
            context.Request.Form["recaptcha_response_field"]  = "RESPONSE";

            Assert.Throws <InvalidOperationException>(() => { ReCaptcha.Validate(context, privateKey: "PRIVATE_KEY", virtualPathUtility: virtualPathUtility).ToString(); }, "The captcha cannot be validated because the remote address was not found in the request.");
        }
Ejemplo n.º 27
0
    protected void SignIn_Click(object sender, EventArgs e)
    {
        var           encodedResponse  = Request.Form["g-Recaptcha-Response"];
        var           isCaptchaValid   = ReCaptcha.Validate(encodedResponse);
        var           connectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
        SqlConnection connection       = new SqlConnection(connectionString);

        connection.Open();


        //int ceptelnoInt = 0; Int64.TryParse(ceptelno.Text, out ceptelnoInt);
        //int IDInt = 0; Int64.TryParse(tcno.Text, out IDInt);
        string query;
        string queryInsert = "INSERT INTO [dbo].[User]([Username],[UserPassword],[UserType],[Name],[Surname],[Email],[Phone],[Address],[BDate],[IBAN],[UserPicture],[Annotation],[IDNumber])";

        if (isCaptchaValid)
        {
            try
            {
                if (connection.State == ConnectionState.Open && sozlesme.Checked)
                {
                    string queryValues = " VALUES('" + kullanici_adi.Text + "','" + parola.Text + "'," + tur.SelectedValue + ",'" + isim.Text + "','" + soyisim.Text + "','" + email.Text + "','" + ceptelno.Text + "','" + adres.Text + "','" + dogum_tarihi.Text + "','" + IBAN.Text + "',NULL,NULL,";
                    query = queryInsert + queryValues;
                    if (tcno.Text == "")
                    {
                        query += "NULL)";
                    }
                    else
                    {
                        query += "'" + tcno.Text + "')";
                    }

                    SqlCommand cmd = new SqlCommand(query, connection);
                    cmd.ExecuteNonQuery();
                    errorbox.Text = "Başarıyla kayıt olundu.";
                }
                else
                {
                    errorbox.Text = "Başarıyla kayıt olunmadı.";
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex);
            }
        }
        else
        {
            errorbox.Text = "Başarıyla kayıt olunmadı.";
        }

        connection.Close();
    }
Ejemplo n.º 28
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            try
            {
                if (ModelState.IsValid && ReCaptcha.Validate(ConfigurationManager.AppSettings["ReCaptcha:SecretKey"]))
                {
                    if (!ModelState.IsValid)
                    {
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);
                        ViewBag.publicKey           = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];

                        ViewBag.ReturnUrl = returnUrl;
                        return(View(model));
                    }

                    // 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, false);

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

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

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

                    case SignInStatus.Failure:
                    default:
                        ModelState.AddModelError("", "Invalid login attempt.");
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);
                        ViewBag.publicKey           = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                        ViewBag.ReturnUrl           = returnUrl;
                        return(View(model));
                    }
                }

                ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(this.HttpContext);

                ViewBag.publicKey = ConfigurationManager.AppSettings["ReCaptcha:SiteKey"];
                return(View(model));
            }
            catch (Exception)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.InternalServerError));
            }
        }
Ejemplo n.º 29
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            var privateKey = ConfigurationManager.AppSettings.Get("reCaptchaPrivateKey");

            //sprawdzanie poprawności
            if (ReCaptcha.Validate(privateKey))
            {
                if (ModelState.IsValid)
                {
                    //rejestracja
                    var user = new ApplicationUser
                    {
                        UserName    = model.Email,
                        Email       = model.Email,
                        FirstName   = model.Name,
                        LastName    = model.Surname,
                        PhoneNumber = model.UserPhone,
                        City        = model.UserCity,
                        HouseNumber = model.UserHouseNumber,
                        PostalCode  = model.UserPostalCode,
                        Street      = model.UserStreet
                    };
                    var result = await UserManager.CreateAsync(user, model.Password);

                    await UserManager.AddToRoleAsync(user.Id, "User");

                    UserManager.CreateSchool(user.Id, model.SchoolName, model.SchoolClass, model.SchoolCity, model.SchoolHouseNumber,
                                             model.SchoolPostalCode, model.CounselorFirstName, model.CounselorLastName, model.SchoolStreet, model.SchoolPhone);

                    //operacje po rejestracji
                    if (result.Succeeded)
                    {
                        await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                        TempData["Alert"] = SetAlert.Set("Dziękujemy za rejestrację w serwisie!", "Sukces", AlertType.Success);

                        // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
                        // Send an email with this link
                        string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);

                        var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        await UserManager.SendEmailAsync(user.Id, "Potwierdzenie rejestracji konta w SAP", "Potwierdź swój email klikająć <a href=\"" + callbackUrl + "\">tutaj</a>");

                        return(RedirectToLocal(callbackUrl));
                    }
                    AddErrors(result);
                }
            }

            return(View(model));
        }
Ejemplo n.º 30
0
        public virtual async Task <ActionResult> ForgotPassword(ForgotPasswordModel model)
        {
            var currentLanguage = WorkContext.CurrentLanguage;

            model.Settings        = CurrentSettings;
            model.CurrentLanguage = currentLanguage;

            if (CurrentSettings.UseGoogleRecaptchaForResetPassword && CurrentSettings.ShowRecaptchaAfterNFailedAttempt - 1 <= FailedAttempts)
            {
                ViewBag.publicKey = CurrentSettings.GoogleRecaptchaSiteKey;


                if (CurrentSettings.ShowRecaptchaAfterNFailedAttempt <= FailedAttempts)
                {
                    if (!ReCaptcha.Validate(CurrentSettings.GoogleRecaptchaSecretKey))
                    {
                        IncreaseFailedAttempts();
                        ViewBag.RecaptchaLastErrors = ReCaptcha.GetLastErrors(HttpContext);
                        return(View(model));
                    }
                }
            }

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

                if (user == null)
                {
                    // Don't reveal that the user does not exist or is not confirmed
                    IncreaseFailedAttempts();
                    ModelState.AddModelError("Email", _localizationService.GetResource("UserNotExist"));
                    return(View(model));
                }

                var code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);

                var callbackUrl = Url.Action("ResetPassword", "User", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                await _emailService.SendEmailFromTemplateAsync("ResetPassword", _localizationService.GetResource("ResetPassword"), model.Email, new
                {
                    Url          = callbackUrl,
                    UserFullName = user.FirstName + " " + user.LastName
                });

                return(View("ForgotPasswordConfirmation"));
            }

            // If we got this far, something failed, redisplay form
            IncreaseFailedAttempts();
            return(View(model));
        }