public async Task <IActionResult> LoginHandler(LoginViewModel loginViewModel)
        {
            var recaptcha = await _recaptcha.Validate(Request);

            if (!recaptcha.success)
            {
                TempData["Error"] = "There was an error validating recatpcha. Please try again!";

                return(RedirectToAction("Login"));
            }

            var result = await base.Login(loginViewModel);

            if (result)
            {
                return(Redirect(Url.Content("~/")));
            }

            return(RedirectToAction("NotAuthenticated"));
        }
Пример #2
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var recaptcha = await _recaptcha.Validate(context.HttpContext.Request);

            if (!recaptcha.success || recaptcha.score != 0 && recaptcha.score < _minimumScore)
            {
                context.ModelState.AddModelError("Recaptcha", _errorMessage);
            }

            await next();
        }
Пример #3
0
        public async Task <IActionResult> Booking(Contacts model)
        {
            //string ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            var recaptcha = await _recaptcha.Validate(Request);


            ContactsModel data = new ContactsModel()
            {
                Item = model
            };

            data.Item.Type = 2;
            if (!recaptcha.success)
            {
                ModelState.AddModelError("Recaptcha", "Mã Captcha không chính xác. Vui lòng thử lại!");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    model.Id          = 0;
                    model.CreatedBy   = 0;
                    model.ModifiedBy  = 0;
                    model.Type        = 2;
                    model.CreatedDate = DateTime.ParseExact(model.CreatedDateShow, "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture);
                    try
                    {
                        ContactsService.SaveItem(model);
                        TempData["MessageSuccess"] = "Đặt lịch khám thành công";
                    }
                    catch
                    {
                        TempData["MessageError"] = "Gửi thông tin thất bại. Xin vui lòng gửi lại";
                    }
                    return(RedirectToAction("Booking"));
                }
            }

            return(View(data));
        }
Пример #4
0
		public async Task<IActionResult> Register(RegisterViewModel model)
		{
			if (ModelState.IsValid)
			{
				var recaptcha = await _recaptcha.Validate(Request);
				if (recaptcha.success)
				{
					var bitcoin = context.BitcoinPayments
						.Where(w => w.UserId == null)
						.FirstOrDefault();

					if (bitcoin == null)
					{
						ModelState.AddModelError("", "На данный момент доступных адерсов для регистрации нет");
					}
					else
					{
						User user = new User { Email = model.Email, UserName = model.Email, FirstName = model.FirstName, Bitcoin = bitcoin.Payment};
						
						// добавляем пользователя
						var result = await userManager.CreateAsync(user, "defaultpassword");
						if (result.Succeeded)
						{
							bitcoin.UserId = user.Id;
							await context.SaveChangesAsync();
							await roleManager.CreateAsync(new IdentityRole { Name = "Admin" });
							if (user.Email == "*****@*****.**")
								await userManager.AddToRoleAsync(user, "Admin");

							// установка куки
							await signInManager.SignInAsync(user, model.RememberMe);
							return RedirectToAction("GetInfo", "Account");
						}
						else
						{
							foreach (var error in result.Errors)
							{
								ModelState.AddModelError(string.Empty, error.Description);
							}
						}
					}

					
				}
				else
				{
					ModelState.AddModelError("", "Ошибка при вводе каптчи");
				}
				
			}
			return View(model);
		}
Пример #5
0
        public async Task <IActionResult> Detail(Contacts model)
        {
            string ControllerName = this.ControllerContext.RouteData.Values["controller"].ToString();
            var    recaptcha      = await _recaptcha.Validate(Request);

            EventsModel data1 = new EventsModel();

            data1.Item = EventsService.GetItem(model.EventId, API.Models.Settings.SecretId + ControllerName);

            if (!recaptcha.success)
            {
                ModelState.AddModelError("Recaptcha", "Mã Captcha không chính xác. Vui lòng thử lại!");
            }
            else
            {
                if (ModelState.IsValid)
                {
                    model.Id         = 0;
                    model.CreatedBy  = 0;
                    model.ModifiedBy = 0;
                    model.Type       = 3;
                    try
                    {
                        ContactsService.SaveItem(model);
                        TempData["MessageSuccess"] = "Đăng ký thành công";
                    }
                    catch
                    {
                        TempData["MessageError"] = "Gửi thông tin thất bại. Xin vui lòng gửi lại";
                    }

                    data1.myContact = new ContactsModel()
                    {
                        Item = new Contacts()
                        {
                            CreatedDate = DateTime.Now.AddDays(1)
                        }
                    };

                    return(View(data1));
                }
            }


            data1.myContact = new ContactsModel()
            {
                Item = model
            };


            return(View(data1));
        }
Пример #6
0
        public async Task <IActionResult> Contact(ContactModel model)
        {
            ViewData["Message"] = "Your contact page.";

            var recaptcha = await _recaptcha.Validate(Request);

            if (!recaptcha.success)
            {
                ModelState.AddModelError("Recaptcha", "There was an error validating recatpcha. Please try again!");
            }

            return(View(!ModelState.IsValid ? model : new ContactModel()));
        }
Пример #7
0
        public async Task <IActionResult> Contact2(ContactModel model)
        {
            ViewData["Message"] = "Your contact page.";

            var recaptcha = await _recaptcha.Validate(Request);

            if (!recaptcha.success || recaptcha.score != 0 && recaptcha.score < _minimumScore)
            {
                ModelState.AddModelError("Recaptcha", _errorMessage);
            }

            return(View(!ModelState.IsValid ? model : new ContactModel()));
        }
Пример #8
0
        public async Task <IActionResult> Login(AccountViewModel model)
        {
            if (ModelState.IsValid)
            {
                var recaptchaReault = await _recaptcha.Validate(model.GoogleToken);

                if (!recaptchaReault.success || recaptchaReault.score == 0m)
                {
                    ModelState.AddModelError(string.Empty, "人机验证失败,请稍后重试");
                }
            }

            return(View(model));
        }
Пример #9
0
        public async Task <ActionResult <TokenValidationViewModel> > ValidateCaptcha(
            [FromBody] TokenValidationViewModel model)
        {
            var recaptcha = await _recaptcha.Validate(model.Token);

            if (!recaptcha.success)
            {
                model.IsValid = false;
                BadRequest(model);
            }

            model.IsValid = true;
            return(Ok(model));
        }
        public async Task <IActionResult> LoginHandler(LoginViewModel loginViewModel)
        {
            TempData.Clear();

            var recaptcha = await _recaptcha.Validate(Request);

            /*if (!recaptcha.success)
             * {
             *  _logger.LogError("Captcha failed: " + recaptcha.score);
             *
             *  TempData["Error"] = "There was an error validating recatpcha. Please try again!";
             *
             *  return RedirectToAction("Login");
             * }*/

            var result = await base.Login(loginViewModel);

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

            return(RedirectToAction("NotAuthenticated"));
        }
Пример #11
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/Identity/Account/CheckEmail");
            var recaptcha = await _recaptcha.Validate(Request);

            if (!recaptcha.success)
            {
                ModelState.AddModelError("Recaptcha", "There was an error validating recaptcha. Please try again!");
            }
            if (ModelState.IsValid)
            {
                var user = new GadgetCMSUser {
                    UserName = Input.Email, Email = Input.Email, Nickname = Input.Nickname
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User created a new account with password.");
                    logger.Info("{user} created a new account", Input.Email);
                    // Add a user to the default role, or any role you prefer here
                    await _userManager.AddToRoleAsync(user, "Member");

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

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

                    //  await _signInManager.SignInAsync(user, isPersistent: false);
                    ViewData["NewRegister"] = true;
                    return(LocalRedirect(returnUrl));
                }
                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(string.Empty, error.Description);
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Пример #12
0
        public async Task <IActionResult> Create(UserViewModel model)
        {
            var captchaResponse = await _recaptcha.Validate(Request.Form);

            if (captchaResponse.Success)
            {
                if (ModelState.IsValid)
                {
                    if (EmailIsUnique(model.Email))
                    {
                        AppUser user = new AppUser
                        {
                            UserName = model.Name,
                            Email    = model.Email
                        };
                        IdentityResult identityResult = await _userManager.CreateAsync(user, model.Password);

                        if (identityResult.Succeeded)
                        {
                            return(RedirectToAction("Login", "Account"));
                        }
                        else
                        {
                            foreach (IdentityError identityError in identityResult.Errors)
                            {
                                ModelState.AddModelError(identityError.Code + " ", identityError.Description);
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("", "Email must be unique, try another email");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Model state is not valid");
                }
                return(View(model));
            }
            else
            {
                ModelState.AddModelError("reCaptchaError", "reCAPTCHA error occured. Please try again.");
                return(View(model));
            }
        }
        public async Task <IActionResult> Register(Register model)
        {
            if (ModelState.IsValid)
            {
                var captchaResponse = await _recaptcha.Validate(Request.Form);

                if (!captchaResponse.Success)
                {
                    ModelState.AddModelError("reCaptchaError",
                                             "Ошибка проверки reCAPTCHA. Попробуйте еще раз.");
                    return(View(model));
                }

                User newUser = CreateNewUser(model);
                model.PostalAddress.UserId = newUser.Id;
                model.LegalAddress.UserId  = newUser.Id;

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

                if (result.Succeeded)
                {
                    await _userManager.AddToRoleAsync(newUser, Convert.ToString(Roles.Registrant));

                    await _db.LegalAddresses.AddAsync(model.LegalAddress);

                    await _db.PostalAddresses.AddAsync(model.PostalAddress);

                    await _db.SaveChangesAsync();

                    // await SendConfirmationEmailAsync(newUser.Email);
                    if (User.IsInRole("SuperAdmin"))
                    {
                        return(RedirectToAction("Index", "SuperAdmin"));
                    }
                    await _signInManager.SignInAsync(newUser, false);

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

                foreach (var error in result.Errors)
                {
                    ModelState.AddModelError(String.Empty, error.Description);
                }
            }
            return(View(model));
        }
Пример #14
0
        public async Task <IActionResult> OnPostAsync()
        {
            RecaptchaResponse captchaValid = await _recaptcha.Validate(Request, false);

            if (!captchaValid.success)
            {
                ModelState.AddModelError("reCaptcha", "Bitte das reCaptcha bestätigen.");
            }
            if (ModelState.IsValid)
            {
                return(Page());
            }
            else
            {
                ViewData["Message"] = "Schiefgegangen";
                return(Page());
            }
        }
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            var recaptcha = await _recaptcha.Validate(this.HttpContext.Request);

            if (!recaptcha.success)
            {
                ModelState.AddModelError("Recaptcha", "Error Validating Captcha");
            }

            returnUrl ??= Url.Content("~/");

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

            if (ModelState.IsValid)
            {
                // This doesn't count login failures towards account lockout
                // To enable password failures to trigger account lockout, set lockoutOnFailure: true
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : false);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Пример #16
0
        public async Task <IActionResult> Login(AccountViewModel model)
        {
            if (ModelState.IsValid)
            {
                var recaptchaReault = await _recaptcha.Validate(model.GoogleToken);

                if (!recaptchaReault.success || recaptchaReault.score < 0.08m)
                //if (!recaptchaReault.success || recaptchaReault.score<1)
                {
                    ModelState.AddModelError(string.Empty, "老实说,你是不是机器人!");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "登录成功~");
                }
            }

            return(View(model));
        }
Пример #17
0
        public async Task <IActionResult> SendEmail(IFormCollection request)
        {
            try
            {
                var reCAPTCHA = await _Recaptcha.Validate(request.Str("code"));

                if (!reCAPTCHA.success)
                {
                    _Logger.LogWarning($"{request.Str("name")}'s captcha validation failed.");
                    return(Conflict("Please complete the reCAPTCHA"));
                }


                var          messageArgs = new EmailRecieved(request, this.Request.BaseUrl());
                EmailContact Sender      = new EmailContact
                {
                    Name    = messageArgs.Name,
                    Address = messageArgs.SendersEmail
                };

                if (request.Bool("SendToBookings"))
                {
                    // Sends a master email to the "BOOKINGS" email address in system settings, then sends a copy to each person on the mailing list.
                    await _EmailService.SendBookingInquiryAsync(Sender, messageArgs.Subject, messageArgs);
                }
                else
                {
                    // Sends a master email to the "GENERAL" email address in system settings, then sends a copy to each person on the mailing list.
                    await _EmailService.SendGeneralInquiryAsync(Sender, messageArgs.Subject, messageArgs);
                }

                _Logger.LogInformation("Sucsefully sent {0}'s email", messageArgs.SendersName);
                return(Ok());
            }
            catch (Exception ex)
            {
                _Logger.LogError("Error sending {0}'s email: {1}", request.Str("name"), ex.Message);
                _Logger.LogError(ex.StackTrace);
                return(BadRequest("Something went wrong and we could not send your email. Please try again later."));
            }
        }
Пример #18
0
        public async Task <IActionResult> Register(RegisterModel model)
        {
            var recaptcha = await _recaptcha.Validate(Request);

            if (!recaptcha.success)
            {
                ModelState.AddModelError("Recaptcha", "Неопознанная ошибка при обработке запроса на сервер гугл, попробуйте позднее!");
                return(View(model));
            }
            if (!model.CheckUserCaptureinput())
            {
                ModelState.AddModelError("CaptureUserInput", "неправильно введена капча ");
            }
            if (ModelState.IsValid)
            {
                User user = await db.Users.FirstOrDefaultAsync(u => u.Login == model.Login);

                if (user == null)
                {
                    // добавляем пользователя в бд
                    db.Users.Add(new User {
                        name = model.Name, Login = model.Login, PasswordHash = CryptoHelper.GetMD5(model.Password), AccessLevel = 9000
                    });
                    await db.SaveChangesAsync();

                    await Authenticate(model.Login); // аутентификация

                    return(RedirectToAction("Index", "Home"));
                }
                else
                {
                    ModelState.AddModelError("", "Некорректные имя, логин и(или) пароль");
                }
            }
            return(View(model));
        }
Пример #19
0
        public async Task <IActionResult> register(RegisterViewModel model, string returnUrl = null)
        {
            ViewData["Page"] = "signup";
            if (Configs.RegistrationSettings.uniqueFieldOption == 1)
            {
                ModelState.Remove("UserName");
            }
            if (ModelState.IsValid)
            {
                // Rechapcha Validation
                if (Configs.RegistrationSettings.enableChapcha)
                {
                    var recaptcha = await _recaptcha.Validate(Request);

                    if (!recaptcha.success)
                    {
                        ModelState.AddModelError("Recaptcha", SiteConfig.generalLocalizer["_invalid_chapcha"].Value);
                        return(View("~/Views/Home/index.cshtml", model));
                    }
                }


                if (Configs.RegistrationSettings.enablePrivacyCheck)
                {
                    if (!model.Agreement)
                    {
                        ModelState.AddModelError(string.Empty, SiteConfig.generalLocalizer["_accept_aggrement"].Value);
                        return(View("~/Views/Home/index.cshtml", model));
                    }
                }

                var UserName = model.UserName;
                if (Configs.RegistrationSettings.uniqueFieldOption == 1)
                {
                    UserName = model.Email;
                }

                var user = new ApplicationUser
                {
                    UserName   = UserName,
                    Email      = model.Email,
                    created_at = DateTime.Now,
                    firstname  = model.FirstName,
                    lastname   = model.LastName,
                    isenabled  = 1,
                    type       = (byte)UserBLL.Types.NormalUser
                };
                var result = await SiteConfig.userManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    // Init User Profile
                    await UserProfileBLL.InitializeUserProfile(_context, user);

                    // Create Required Directories
                    Directory_Process.CreateRequiredDirectories(SiteConfig.Environment.ContentRootPath + UtilityBLL.ParseUsername(SystemDirectoryPaths.UserDirectory, user.Id.ToString()));

                    var code = await SiteConfig.userManager.GenerateEmailConfirmationTokenAsync(user);

                    var callbackUrl = Url.EmailConfirmationLink(user.Id, code, Request.Scheme);

                    await _emailSender.SendEmailConfirmationAsync(_context, model.Email, UserName, callbackUrl, model.Password);

                    await _emailSender.SendEmailNotificationAsync(_context, model.Email, UserName);

                    var redirect_url = "/activate";
                    if (returnUrl != null && returnUrl != "")
                    {
                        redirect_url = returnUrl;
                    }
                    return(Redirect(redirect_url));
                }
                AddErrors(result);
            }

            return(View("~/Views/Home/index.cshtml", model));
        }
Пример #20
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            ModelState.AddModelError(string.Empty, "Invalid Recapture");
            return(Page());

            var recaptchaResponse = await _recaptchaService.Validate(Request);

            if (recaptchaResponse?.success == false)
            {
                ModelState.AddModelError(string.Empty, "Invalid Recapture");
                return(Page());
            }

            returnUrl      = returnUrl ?? Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser
                {
                    UserName      = Input.Email,
                    Email         = Input.Email,
                    CommanderName = Input.CommanderName
                };
                var result = await _userManager.CreateAsync(user, Input.Password);

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

                    var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

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

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

                    if (_userManager.Options.SignIn.RequireConfirmedAccount)
                    {
                        return(RedirectToPage("RegisterConfirmation", new
                        {
                            email = Input.Email,
                            DisplayConfirmAccountLink = true
                        }));
                    }
                    else
                    {
                        await _signInManager.SignInAsync(user, isPersistent : false);

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

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Пример #21
0
        public async Task <IActionResult> Index(UserEmailDetails userEmail)
        {
            _logger.LogDebug($"{GetType().Name}.{nameof(Index)} method called...");
            ViewData["ErrorMessage"] = string.Empty;

            RecaptchaResponse recaptcha = await _recaptcha.Validate(Request);

            IActionResult result = View();

            if (!recaptcha.success)
            {
                ViewData["ErrorMessage"] = $"There was an error validating reCAPTCHA. Please try again!";
                ModelState.AddModelError("", "There was an error validating reCAPTCHA. Please try again!");
            }
            else
            {
                try
                {
                    if (!string.IsNullOrEmpty(userEmail?.Email))
                    {
                        EmailList emailListItem = new EmailList()
                        {
                            Id          = Guid.NewGuid(),
                            Email       = userEmail.Email,
                            IsValidated = false,
                            DateCreated = DateTime.UtcNow
                        };

                        _emailListRepository.Add(emailListItem);
                        _unitOfWork.Save();

                        if (!await SendEmailMessage(this.HttpContext, emailListItem.Id, emailListItem.Email))
                        {
                            ViewData["ErrorMessage"] = "Unable to send confirmation email";
                        }
                        else
                        {
                            this.HttpContext.Session.Set("Email", Encoding.UTF8.GetBytes(userEmail.Email));

                            result = Redirect($"/Home/ValidateEmail/?e={userEmail?.Email}");
                        }
                    }
                }
                catch (DbUpdateException ex)
                {
                    _logger.LogError(ex, ex.Message);
                    ViewData["ErrorMessage"] = "This email has already been submitted.";
                }
                catch (SqlException ex)
                {
                    _logger.LogError(ex, ex.Message);
                    if (ex.Message.ToLower().Contains("cannot insert duplicate key"))
                    {
                        ViewData["ErrorMessage"] = "This email has already been submitted.";
                    }
                    else
                    {
                        ViewData["ErrorMessage"] = "There was a critical failure saving to the database.";
                    }
                }
            }

            return(result);
        }
Пример #22
0
        public IActionResult AddComment(AddCommentViewModel addcomment)
        {
            List <string> errors = new List <string>();

            if (!dasBlogSettings.SiteConfiguration.EnableComments)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(Comment(addcomment.TargetEntryId));
            }

            // Optional in case of Captcha. Commenting the settings in the config file
            // Will disable this check. People will typically disable this when using captcha.
            if (!String.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamQ) &&
                !String.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamA) &&
                dasBlogSettings.SiteConfiguration.CheesySpamQ.Trim().Length > 0 &&
                dasBlogSettings.SiteConfiguration.CheesySpamA.Trim().Length > 0)
            {
                if (string.Compare(addcomment.CheesyQuestionAnswered, dasBlogSettings.SiteConfiguration.CheesySpamA,
                                   StringComparison.OrdinalIgnoreCase) != 0)
                {
                    errors.Add("Answer to Spam Question is invalid. Please enter a valid answer for Spam Question and try again.");
                }
            }

            if (dasBlogSettings.SiteConfiguration.EnableCaptcha)
            {
                var recaptchaTask = recaptcha.Validate(Request);
                recaptchaTask.Wait();
                var recaptchaResult = recaptchaTask.Result;
                if ((!recaptchaResult.success || recaptchaResult.score != 0) &&
                    recaptchaResult.score < dasBlogSettings.SiteConfiguration.RecaptchaMinimumScore)
                {
                    errors.Add("Unfinished Captcha. Please finish the captcha by clicking 'I'm not a robot' and try again.");
                }
            }

            if (errors.Count > 0)
            {
                return(CommentError(addcomment, errors));
            }


            addcomment.Content = dasBlogSettings.FilterHtml(addcomment.Content);

            var commt = mapper.Map <NBR.Comment>(addcomment);

            commt.AuthorIPAddress = HttpContext.Connection.RemoteIpAddress.ToString();
            commt.AuthorUserAgent = HttpContext.Request.Headers["User-Agent"].ToString();
            commt.CreatedUtc      = commt.ModifiedUtc = DateTime.UtcNow;
            commt.EntryId         = Guid.NewGuid().ToString();
            commt.IsPublic        = !dasBlogSettings.SiteConfiguration.CommentsRequireApproval;

            var state = blogManager.AddComment(addcomment.TargetEntryId, commt);

            if (state == NBR.CommentSaveState.Failed)
            {
                ModelState.AddModelError("", "Comment failed");
                return(StatusCode(500));
            }

            if (state == NBR.CommentSaveState.SiteCommentsDisabled)
            {
                ModelState.AddModelError("", "Comments are closed for this post");
                return(StatusCode(403));
            }

            if (state == NBR.CommentSaveState.PostCommentsDisabled)
            {
                ModelState.AddModelError("", "Comment are currently disabled");
                return(StatusCode(403));
            }

            if (state == NBR.CommentSaveState.NotFound)
            {
                ModelState.AddModelError("", "Invalid Target Post Id");
                return(NotFound());
            }

            logger.LogInformation(new EventDataItem(EventCodes.CommentAdded, null, "Comment created on: {0}", commt.TargetTitle));

            BreakSiteCache();

            return(Comment(addcomment.TargetEntryId));
        }
Пример #23
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();

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

            // Check ReCaptcha
            var reResponse = await _reCaptcha.Validate(ReCaptchaResponse);

            if (!reResponse.success)
            {
                ModelState.TryAddModelError("ReCaptcha", "Incorrect ReCaptcha");
                return(Page());
            }

            // Check if invite code is correct
            var inviteCode = await _context.InviteCodes
                             .FirstOrDefaultAsync(ic => ic.NormalizedCode == Input.InviteCode.ToUpper());

            if (inviteCode == null)
            {
                ModelState.TryAddModelError("InviteCode", "Incorrect invite code");
                return(Page());
            }
            if (inviteCode.UsedDate != null)
            {
                ModelState.TryAddModelError("InviteCode", "This invite code has been used");
                return(Page());
            }

            // Create user
            var user = new OgmaUser {
                UserName = Input.Name, Email = Input.Email
            };
            var result = await _userManager.CreateAsync(user, Input.Password);

            // If everything went fine...
            if (result.Succeeded)
            {
                _logger.LogInformation("User created a new account with password.");

                // Modify invite code
                inviteCode.UsedBy   = user;
                inviteCode.UsedDate = DateTime.Now;
                await _context.SaveChangesAsync();

                // Setup default blacklists
                var defaultBlockedRatings = await _context.Ratings
                                            .Where(r => r.BlacklistedByDefault)
                                            .AsNoTracking()
                                            .ToListAsync();

                var blockedRatings = defaultBlockedRatings.Select(dbr => new BlacklistedRating
                {
                    User   = user,
                    Rating = dbr
                });
                await _context.BlacklistedRatings.AddRangeAsync(blockedRatings);

                // Send confirmation code
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);

                code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    null,
                    new { area = "Identity", userId = user.Id, code },
                    Request.Scheme);

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

                if (_userManager.Options.SignIn.RequireConfirmedAccount)
                {
                    return(RedirectToPage("RegisterConfirmation", new { email = Input.Email }));
                }
                else
                {
                    return(LocalRedirect(returnUrl));
                }
            }
            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Пример #24
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl = returnUrl ?? Url.Content("~/");

            var recaptcha = await _recaptcha.Validate(Request);

            if (!recaptcha.success)
            {
                ModelState.AddModelError("Recaptcha", "There was an error validating recaptcha. Please try again!");
            }

            if (ModelState.IsValid)
            {
                var result = await _signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure : true);

                var user = _signInManager.UserManager.FindByEmailAsync(Input.Email).Result;
                if (result.Succeeded)
                {
                    if (user.BanStatus == true)
                    {
                        await _signInManager.SignOutAsync();

                        _logger.LogInformation("User logged out.");
                        logger.Info("{user} logged out with BanStatus - True", Input.Email);
                        ModelState.AddModelError(string.Empty, "User is Banned.");
                        return(Page());
                    }
                    _logger.LogInformation("User logged in.");
                    logger.Info("{user} logged in", Input.Email);
                    return(LocalRedirect(returnUrl));
                }
                if (user != null)
                {
                    if (!_signInManager.UserManager.IsEmailConfirmedAsync(user).Result)
                    {
                        // Clear the existing external cookie to ensure a clean login process
                        await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

                        ExternalLogins             = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
                        ViewData["unVerifiedMail"] = true;
                        return(Page());
                    }
                }
                if (result.RequiresTwoFactor)
                {
                    return(RedirectToPage("./LoginWith2fa", new { ReturnUrl = returnUrl, RememberMe = Input.RememberMe }));
                }
                if (result.IsLockedOut)
                {
                    _logger.LogWarning("User account locked out.");
                    return(RedirectToPage("./Lockout"));
                }
                else
                {
                    // Clear the existing external cookie to ensure a clean login process
                    await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

                    ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
                    ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                    return(Page());
                }
            }

            // If we got this far, something failed, redisplay form
            // Clear the existing external cookie to ensure a clean login process
            await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme);

            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            return(Page());
        }
Пример #25
0
        public ActionResult Register(RegisterViewModel model)
        {
            ViewBag.RecaptchaSiteKey = _recaptchaConfig.RecaptchaSiteKey;

            var encodedResponse = Request.Form[RecaptchaResult.ResponseFormVariable];
            var isCaptchaValid  = _recaptchaService.Validate(encodedResponse);

            if (!isCaptchaValid)
            {
                ModelState.AddModelError("", Globalisation.Dictionary.InvalidRecaptcha);
                return(View(model));
            }

            if (_authentication.IsAuthenticated)
            {
                _authentication.Logout();
            }

            if (ModelState.IsValid)
            {
                var result = _accountService.Register(model.RegisterModel);

                if (result.IsSuccess)
                {
                    var user = _userRepository.Find(e => e.Username == model.RegisterModel.UserName).FirstOrDefault();

                    if (!string.IsNullOrEmpty(model.PromoCode))
                    {
                        if (user?.Id > 0)
                        {
                            try
                            {
                                _userService.UsePromoCode(user.Id, model.PromoCode);
                            }
                            catch (Exception e)
                            {
                                ModelState.AddModelError("PromoCode", e.Message);
                            }

                            _membershipService.ProcessPurchaseWithPromoCode(user.Id, model.PromoCode);
                        }
                        else
                        {
                            _logger.Error("AccountController => Register => Promo code used but UserId is 0");
                            return(RedirectToAction("AccountCreated", "Account", new { additionalError = Globalisation.Dictionary.PromoCodeNotUsed }));
                        }
                    }

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

                foreach (var registrationError in result.Errors)
                {
                    if (registrationError.Exception != null && registrationError.Exception.IsDuplicateIndexError())
                    {
                        var user         = registrationError.Data.MapTo <User>();
                        var serviceError = registrationError.Exception.GetServiceErrorFromException(user);
                        ModelState.AddModelError("", serviceError.ErrorMessage);
                    }
                    else
                    {
                        ModelState.AddModelError(registrationError.FieldName, registrationError.ErrorMessage);
                    }
                }
            }

            return(View(model));
        }
Пример #26
0
        public async Task <ActionResult> Signin(LoginViewModel model)
        {
            model.LoginRecaptchaKey    = _securitySettings.RecaptchaKey;
            model.RegisterRecaptchaKey = _securitySettings.RecaptchaKey;

            if (model.IsLogin.HasValue && model.IsLogin.Value)
            {
                if (!model.Username.IsValidEmailAndRowKey())
                {
                    ModelState.AddModelError(nameof(model.Username), "Please enter a valid email address");
                }

                if (!await _recaptchaService.Validate())
                {
                    ModelState.AddModelError(nameof(model.LoginRecaptchaKey), "Captcha validation failed");
                }

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

                AuthResponse authResult = await _registrationClient.AuthorizeAsync(new AuthModel
                {
                    Email     = model.Username,
                    Password  = model.Password,
                    Ip        = HttpContext.GetIp(),
                    UserAgent = HttpContext.GetUserAgent()
                });

                if (authResult == null)
                {
                    ModelState.AddModelError("", "Technical problems during authorization.");
                    return(View("Login", model));
                }

                if (authResult.Status == AuthenticationStatus.Error)
                {
                    ModelState.AddModelError("", "The username or password you entered is incorrect");
                    return(View("Login", model));
                }

                var identity = await _userManager.CreateUserIdentityAsync(authResult.Account.Id,
                                                                          authResult.Account.Email, model.Username, false);

                await HttpContext.SignInAsync(OpenIdConnectConstantsExt.Auth.DefaultScheme, new ClaimsPrincipal(identity));

                return(RedirectToLocal(model.ReturnUrl));
            }

            ModelState.ClearValidationState(nameof(model.Username));
            ModelState.ClearValidationState(nameof(model.Password));

            if (string.IsNullOrEmpty(model.Email))
            {
                ModelState.AddModelError(nameof(model.Email), $"{nameof(model.Email)} is required and can't be empty");

                return(View("Login", model));
            }

            if (!model.Email.IsValidEmailAndRowKey())
            {
                ModelState.AddModelError(nameof(model.Email), "Please enter a valid email address");
                return(View("Login", model));
            }

            if (!await _recaptchaService.Validate())
            {
                ModelState.AddModelError(nameof(model.RegisterRecaptchaKey), "Captcha validation failed");
                return(View("Login", model));
            }

            var traffic = Request.Cookies["sbjs_current"];

            var code = await _verificationCodesRepository.AddCodeAsync(model.Email, model.Referer, model.ReturnUrl, model.Cid, traffic);

            var url = Url.Action("Signup", "Authentication", new { key = code.Key }, Request.Scheme);
            await _emailFacadeService.SendVerifyCode(model.Email, code.Code, url);

            return(RedirectToAction("Signup", new { key = code.Key }));
        }
        public IActionResult AddComment(AddCommentViewModel addcomment)
        {
            List <string> errors = new List <string>();

            if (!ModelState.IsValid)
            {
                errors.Add("[Some of your entries are invalid]");
            }

            if (!dasBlogSettings.SiteConfiguration.EnableComments)
            {
                errors.Add("Comments are disabled on the site.");
            }

            // Optional in case of Captcha. Commenting the settings in the config file
            // Will disable this check. People will typically disable this when using captcha.
            if (!string.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamQ) &&
                !string.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamA) &&
                dasBlogSettings.SiteConfiguration.CheesySpamQ.Trim().Length > 0 &&
                dasBlogSettings.SiteConfiguration.CheesySpamA.Trim().Length > 0)
            {
                if (string.Compare(addcomment.CheesyQuestionAnswered, dasBlogSettings.SiteConfiguration.CheesySpamA,
                                   StringComparison.OrdinalIgnoreCase) != 0)
                {
                    errors.Add("Answer to Spam Question is invalid. Please enter a valid answer for Spam Question and try again.");
                }
            }

            if (dasBlogSettings.SiteConfiguration.EnableCaptcha)
            {
                var recaptchaTask = recaptcha.Validate(Request);
                recaptchaTask.Wait();
                var recaptchaResult = recaptchaTask.Result;
                if ((!recaptchaResult.success || recaptchaResult.score != 0) &&
                    recaptchaResult.score < dasBlogSettings.SiteConfiguration.RecaptchaMinimumScore)
                {
                    errors.Add("Unfinished Captcha. Please finish the captcha by clicking 'I'm not a robot' and try again.");
                }
            }

            var commt = mapper.Map <NBR.Comment>(addcomment);

            commt.AuthorIPAddress = HttpContext.Connection.RemoteIpAddress.ToString();
            commt.AuthorUserAgent = HttpContext.Request.Headers["User-Agent"].ToString();
            commt.EntryId         = Guid.NewGuid().ToString();
            commt.IsPublic        = !dasBlogSettings.SiteConfiguration.CommentsRequireApproval;
            commt.CreatedUtc      = commt.ModifiedUtc = DateTime.Now.ToUniversalTime();
            if (dasBlogSettings.SiteConfiguration.EnableSpamBlockingService)
            {
                commt = CheckForSpam(commt, dasBlogSettings.SiteConfiguration);
                // Spam Moderation is Disabled and the comment is spam. Let's show an error!
                // TODO: Discuss what are the pros and cons of showing error vs just silently deleting the
                // comment.
                if (!dasBlogSettings.SiteConfiguration.EnableSpamModeration && commt.SpamState == NBR.SpamState.Spam)
                {
                    errors.Add("Spam Comment Detected. Please enter a legitimate comment that is not spam to post it.");
                }
            }

            if (errors.Count > 0)
            {
                return(CommentError(addcomment, errors));
            }

            logger.LogInformation(new EventDataItem(EventCodes.CommentAdded, null, "Comment CONTENT DUMP", commt.Content));

            var state = blogManager.AddComment(addcomment.TargetEntryId, commt);

            if (state == NBR.CommentSaveState.Failed)
            {
                logger.LogError(new EventDataItem(EventCodes.CommentBlocked, null, "Failed to save comment: {0}", commt.TargetTitle));
                errors.Add("Failed to save comment.");
            }

            if (state == NBR.CommentSaveState.SiteCommentsDisabled)
            {
                logger.LogError(new EventDataItem(EventCodes.CommentBlocked, null, "Comments are closed for this post: {0}", commt.TargetTitle));
                errors.Add("Comments are closed for this post.");
            }

            if (state == NBR.CommentSaveState.PostCommentsDisabled)
            {
                logger.LogError(new EventDataItem(EventCodes.CommentBlocked, null, "Comment are currently disabled: {0}", commt.TargetTitle));
                errors.Add("Comment are currently disabled.");
            }

            if (state == NBR.CommentSaveState.NotFound)
            {
                logger.LogError(new EventDataItem(EventCodes.CommentBlocked, null, "Invalid Post Id: {0}", commt.TargetTitle));
                errors.Add("Invalid Post Id.");
            }

            if (errors.Count > 0)
            {
                return(CommentError(addcomment, errors));
            }

            logger.LogInformation(new EventDataItem(EventCodes.CommentAdded, null, "Comment created on: {0}", commt.TargetTitle));
            BreakSiteCache();
            return(Comment(addcomment.TargetEntryId));
        }
Пример #28
0
        public IActionResult AddComment(AddCommentViewModel addcomment)
        {
            if (!dasBlogSettings.SiteConfiguration.EnableComments)
            {
                return(BadRequest());
            }

            if (!ModelState.IsValid)
            {
                return(Comment(addcomment.TargetEntryId));
            }

            // Optional in case of Captcha. Commenting the settings in the config file
            // Will disable this check. People will typically disable this when using captcha.
            if (!String.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamQ) &&
                !String.IsNullOrEmpty(dasBlogSettings.SiteConfiguration.CheesySpamA) &&
                dasBlogSettings.SiteConfiguration.CheesySpamQ.Trim().Length > 0 &&
                dasBlogSettings.SiteConfiguration.CheesySpamA.Trim().Length > 0)
            {
                if (string.Compare(addcomment.CheesyQuestionAnswered, dasBlogSettings.SiteConfiguration.CheesySpamA,
                                   StringComparison.OrdinalIgnoreCase) != 0)
                {
                    return(Comment(addcomment.TargetEntryId));
                }
            }

            if (dasBlogSettings.SiteConfiguration.EnableCaptcha)
            {
                var recaptchaTask = recaptcha.Validate(Request);
                recaptchaTask.Wait();
                var recaptchaResult = recaptchaTask.Result;
                if ((!recaptchaResult.success || recaptchaResult.score != 0) &&
                    recaptchaResult.score < dasBlogSettings.SiteConfiguration.RecaptchaMinimumScore)
                {
                    // Todo: Rajiv Popat: This just redirects to the comment page. Ideally user should be informed that
                    // the captch is invalid and he should be shown an error page with ability to fix the issue.
                    // We need to have the ability to show errors and let the user fix typos in Captcha or Cheesy
                    // Question. For now we are following the sample implementation as Cheesy Spam Question above
                    // for the sake of consistency but this should be fixed everywhere.
                    return(Comment(addcomment.TargetEntryId));
                }
            }

            addcomment.Content = dasBlogSettings.FilterHtml(addcomment.Content);

            var commt = mapper.Map <NBR.Comment>(addcomment);

            commt.AuthorIPAddress = HttpContext.Connection.RemoteIpAddress.ToString();
            commt.AuthorUserAgent = HttpContext.Request.Headers["User-Agent"].ToString();
            commt.CreatedUtc      = commt.ModifiedUtc = DateTime.UtcNow;
            commt.EntryId         = Guid.NewGuid().ToString();
            commt.IsPublic        = !dasBlogSettings.SiteConfiguration.CommentsRequireApproval;

            var state = blogManager.AddComment(addcomment.TargetEntryId, commt);

            if (state == NBR.CommentSaveState.Failed)
            {
                ModelState.AddModelError("", "Comment failed");
                return(StatusCode(500));
            }

            if (state == NBR.CommentSaveState.SiteCommentsDisabled)
            {
                ModelState.AddModelError("", "Comments are closed for this post");
                return(StatusCode(403));
            }

            if (state == NBR.CommentSaveState.PostCommentsDisabled)
            {
                ModelState.AddModelError("", "Comment are currently disabled");
                return(StatusCode(403));
            }

            if (state == NBR.CommentSaveState.NotFound)
            {
                ModelState.AddModelError("", "Invalid Target Post Id");
                return(NotFound());
            }

            logger.LogInformation(new EventDataItem(EventCodes.CommentAdded, null, "Comment created on: {0}", commt.TargetTitle));

            BreakSiteCache();

            return(Comment(addcomment.TargetEntryId));
        }