protected bool ValidateValidCode(string recapchaType, string recaptcha)
        {
#if DEBUG
            return(true);
#endif

            if (recapchaType.Equals("None", StringComparison.OrdinalIgnoreCase))
            {
                return(true);
            }

            if (recapchaType.Equals("Google", StringComparison.OrdinalIgnoreCase))
            {
                return(GoogleRecaptchaHelper.IsValidRequest(recaptcha));
            }

            if (recapchaType.Equals("Geetest", StringComparison.OrdinalIgnoreCase))
            {
                return(new GeetestHelper()
                       .ValidateRequest(JsonConvert.DeserializeObject <GeetestRequestModel>(recaptcha),
                                        Session[GeetestConsts.GeetestUserId]?.ToString() ?? "",
                                        Convert.ToByte(Session[GeetestConsts.GtServerStatusSessionKey]),
                                        () => { Session.Remove(GeetestConsts.GeetestUserId); }));
            }

            return(false);
        }
Пример #2
0
 public async Task <IActionResult> RealmDiscovery([Bind("Username", "recaptchaResponse", "ReturnUrl")] RealmDiscoveryModel user)
 {
     if (await GoogleRecaptchaHelper.IsReCaptchaV2PassedAsync(user.recaptchaResponse))
     {
         User identity = _context.Users.Where(u => u.Username == user.Username).FirstOrDefault();
         if (identity == null)
         {
             if (user.Username.Contains("@"))
             {
                 var authenticationProperties = new AuthenticationProperties();
                 authenticationProperties.Items["login_hint"] = user.Username;
                 if (user.ReturnUrl == null)
                 {
                     authenticationProperties.RedirectUri = "/Landing/";
                 }
                 else
                 {
                     authenticationProperties.RedirectUri = user.ReturnUrl;
                 }
                 return(Challenge(authenticationProperties, AzureADDefaults.AuthenticationScheme));
             }
             else
             {
                 ViewData["Alert"]   = "Danger";
                 ViewData["Message"] = "We can't find an account with that Username";
                 return(View(user));
             }
         }
         else if (identity.Existence != Existence.Internal)
         {
             var authenticationProperties = new AuthenticationProperties();
             authenticationProperties.Items["login_hint"] = user.Username;
             if (user.ReturnUrl == null)
             {
                 authenticationProperties.RedirectUri = "/Landing/";
             }
             else
             {
                 authenticationProperties.RedirectUri = user.ReturnUrl;
             }
             return(Challenge(authenticationProperties, AzureADDefaults.AuthenticationScheme));
         }
         else
         {
             TempData["Username"]  = identity.Username;
             TempData["ReturnUrl"] = user.ReturnUrl;
             return(Redirect("/Internal/Account/SignIn"));
         }
     }
     else
     {
         ViewData["Alert"]   = "Warning";
         ViewData["Message"] = "Unable to verify reCAPTCHA! Please try again";
         return(View(user));
     }
 }
Пример #3
0
 public async Task OnPost()
 {
     if (ModelState.IsValid)
     {
         if (!await GoogleRecaptchaHelper.IsReCaptchaPassedAsync(Request.Form["g-recaptcha-response"],
                                                                 _config["GoogleReCaptcha:secret"]))
         {
             ModelState.AddModelError(string.Empty, "You failed the CAPTCHA");
         }
         //do your stuff here...
     }
 }
Пример #4
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            // returnUrl = returnUrl ?? Url.Content("~/");
            if (returnUrl == null)
            {
                returnUrl = "/Home/Index";          // this is used to redirect to dash board page after the login into the system.
            }
            else
            {
                returnUrl = returnUrl ?? Url.Content("~/");
            }

            if (ModelState.IsValid)
            {
                if (!await GoogleRecaptchaHelper.IsReCaptchaPassedAsync(Request.Form["g-recaptcha-response"],
                                                                        _config["GoogleReCaptcha:secret"]))
                {
                    ModelState.AddModelError(string.Empty, "You failed the CAPTCHA");
                    return(Page());
                }
                // 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 : true);

                if (result.Succeeded)
                {
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect("/Home/Index"));
                }
                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());
        }
        public async Task <IActionResult> Add([FromBody] ContactRequest request)
        {
            if (!ModelState.IsValid)
            {
                return(Ok(ModelState));
            }

            var response = new BaseResponse <Guid>();

            if (!await GoogleRecaptchaHelper.IsReCaptchaPassedAsync(request.CaptchaToken, "6Ldt7KEUAAAAAL_gnq4ORX4NrKDK3qegm1TSyBAg"))
            {
                response.Message = "Lütfen robot olmadığınızı doğrulayın.";
                return(Ok(response));
            }

            var item = new Contact
            {
                FullName    = request.Name,
                Email       = request.Email,
                PhoneNumber = request.PhoneNumber,
                Message     = request.Message
            };

            contactRepo.Add(item);
            response.Message = "Kayıt başarıyla eklenmiştir.";
            response.Data    = item.Id;

            var MailBody = "HepsiSef bize ulaşın" + "\n " + "isim:" + " " + item.FullName + "\n" + "email:" + " " + item.Email + "\n" + "telefon no:" + " " + item.PhoneNumber + "\n" + "mesaj:" + " " + item.Message;

            List <AdminMailMM> Admins = new List <AdminMailMM>();

            Admins = userRepo.GetBy(x => x.Role == Role.Admin).Select(x => new AdminMailMM
            {
                Email = x.Email
            }).ToList();

            foreach (var mail in Admins)
            {
                MailManager.Send(MailBody, mail.Email);
            }

            return(Ok(response));
        }
        public async Task <IActionResult> Contact(Contact contact)
        {
            if (ModelState.IsValid)
            {
                if (!await GoogleRecaptchaHelper.IsReCaptchaPassedAsync(Request.Form["g-recaptcha-response"],
                                                                        _config["GoogleReCaptcha:secret"]))
                {
                    ModelState.AddModelError(string.Empty, "You failed the CAPTCHA");
                    return(View(contact));
                }

                await _blogService.Contact(contact);

                await emailSender.Execute(contact.Email + " sent you message", contact.Message, "");

                TempData["msg"] = "Thank you for your message, We will read it and get in touch with you if needed";
            }

            return(View());
        }
Пример #7
0
        public async Task <IActionResult> Register(RegisterUserViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (!await GoogleRecaptchaHelper.IsReCaptchaPassedAsync(Request.Form["g-recaptcha-response"],
                                                                    _config["GoogleReCaptcha:secret"]))
            {
                ModelState.AddModelError(string.Empty, "احراز هویت را انجام دهید");
                return(View(model));
            }


            string activecode = Guid.NewGuid().ToString().Replace("-", "");
            User   user       = new User
            {
                Email           = model.Email,
                Password        = string.Join("-", PasswordHash.HashPasswordV2(model.Password)),
                EmailActiveCode = activecode
            };
            int userid = userService.AddUser(user);

            if (userid > 0)
            {
                ActiveEmailViewModel emailViewModel = new ActiveEmailViewModel
                {
                    ActiveCode = activecode,
                    UserId     = userid
                };
                emailSender.SendEmail(model.Email, "ارسال ایمیل فعال سازی", renderViewToString.Render("_ActiveEmail", emailViewModel));
            }
            ModelState.AddModelError(string.Empty, "در ثبت اطلاعات مشکلی به وجود امده است");

            return(View(model));
        }
Пример #8
0
 public bool ValidateCaptcha(string captchaResponse)
 {
     return(GoogleRecaptchaHelper.ValidateReCaptchaV2(captchaResponse));
 }
Пример #9
0
 public JsonResult ValidateGoogleRecaptchaResponse(string response)
 {
     return(Json(GoogleRecaptchaHelper.IsValidRequest(response)));
 }
Пример #10
0
 public CaptchaVerifyHelper(GoogleRecaptchaHelper googleRecaptchaHelper, TencentCaptchaHelper tencentCaptchaHelper, ILogger <CaptchaVerifyHelper> logger)
 {
     _googleRecaptchaHelper = googleRecaptchaHelper;
     _tencentCaptchaHelper  = tencentCaptchaHelper;
     _logger = logger;
 }
Пример #11
0
        public async Task <IActionResult> Withdrawal(WithdrawalViewModel model, string withdrawalAll)
        {
            if (!_userService.IsSignedIn(User))
            {
                return(RedirectToAction(nameof(HomeController.Index), "Home"));
            }
            var config = await _globalConfigurationService.GetValueConfig(Constants.Configuration.ProgramLocked);

            if (config.Contains("true"))
            {
                return(View("~/Views/Lock.cshtml"));
            }

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

            if (model.WithdrawalAmount < _configuration.GetValue <decimal>("InvestmentValidation:MinWithdrawalAmount"))
            {
                ViewData["Message"] = string.Format(ValidationMessages.WithdrawalInvalid, _configuration.GetValue <decimal>("InvestmentValidation:MinWithdrawalAmount"));
                ModelState.AddModelError("WithdrawalAmount", string.Format(ValidationMessages.WithdrawalInvalid, _configuration.GetValue <decimal>("InvestmentValidation:MinWithdrawalAmount")));
                return(View(model));
            }

            if (!await GoogleRecaptchaHelper.IsReCaptchaPassedAsync(Request.Form["g-recaptcha-response"], _configuration.GetValue <string>("GoogleReCaptcha:SecretKey")))
            {
                ViewData["CaptchaInvalidMessage"] = ValidationMessages.CaptchaInvalidMessage;
                return(View(model));
            }

            var currentUser = await _userService.GetCurrentUser();

            if (WithdrawalProcessingUsers.ContainsKey(currentUser.UserName) && WithdrawalProcessingUsers[currentUser.UserName])
            {
                ViewBag.Error = ValidationMessages.WithdrawalError;
                return(View());
            }

            try
            {
                //Lock user of withdrawal
                if (WithdrawalProcessingUsers.ContainsKey(currentUser.UserName))
                {
                    WithdrawalProcessingUsers[currentUser.UserName] = true;
                }
                else
                {
                    WithdrawalProcessingUsers.Add(currentUser.UserName, true);
                }


                var amount = (decimal)model.WithdrawalAmount;
                if (!string.IsNullOrWhiteSpace(withdrawalAll))
                {
                    if (model.WithdrawalType == Common.WithdrawalType.Quick)
                    {
                        amount = currentUser.CurrentAccountAmount * 90 / 100;
                    }
                    else
                    {
                        amount = currentUser.CurrentAccountAmount;
                    }
                }

                var withdrawalFee = await _withdrawFeeService.GetFeeAmount(amount, true);

                var checkWithdrawal = _configuration.GetValue <bool>("ViewClient:Withdrawal") != null?_configuration.GetValue <bool>("ViewClient:Withdrawal") : true;

                if (model.WithdrawalType == Common.WithdrawalType.Quick && checkWithdrawal)
                {
                    var quickWithdrawalFee = await _withdrawFeeService.GetQuickWithdrawalFee();

                    var dateQuickWithdrawal = _configuration.GetValue <int>("Fee:DateQuickWithdrawal");
                    withdrawalFee += amount * quickWithdrawalFee * dateQuickWithdrawal;
                }

                var personalIncomeFee = _configuration.GetValue <decimal>("Fee:PersonalIncomeFee") / 100;
                withdrawalFee += amount * personalIncomeFee;

                withdrawalFee = Decimal.Round(withdrawalFee, 0);

                if ((decimal)model.WithdrawalAmount + withdrawalFee > Decimal.Round(currentUser.CurrentAccountAmount, 0))
                {
                    ViewData["Message"] = ValidationMessages.WithdrawalInvalid2;
                    ModelState.AddModelError("WithdrawalAmount", ValidationMessages.WithdrawalInvalid2);
                    return(View(model));
                }

                if (model.WithdrawalType == Common.WithdrawalType.Quick && model.WithdrawalAmount > Decimal.Round(currentUser.CurrentAccountAmount * 90 / 100, 0) && checkWithdrawal)
                {
                    ViewData["Message"] = ValidationMessages.WithdrawalInvalid3;
                    ModelState.AddModelError("WithdrawalAmount", ValidationMessages.WithdrawalInvalid3);
                    return(View(model));
                }

                if (currentUser.WithdrawProcessing && (DateTime.Now - currentUser.WithdrawProcessingDate).Minutes <= 5)
                {
                    ViewBag.Error = ValidationMessages.WithdrawalError;
                    return(View());
                }

                TempData["Message"] = Model.Resources.Common.WithdrawalResult;

                if (model.WithdrawalType == Common.WithdrawalType.Quick && checkWithdrawal)
                {
                    if (!_configuration.GetValue <bool>("PaymentSecurity:DisableVTP"))
                    {
                        var viettelPayApi   = _configuration.GetValue <bool>("RequestPaymentLink:IsLive") ? _configuration.GetValue <string>("RequestPaymentLink:Live") : _configuration.GetValue <string>("RequestPaymentLink:Test");
                        var cmd             = _configuration.GetValue <string>("RequestPaymentParam:cmdRequest");
                        var rsaPublicKey    = _configuration.GetValue <string>("RSAKey:public");
                        var rsaPrivateKey   = _configuration.GetValue <string>("RSAKey:private");
                        var rsaPublicKeyVTP = _configuration.GetValue <string>("RSAKey:VTPpublic");

                        var rsa             = new RSAHelper(RSAType.RSA, Encoding.UTF8, rsaPrivateKey, rsaPublicKeyVTP);
                        var passwordEncrypt = rsa.Encrypt(_configuration.GetValue <string>("RequestPaymentParam:password"));

                        var dataRequestPayment = new DataRequestPayment()
                        {
                            msisdn       = "84" + currentUser.PhoneNumber.Remove(0, 1),
                            customerName = currentUser.FullName,
                            transId      = TempData["OrderId"].ToString(),
                            amount       = ((decimal)model.WithdrawalAmount).ToString("0"),
                            smsContent   = _configuration.GetValue <string>("RequestPaymentParam:smsContent"),
                            note         = "Rut tien tu Savenow"
                        };

                        var soapDataRequestPayment = new SoapDataRequestPayment()
                        {
                            username     = _configuration.GetValue <string>("RequestPaymentParam:username"),
                            password     = passwordEncrypt,
                            serviceCode  = _configuration.GetValue <string>("RequestPaymentParam:serviceCode"),
                            orderId      = TempData["OrderId"].ToString(),
                            totalTrans   = "1",
                            totalAmount  = ((decimal)model.WithdrawalAmount).ToString("0"),
                            transContent = _configuration.GetValue <string>("RequestPaymentParam:smsContent")
                        };

                        var code = await _viettelPay.Request(viettelPayApi, cmd, rsaPublicKey, rsaPrivateKey, rsaPublicKeyVTP, dataRequestPayment, soapDataRequestPayment);

                        if (!string.IsNullOrWhiteSpace(code) && code == "10")
                        {
                            currentUser.WithdrawProcessing = false;
                            await _userService.UpdateUser(currentUser);

                            ViewBag.Error = ValidationMessages.VTPInvalidAccount;
                            return(View());
                        }
                        else if (code != "00")
                        {
                            currentUser.WithdrawProcessing = false;
                            await _userService.UpdateUser(currentUser);

                            ViewBag.Error = ValidationMessages.VTPError;
                            return(View());
                        }
                    }
                    TempData["Message"] = Model.Resources.Common.WithdrawalQuickResult;
                }

                await _withdrawFeeService.GetFeeAmount(amount);

                if (!string.IsNullOrWhiteSpace(withdrawalAll))
                {
                    await _fundTransactionHistoryService.Withdrawal(currentUser.UserName, (decimal)model.WithdrawalAmount, withdrawalFee, model.WithdrawalType, true, objectId : TempData["OrderId"]?.ToString());
                }
                else
                {
                    await _fundTransactionHistoryService.Withdrawal(currentUser.UserName, (decimal)model.WithdrawalAmount, withdrawalFee, model.WithdrawalType, objectId : TempData["OrderId"]?.ToString());
                }

                if (TempData["OrderId"] != null)
                {
                    var order = await _orderRequestService.GetOrder(orderId : Int32.Parse(TempData["OrderId"].ToString()));

                    order.Amount = (decimal)model.WithdrawalAmount;
                    await _orderRequestService.UpdateOrder(order);
                }
            }
            finally
            {
                WithdrawalProcessingUsers.Remove(currentUser.UserName);
            }


            return(RedirectToAction(nameof(AccountController.WithdrawalResult), "Account"));
        }
Пример #12
0
 public bool Validate(string response)
 {
     return(GoogleRecaptchaHelper.ValidateReCaptchaV2(_config, response));
 }
Пример #13
0
        public IActionResult PostRegister([FromBody] JObject json)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            dynamic data             = json;
            string  name             = data.name;
            string  email            = data.email;
            string  password         = data.password;
            string  confirm_password = data.confirm_password;
            string  phone            = data.phone;
            string  address          = data.address;
            int     id_city          = data.id_city;
            int     num_item_selled  = data.num_item_selled;
            string  captcha          = data.captcha;

            if (password != confirm_password)
            {
                return(BadRequest("Mật khẩu nhập lại không đúng"));
            }
            if (password.Length < 8)
            {
                return(BadRequest("Mật khẩu tối thiểu 8 ký tự"));
            }
            Regex rgx = new Regex(info.RegEx);

            if (!rgx.IsMatch(password))
            {
                return(BadRequest("Mật khẩu phải có ký tự Hoa, Số, Thường"));
            }
            //Validate Google recaptcha below
            if (!GoogleRecaptchaHelper.IsReCaptchaPassedAsync(captcha, "6Lfwz6IUAAAAAM_gyYa0tzAoeyVYKZ5rkOxT_d6h"))
            {
                return(BadRequest("Vui Lòng Nhập Captcha"));
            }

            password = bf.Encrypt_CBC(password);
            Users account = new Users();

            account.name            = name;
            account.email           = email;
            account.password        = password;
            account.phone           = phone;
            account.address         = address;
            account.id_city         = id_city;
            account.num_item_selled = num_item_selled;
            account.level_seller    = 1;
            account.score_buyer     = 0;
            account.date_registion  = DateTime.Now;
            account.active          = true;

            _context.Add(account);
            _context.SaveChanges();

            //mailer
            ml.SendMail("Exaxxi Site", email, "Register in Exaxxi", "Chúc mừng bạn đã đăng ký thành công!");

            return(Ok());
        }