Example #1
0
        public ActionResult CreateByTopic(int id, [Bind(Include = "QuoteId,TopicId,QuoteText,QuoteAuthor,QuotePassword")] Quotes quotes)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("", "Shit's fried mate");
            }
            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                ModelState.AddModelError("", "Incorrect captcha answer.");
            }
            quotes.TopicId = id;
            if (ModelState.IsValid)
            {
                db.Quotes.Add(quotes);
                db.SaveChanges();
                return(RedirectToAction("Index"));
            }

            ViewBag.TopicId = new SelectList(db.Topics, "TopicId", "TopicName", quotes.TopicId);
            return(View(quotes));
        }
Example #2
0
        public ActionResult SubmitForm(Contact model)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA");
                return(CurrentUmbracoPage());
            }
            else
            {
                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                    return(CurrentUmbracoPage());
                }
            }

            if (ModelState.IsValid)
            {
                //Process the valid form

                SendEmail(model);
                TempData["ContactSuccess"] = true;
                return(RedirectToCurrentUmbracoPage());
            }
            return(CurrentUmbracoPage());
        }
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!string.IsNullOrEmpty(_publicKey) && !string.IsNullOrEmpty(_privateKey))
            {
                var localizedResourceService = HostContainer.GetInstance <ILocalizedResourceService>();

                var controller = (Controller)HttpContext.Current.Items[FrameworkConstants.EzCurrentController];
                RecaptchaVerificationHelper recaptchaHelper = controller.GetRecaptchaVerificationHelper(_privateKey);

                if (string.IsNullOrEmpty(recaptchaHelper.Response))
                {
                    filterContext.Controller.ViewData.ModelState.AddModelError(Name,
                                                                               localizedResourceService.T("CaptchaValidation_Message_EmptyCaptcha"));
                }
                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    filterContext.Controller.ViewData.ModelState.AddModelError(Name,
                                                                               localizedResourceService.T("CaptchaValidation_Message_InvalidCaptchaAnswer"));
                }
            }

            base.OnActionExecuting(filterContext);
        }
Example #4
0
        public async Task <ActionResult> Feedback(FeedBackModel model)
        {
            try
            {
                RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

                if (String.IsNullOrEmpty(recaptchaHelper.Response))
                {
                    TempData["FeedbackStatus"]  = false;
                    TempData["FeedbackMessage"] = "Vui lòng nhập mã bảo mật bên dưới.";
                    return(Redirect(Request.UrlReferrer.AbsoluteUri));
                }

                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    TempData["FeedbackStatus"]  = false;
                    TempData["FeedbackMessage"] = "Vui lòng nhập lại mã bảo mật bên dưới.";
                    return(Redirect(Request.UrlReferrer.AbsoluteUri));
                }
                TempData["FeedbackStatus"] = model.InsertNewFeedback();
                return(Redirect(Request.UrlReferrer.AbsoluteUri));
            }
            catch (Exception exception)
            {
                LoggingUtil.LogException(exception);
                return(RedirectToAction(Constants.SystemFailureHomeAction, Constants.ErrorController));
            }
        }
Example #5
0
        public ActionResult SubmitContactForm(ContactFormModel model) //Use ActionResult to handle the user interaction
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            //Check if reCAPTCHA has a result
            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA");
                return(CurrentUmbracoPage());

                /* If it's an USkinned Umbraco Site:
                 *  return JavaScript("$('#recaptchaErrorMsg').show();$('#recaptchaErrorMsg').html('The reCAPTCHA field is required.');");
                 */
            }
            else
            {
                //Check if reCAPTCHA has a success result
                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect!");
                    return(CurrentUmbracoPage());

                    /* If it's an USkinned Umbraco Site:
                     *  return JavaScript("$('#recaptchaFailMsg').show();$('#recaptcahFailMsg').html('The reCAPTCHA is incorrect!');");
                     */
                }
            }

            //Check if the data posted is valid
            if (!ModelState.IsValid)
            {
                return(CurrentUmbracoPage());

                /* If it's an USkinned Umbraco Site:
                 *  return JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('{1}');", model.CurrentNodeID, HttpUtility.JavaScriptStringEncode(umbraco.library.GetDictionaryItem("USN Contact Form General Error"))));
                 */
            }

            string managerEmail = CurrentPage.HasValue("notifyEmail") ? CurrentPage.GetPropertyValue <string>("notifyEmail") : string.Empty;

            //Send email to manager
            SendNotificationToManager(model, managerEmail);

            //Send an auto replied email back to the clients
            SendAutoResponder(model);

            //Check if redirectionPage Url is empty
            var redirectionPage = CurrentPage.GetPropertyValue <Link>("redirection");

            //If it is, then redirect page to the Home page
            if (string.IsNullOrWhiteSpace(redirectionPage?.Url))
            {
                return(this.RedirectToUmbracoPage(CurrentPage.Site()));
            }
            //Otherwise, redirect it to the redirection page
            return(this.Redirect(redirectionPage.Url));
        }
Example #6
0
        /// <summary>
        /// Verifies the user's answer to the recaptcha challenge.
        /// </summary>
        /// <returns>Returns the verification result as <see cref="RecaptchaVerificationResult"/> enum value.</returns>
        ///<exception cref="InvalidOperationException">The private key is null or empty.</exception>
        ///<exception cref="System.Net.WebException">The time-out period for the recaptcha verification request expired.</exception>
        public RecaptchaVerificationResult Verify()
        {
            if (_verificationHelper == null)
            {
                _verificationHelper = new RecaptchaVerificationHelper(this.PrivateKey);
            }

            return(_verificationHelper.VerifyRecaptchaResponse());
        }
Example #7
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA");
                return(View(model));
            }
            else
            {
                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                    return(View(model));
                }
            }

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

                var lpUser = new LPUser();
                lpUser.Email    = model.Email;
                lpUser.Username = model.Username;
                //Used for testing
                //string[] splitstring = model.Email.Split('@');
                //lpUser.Username = splitstring[0];
                if (result.Succeeded)
                {
                    db.LPUsers.Add(lpUser);
                    db.SaveChanges();
                    CreateProfile(model.Email);
                    System.Diagnostics.Debug.WriteLine("Registered");
                    //  Comment the following line to prevent log in until the user is confirmed.
                    await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false);

                    string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");

                    ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                                      + "before you can log in.";

                    //Call the ActionResult method that creates an LPUser
                    //return RedirectToAction("LPUserCreate", "Home", new { Email = model.Email });
                    return(View("Info"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("reCAPTCHA", "Please complete the reCAPTCHA");
                // If we got this far, something failed, redisplay form
                return(View(model));
            }
            else
            {
                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("reCAPTCHA", "The reCAPTCHA is incorrect");
                    // If we got this far, something failed, redisplay form
                    return(View(model));
                }
            }
            if (ModelState.IsValid)
            {
                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, isPersistent : false, rememberBrowser : false);

                    // For more information on how to enable account confirmation and password reset please visit https://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, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                    //Replace this with Repository Pattern!!
                    CompanionContext db       = new CompanionContext();
                    CompanionUser    compUser = new CompanionUser();
                    compUser.ASPIdentityID = user.Id;
                    compUser.Email         = user.Email;
                    db.CompanionUsers.Add(compUser);
                    db.SaveChanges();

                    return(RedirectToAction("Index", "Home"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #9
0
        public ActionResult Create(EditOrderViewModel model)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("", "Captcha відповідь не може бути пустою.");
                return(View("Edit", model));
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                ModelState.AddModelError("", "Невірна captcha відповідь.");
                return(View("Edit", model));
            }

            HttpCookie consumerBasketRawDataCookie = Request.Cookies["ConsumerBasket"];

            if (consumerBasketRawDataCookie == null)
            {
                ModelState.AddModelError("", "Не вибрано жодного товару для покупки");
            }

            if (ModelState.IsValid)
            {
                List <ProductInBasketViewModel> productInBasketViewModels = JsonConvert.DeserializeObject <List <ProductInBasketViewModel> >(
                    HttpContext.Server.UrlDecode(consumerBasketRawDataCookie.Value));

                Order order = _ordersBL.CreateOrder(new CreateOrderQuery
                {
                    Person = new CreateOrderQuery.AddPersonQuery
                    {
                        Email       = model.Email,
                        MiddleName  = model.MiddleName,
                        LastName    = model.LastName,
                        PhoneNumber = model.PhoneNumber,
                        FirstName   = model.FirstName
                    },
                    OrderedProducts = new List <CreateOrderQuery.AddOrderedProductQuery>(
                        productInBasketViewModels.Select(
                            p => new CreateOrderQuery.AddOrderedProductQuery
                    {
                        ProductId = p.Id,
                        Quantity  = p.Quantity
                    }).ToList()),
                    AdditionalComment = model.AdditionalComment
                });
                TempData[Constants.TempDataKeys.ORDER_ID] = order.Id;
                return(RedirectToAction("OrderDetails", new { orderId = order.Id }));
            }

            return(View("Edit", model));
        }
Example #10
0
        public ActionResult RateHospital(int id = 0, int score = 0)
        {
            try
            {
                if (Session["RATING_TIME"] == null)
                {
                    Session["RATING_TIME"] = 0;
                }

                int ratingTime = (int)Session["RATING_TIME"];
                Session["RATING_TIME"] = ++ratingTime;

                if (ratingTime > 3)
                {
                    RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

                    if (String.IsNullOrEmpty(recaptchaHelper.Response))
                    {
                        TempData["RateActionStatus"]  = false;
                        TempData["RateActionMessage"] = "Vui lòng nhập mã bảo mật bên dưới.";

                        return(RedirectToAction(Constants.HospitalAction, Constants.HomeController, new { hospitalId = id, redirect = "yes" }));
                    }

                    RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

                    if (recaptchaResult != RecaptchaVerificationResult.Success)
                    {
                        TempData["RateActionStatus"]  = false;
                        TempData["RateActionMessage"] = "Vui lòng nhập lại mã bảo mật bên dưới.";

                        return(RedirectToAction(Constants.HospitalAction, Constants.HomeController, new { hospitalId = id, redirect = "yes" }));
                    }
                }

                string email = User.Identity.Name.Split(Char.Parse(Constants.Minus))[0];

                int userId = AccountModel.LoadUserIdByEmail(email);

                bool check = HomeModel.RateHospital(userId, id, score);
                if (!check)
                {
                    TempData["RateActionStatus"]  = false;
                    TempData["RateActionMessage"] = "Vui lòng thử lại sau ít phút.";
                }
                TempData["RateActionStatus"] = true;
                return(RedirectToAction(Constants.HospitalAction, Constants.HomeController, new { hospitalId = id, redirect = "yes" }));
            }
            catch (Exception exception)
            {
                LoggingUtil.LogException(exception);
                return(RedirectToAction(Constants.SystemFailureHomeAction, Constants.ErrorController));
            }
        }
Example #11
0
        public bool CheckCaptcha(RecaptchaVerificationHelper recaptchaHelper, ref string errore)
        {
            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {
                errore = App_GlobalResources.ErrorResource.ContactsCaptchaEmpty;
                return(false);
            }
            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                errore = App_GlobalResources.ErrorResource.ContactsCaptchaError;
                return(false);
            }
            return(true);
        }
        protected void BootstrapButtonLogin_Click(object sender, EventArgs e)
        {
            divMessage.Visible = true;

            // validate captcha:
            if (Request["g-recaptcha-response"] == null)
            {
                divMessage.InnerHtml = "Error, no Captcha field form.  Intente mas tarde o por favor contacte a soporte técnico si el error persiste.";
                return;
            }

            var Recaptchav2 = new RecaptchaVerificationHelper();


            if (string.IsNullOrEmpty(Request["g-recaptcha-response"].ToString()))
            {
                divMessage.InnerHtml = "El Captcha no puede estar vacio.";
                return;
            }
            else
            {
                string secretkey = Global.Configuration.Security.Google.Recaptcha.v2.GetGoogleRecaptchaSecretKey();

                RecaptchaVerificationResult result = Recaptchav2.VerifyRecaptchaResponse(secretkey, Request["g-recaptcha-response"].ToString());

                if (result == RecaptchaVerificationResult.Success)
                {
                    //Response.Redirect( "Welcome.aspx" );
                    //divMessage.InnerHtml = "Captcha OK :D";

                    Response.Redirect("~/Admin/Login.aspx", true);
                    //Server.Transfer("~/Default.aspx", true);
                }
                else if (result == RecaptchaVerificationResult.IncorrectCaptchaSolution)
                {
                    divMessage.InnerHtml = "Valor de Captcha NO Valido.";
                    return;
                }
                else
                {
                    divMessage.InnerHtml = "Existe un problema para validar el captcha, intente mas tarde o por favor contacte a soporte técnico.";
                    return;
                }
            }
        }
Example #13
0
        /// <summary>
        /// This method calls the Google ReCaptcha API..
        /// </summary>
        /// <param name="errorMsgId">The id of the form field where the error message should be displayed.</param>
        private void VerifyCaptcha(string errorMsgId)
        {
            const string CaptchaError = "The ReCaptcha checkbox is required.";
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                this.ModelState.AddModelError(errorMsgId, CaptchaError);
                return;
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                this.ModelState.AddModelError(errorMsgId, CaptchaError);
            }
        }
Example #14
0
        public async Task <ActionResult> Login(LoginViewModel model, string returnUrl)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("", "Captcha answer cannot be empty.");
                return(View(model));
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                ModelState.AddModelError("", "Incorrect captcha answer.");
            }

            if (!ModelState.IsValid)
            {
                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, shouldLockout : true);

            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));
            }
        }
        public ActionResult Contact(Contact contact)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("", "Captcha answer cannot be empty.");
                return(View(contact));
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                ModelState.AddModelError("", "Incorrect captcha answer.");
            }

            return(View(contact));
        }
Example #16
0
        private bool ValidateRecaptcha()
        {
            bool recaptchaSuccess = true;

            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (String.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("", "Captcha answer cannot be empty.");
                recaptchaSuccess = false;
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                ModelState.AddModelError("", "Incorrect captcha answer.");
                recaptchaSuccess = false;
            }
            return(recaptchaSuccess);
        }
 public ActionResult Index(Support s)
 {
     RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
     if (String.IsNullOrEmpty(recaptchaHelper.Response))
     {
         ModelState.AddModelError("", "Captcha answer cannot be empty.");
         return View(s);
     }
     RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();
     if (recaptchaResult != RecaptchaVerificationResult.Success)
     {
         ModelState.AddModelError("", "Incorrect captcha answer.");
         return View(s);
     }
     if (ModelState.IsValid)
     {
         _mailPusher.SendEmail("*****@*****.**", "Administrator","*****@*****.**", s.Subject +" "+ s.Name + "[" + s.MobileNumber + "]", s.Message);
         TempData["msg"] = "Your Message has been Successfully Sent";
         return View();
     }
     ModelState.AddModelError("", "Kindly ensure you supply all necessary and required details");
     return View(s);
 }
Example #18
0
        public ActionResult Contact(ContactModel contact)
        {
            if (ModelState.IsValid)
            {
                RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

                if (String.IsNullOrEmpty(recaptchaHelper.Response))
                {
                    ModelState.AddModelError("", "Captcha answer cannot be empty.");
                    ViewBag.recaptchaError = "Captcha answer cannot be empty.";
                }

                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("", "Incorrect captcha answer.");
                    ViewBag.recaptchaError = "Incorrect captcha answer.";
                }
                else
                {
                    ViewBag.pageName = "contact";
                    string emailBody = System.IO.File.ReadAllText(Server.MapPath("~/utils/ResetPassword.html"));
                    emailBody = emailBody.Replace("[Name]", contact.Name);
                    emailBody = emailBody.Replace("[Email]", contact.Email);
                    emailBody = emailBody.Replace("[Technology]", contact.Topics);
                    emailBody = emailBody.Replace("[Message]", contact.Message);
                    EMailHelper.SendEmail(System.Configuration.ConfigurationManager.AppSettings["officealEmail"], System.Configuration.ConfigurationManager.AppSettings["EmailSubject"], emailBody);
                    ViewBag.emailsent = "Thanks for contacting us. We will contact you as soon.";
                    contact.Email     = "";
                    contact.Message   = "";
                    contact.Name      = "";
                    contact.Topics    = "";
                }
            }
            return(View());
        }
Example #19
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            //Captcha Check
            var debug = false;

            if (debug)
            {
                RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();
                if (String.IsNullOrEmpty(recaptchaHelper.Response))
                {
                    ModelState.AddModelError("", "Captcha answer cannot be empty.");
                    return(View(model));
                }

                RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

                if (recaptchaResult != RecaptchaVerificationResult.Success)
                {
                    ModelState.AddModelError("", "Incorrect captcha answer.");
                    return(View(model));
                }
            }



            if (ModelState.IsValid)
            {
                var user = new AppUser()
                {
                    UserName      = model.UserName,
                    FirstName     = model.FirstName,
                    LastName      = model.LastName,
                    IsActive      = true,
                    Email         = model.Email,
                    UpdatedAt     = DateTime.Now,
                    CreatedAt     = DateTime.Now,
                    SecurityStamp = new Guid().ToString()
                };

                if (!string.IsNullOrEmpty(model.Password))
                {
                    user.PasswordHash = PasswordHash.CreateHash(model.Password);
                }

                var result = await UserManager.CreateAsync(user);

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

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Example #20
0
        public ActionResult Create([Bind(Include = "QuoteId,TopicId,QuoteText,QuoteAuthor,QuotePassword")] Quotes quotes)
        {
            var           verification = Request.Form["verify"];
            List <string> QuoteSplit   = quotes.QuoteText.Split(' ').ToList();

            //Lower Case Quote Effects//
            switch (QuoteSplit[0])
            {
            case ":marquee":
                quotes.QuoteEffect = "marquee";
                QuoteSplit.RemoveAt(0);
                break;

            case ":colour":
            case ":color":
                quotes.QuoteEffect = "color " + QuoteSplit[1].ToString();
                QuoteSplit.RemoveAt(0);
                QuoteSplit.RemoveAt(0);
                break;

            default:
                quotes.QuoteEffect = null;
                break;
            }
            quotes.QuoteText = String.Join <string>(" ", QuoteSplit);
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                ModelState.AddModelError("", "Shit's fried mate");
            }
            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                ModelState.AddModelError("", "Incorrect captcha answer.");
            }

            //if (ModelState.IsValid && QuoteSplit.Count > 0)
            if (QuoteSplit.Count > 0 && verification == "on")
            {
                //Init Topic Count//

                /*
                 * Dictionary<int, int> top_topics = new Dictionary<int, int>();
                 * foreach (var t in db.Topics)
                 * {
                 *  top_topics.Add(t.TopicId, 0);
                 * }
                 * foreach (var q in db.Quotes)
                 * {
                 *  top_topics[q.TopicId] += 1;
                 *  q.Topic.TopicAmount = top_topics[q.TopicId];
                 * }
                 * */
                foreach (var t in db.Topics)
                {
                    if (t.TopicId == quotes.TopicId)
                    {
                        t.TopicAmount += 1;
                    }
                }
                quotes.QuoteRating = 0;
                db.Quotes.Add(quotes);
                db.SaveChanges();
                return(RedirectToAction("Details", new { id = quotes.QuoteId }));
            }
            else
            {
                TempData["Worked"] = "False";
                return(RedirectToAction("Create"));
            }

            ViewBag.TopicId = new SelectList(db.Topics, "TopicId", "TopicName", quotes.TopicId);
            return(View("Details", quotes));
        }
Example #21
0
        public ActionResult Index(Form data)
        {
            RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

            if (string.IsNullOrEmpty(recaptchaHelper.Response))
            {
                this.ModelState.AddModelError(string.Empty, "Captcha answer cannot be empty.");

                return(this.View(data));
            }

            RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

            if (recaptchaResult != RecaptchaVerificationResult.Success)
            {
                this.ModelState.AddModelError(string.Empty, "Incorrect captcha answer.");

                return(this.View(data));
            }

            FormValidator validator = new FormValidator();

            validator.Validate(data);

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

            string emailBody = string.Empty;

            // If at least half of the interest questions were "Agreed" or "Strongly Agreed".
            if (this.CalculateScore(data) >= 6)
            {
                data.IsPotentialStudent = true;

                emailBody  = "Results to Software Development Quiz<br/><br/>";
                emailBody += "Congratulations! It sounds like training for a career in software development could be a good fit for you. We offer a few options that may work well for you.<br/><br/>";
                emailBody += "DEGREES (TWO YEARS)<br/>";
                emailBody += $"<a href=\"https://www.tri-c.edu/programs/information-technology/programming-and-development/programming-development-at-tri-c.html{Properties.Settings.Default.TrackingQueryString}\">Programming and Development</a><br/><br/>";
                emailBody += "SHORT-TERM AND POST DEGREE CERTIFICATES (JUST OVER A YEAR)<br/>";
                emailBody += $"<a href=\"https://www.tri-c.edu/programs/information-technology/programming-and-development/certificate-in-mobile-application-development.html{Properties.Settings.Default.TrackingQueryString}\">Mobile Application Development</a><br />";
                emailBody += $"<a href=\"https://www.tri-c.edu/programs/information-technology/programming-and-development/certificate-in-web-application-development.html{Properties.Settings.Default.TrackingQueryString}\">Web Application Development</a><br/>";
                emailBody += $"<a href=\"https://www.tri-c.edu/programs/information-technology/programming-and-development/net-programming.html{Properties.Settings.Default.TrackingQueryString}\">.NET Programming</a><br/>";
                emailBody += $"<a href=\"https://www.tri-c.edu/programs/information-technology/programming-and-development/post-degree-certificate-in-programming-and-development.html{Properties.Settings.Default.TrackingQueryString}\">Programming and Development</a><br/><br/>";
                emailBody += "FAST TRACK TRAINING (3-6 MONTHS)<br/>";
                emailBody += $"<a href=\"https://www.tri-c.edu/programs/information-technology/programming-and-development/clevelandcodes.html{Properties.Settings.Default.TrackingQueryString}\">Cleveland Codes Software Developers Academy</a><br/><br/>";

                if (Convert.ToBoolean(data.StartNow))
                {
                    emailBody += "One of our staff will be reaching out to you within 48 hours to discuss program options and enrollment procedures.";
                }
                else
                {
                    emailBody += "You indicated that you are not quite ready to begin a training program. We will keep your name on our email list and share program information about upcoming courses.<br/><br/>";
                    emailBody += "If you don’t want future training opportunities emailed to you, please <a href=\"mailto:[email protected]?subject=%20Unsubscribe%20from%20email%20list\">unsubscribe</a>.";
                }
            }
            else
            {
                data.IsPotentialStudent = false;

                emailBody  = "Results to Software Development Quiz<br/><br/>";
                emailBody += "Based on the interests that you self-reported, it sounds like a career in software development might not be the best fit for you. Tri-C offers many different programs so you can find one that’s the right fit for you.<br/><br/>";
                emailBody += "If you like computers, take our <a href=\"https://forms.tri-c.edu/NetworkingQuiz\">computer networking quiz</a> to see if this area is a better match with your interests.<br/><br/>";
                emailBody += "We also offer programs that include technology applications as part of the coursework, such as business technology and entrepreneurial technology. In addition, the Gill and Tommy LiPuma Center for Creative Arts offers 3D design, digital video editing, game design and motion graphics, to name a few.<br /><br />";
                emailBody += $"<a href=\"https://www.tri-c.edu/programs/{Properties.Settings.Default.TrackingQueryString}\">View All Available Programs</a>";
            }

            EmailProcess ep = new EmailProcess(Properties.Settings.Default.EmailHost, Properties.Settings.Default.EmailPort, Properties.Settings.Default.EmailFrom);

            if (!ep.SendEmail(data.Email, "Tri-C Software Development Quiz Confirmation", emailBody))
            {
                return(this.RedirectToAction("Error"));
            }

            ListProcess lp = new ListProcess(
                Properties.Settings.Default.Site,
                Properties.Settings.Default.List,
                AppDBConnection.KwebConnection);

            if (!lp.Add(data))
            {
                return(this.RedirectToAction("Error"));
            }

            return(this.RedirectToAction("Thanks"));
        }
Example #22
0
        public virtual async Task <ActionResult> Register(RegisterViewModel model)
        {
            ActionResult actionResult;

            AbpUserManager <Tenant, Role, FuelWerx.Authorization.Users.User> .AbpLoginResult loginResultAsync;
            Guid guid;
            Guid guid1;
            bool flag;

            AbpUserManager <Tenant, Role, FuelWerx.Authorization.Users.User> .AbpLoginResult abpLoginResult;
            TenantLogosEditDto tenantLogosEditDto = Abp.Threading.AsyncHelper.RunSync <TenantLogosEditDto>(() => this.GetCurrentTenantLogos());
            dynamic            viewBag            = this.ViewBag;

            guid = (tenantLogosEditDto.HeaderImageId.HasValue ? tenantLogosEditDto.HeaderImageId.Value : Guid.Empty);
            viewBag.TenantCompanyHeaderImageId = guid;
            dynamic obj = this.ViewBag;

            guid1 = (tenantLogosEditDto.HeaderMobileImageId.HasValue ? tenantLogosEditDto.HeaderMobileImageId.Value : Guid.Empty);
            obj.TenantCompanyHeaderMobileImageId = guid1;
            try
            {
                this.CheckSelfRegistrationIsEnabled();
                this.CheckModelState();
                if (!model.IsExternalLogin && this.UseCaptchaOnRegistration())
                {
                    RecaptchaVerificationHelper recaptchaVerificationHelper = this.GetRecaptchaVerificationHelper();
                    if (recaptchaVerificationHelper.Response.IsNullOrEmpty())
                    {
                        throw new UserFriendlyException(this.L("CaptchaCanNotBeEmpty"));
                    }
                    if (recaptchaVerificationHelper.VerifyRecaptchaResponse() != RecaptchaVerificationResult.Success)
                    {
                        throw new UserFriendlyException(this.L("IncorrectCaptchaAnswer"));
                    }
                }
                if (!this._multiTenancyConfig.IsEnabled)
                {
                    model.TenancyName = "Default";
                }
                else if (model.TenancyName.IsNullOrEmpty())
                {
                    throw new UserFriendlyException(this.L("TenantNameCanNotBeEmpty"));
                }
                Tenant activeTenantAsync = await this.GetActiveTenantAsync(model.TenancyName);

                bool settingValueForTenantAsync = await SettingManagerExtensions.GetSettingValueForTenantAsync <bool>(this.SettingManager, "App.UserManagement.AllowSelfRegistration", activeTenantAsync.Id);

                if (!settingValueForTenantAsync)
                {
                    throw new UserFriendlyException(this.L("SelfUserRegistrationIsDisabledMessage_Detail"));
                }
                settingValueForTenantAsync = await SettingManagerExtensions.GetSettingValueForTenantAsync <bool>(this.SettingManager, "App.UserManagement.IsNewRegisteredUserActiveByDefault", activeTenantAsync.Id);

                bool flag1 = settingValueForTenantAsync;
                settingValueForTenantAsync = await SettingManagerExtensions.GetSettingValueForTenantAsync <bool>(this.SettingManager, "Abp.Zero.UserManagement.IsEmailConfirmationRequiredForLogin", activeTenantAsync.Id);

                bool flag2 = settingValueForTenantAsync;
                FuelWerx.Authorization.Users.User user = new FuelWerx.Authorization.Users.User()
                {
                    TenantId     = new int?(activeTenantAsync.Id),
                    Name         = model.Name,
                    Surname      = model.Surname,
                    EmailAddress = model.EmailAddress,
                    IsActive     = flag1
                };
                FuelWerx.Authorization.Users.User userName = user;
                ExternalLoginInfo externalLoginInfoAsync   = null;
                if (model.IsExternalLogin)
                {
                    externalLoginInfoAsync = await AuthenticationManagerExtensions.GetExternalLoginInfoAsync(this.AuthenticationManager);

                    if (externalLoginInfoAsync == null)
                    {
                        throw new ApplicationException("Can not external login!");
                    }
                    FuelWerx.Authorization.Users.User user1 = userName;
                    List <UserLogin> userLogins             = new List <UserLogin>();
                    UserLogin        userLogin = new UserLogin()
                    {
                        LoginProvider = externalLoginInfoAsync.Login.LoginProvider,
                        ProviderKey   = externalLoginInfoAsync.Login.ProviderKey
                    };
                    userLogins.Add(userLogin);
                    user1.Logins   = userLogins;
                    model.UserName = model.EmailAddress;
                    model.Password = FuelWerx.Authorization.Users.User.CreateRandomPassword();
                    if (string.Equals(externalLoginInfoAsync.Email, model.EmailAddress, StringComparison.InvariantCultureIgnoreCase))
                    {
                        userName.IsEmailConfirmed = true;
                    }
                }
                else if (model.UserName.IsNullOrEmpty() || model.Password.IsNullOrEmpty())
                {
                    throw new UserFriendlyException(this.L("FormIsNotValidMessage"));
                }
                userName.UserName = model.UserName;
                userName.Password = (new PasswordHasher()).HashPassword(model.Password);
                IActiveUnitOfWork current = this._unitOfWorkManager.Current;
                current.EnableFilter(new string[] { "MayHaveTenant" });
                this._unitOfWorkManager.Current.SetFilterParameter("MayHaveTenant", "tenantId", activeTenantAsync.Id);
                userName.Roles = new List <UserRole>();
                IQueryable <Role> roles     = this._roleManager.Roles;
                List <Role>       listAsync = await(
                    from r in roles
                    where r.IsDefault
                    select r).ToListAsync <Role>();
                foreach (Role role in listAsync)
                {
                    ICollection <UserRole> userRoles = userName.Roles;
                    userRoles.Add(new UserRole()
                    {
                        RoleId = role.Id
                    });
                }
                this.CheckErrors(await this._userManager.CreateAsync(userName));
                await this._unitOfWorkManager.Current.SaveChangesAsync();

                if (!userName.IsEmailConfirmed)
                {
                    userName.SetNewEmailConfirmationCode();
                    await this._userEmailer.SendEmailActivationLinkAsync(userName, null);
                }
                if (userName.IsActive && (userName.IsEmailConfirmed || !flag2))
                {
                    if (externalLoginInfoAsync == null)
                    {
                        loginResultAsync = await this.GetLoginResultAsync(userName.UserName, model.Password, activeTenantAsync.TenancyName);

                        abpLoginResult = loginResultAsync;
                    }
                    else
                    {
                        loginResultAsync = await this._userManager.LoginAsync(externalLoginInfoAsync.Login, activeTenantAsync.TenancyName);

                        abpLoginResult = loginResultAsync;
                    }
                    if (abpLoginResult.Result != AbpLoginResultType.Success)
                    {
                        this.Logger.Warn(string.Concat("New registered user could not be login. This should not be normally. login result: ", abpLoginResult.Result));
                        abpLoginResult = null;
                    }
                    else
                    {
                        await this.SignInAsync(abpLoginResult.User, abpLoginResult.Identity, false);

                        actionResult = this.Redirect(this.Url.Action("Index", "Application"));
                        return(actionResult);
                    }
                }
                AccountController       accountController       = this;
                RegisterResultViewModel registerResultViewModel = new RegisterResultViewModel()
                {
                    TenancyName    = activeTenantAsync.TenancyName,
                    NameAndSurname = string.Concat(userName.Name, " ", userName.Surname),
                    UserName       = userName.UserName,
                    EmailAddress   = userName.EmailAddress,
                    IsActive       = userName.IsActive,
                    IsEmailConfirmationRequired = flag2
                };
                actionResult = accountController.View("RegisterResult", registerResultViewModel);
            }
            catch (UserFriendlyException userFriendlyException1)
            {
                UserFriendlyException userFriendlyException = userFriendlyException1;
                ((dynamic)this.ViewBag).IsMultiTenancyEnabled = this._multiTenancyConfig.IsEnabled;
                dynamic viewBag1 = this.ViewBag;
                flag = (model.IsExternalLogin ? false : this.UseCaptchaOnRegistration());
                viewBag1.UseCaptcha = flag;
                ((dynamic)this.ViewBag).ErrorMessage = userFriendlyException.Message;
                actionResult = this.View("Register", model);
            }
            return(actionResult);
        }
Example #23
0
        public ActionResult Login(AccountLoginModel model)
        {
            if (ModelState.IsValid)
            {
                if (int.Parse(Session["Strikes"].ToString()) >= 3)
                {
                    RecaptchaVerificationHelper recaptchaHelper = this.GetRecaptchaVerificationHelper();

                    if (String.IsNullOrEmpty(recaptchaHelper.Response))
                    {
                        ModelState.AddModelError("", "Captcha answer cannot be empty.");
                        model.MistakesWereMade = int.Parse(Session["Strikes"].ToString());
                        return(View(model));
                    }

                    RecaptchaVerificationResult recaptchaResult = recaptchaHelper.VerifyRecaptchaResponse();

                    if (recaptchaResult != RecaptchaVerificationResult.Success)
                    {
                        ModelState.AddModelError("", "Incorrect captcha answer.");
                        model.MistakesWereMade = int.Parse(Session["Strikes"].ToString());
                    }
                }
                if (TempData["Success"] != null)
                {
                    model.SuccessMessage = TempData["Success"].ToString();
                }
                if (TempData["Error"] != null)
                {
                    model.ErrorMessage = TempData["Error"].ToString();
                }

                var context = new StackOverflowContext();
                var account = context.Accounts.FirstOrDefault(x => x.Email == model.Email);
                if (account != null)
                {
                    if (!account.IsVerified)
                    {
                        model.ErrorMessage = "Account Has not Been Verified";
                        return(View(model));
                    }

                    if (account.Password != model.Password)
                    {
                        SendWarningEmail(model.Email);
                        model.ErrorMessage = "Wrong Password";

                        Session["Strikes"]     = int.Parse(Session["Strikes"].ToString()) + 1;
                        model.MistakesWereMade = int.Parse(Session["Strikes"].ToString());
                        return(View(model));
                    }
                    FormsAuthentication.SetAuthCookie(account.Id.ToString(), false);
                    return(RedirectToAction("Index", "Question"));
                }
            }
            model.ErrorMessage = "Account not Found";

            Session["Strikes"]     = int.Parse(Session["Strikes"].ToString()) + 1;
            model.MistakesWereMade = int.Parse(Session["Strikes"].ToString());
            return(View(model));
        }