Ejemplo n.º 1
0
        private async Task <CaptchaResponse> Solve(CaptchaService service, CaptchaType captchaType)
        {
            var proxy = MakeProxy(Proxy, ProxyType);

            switch (captchaType)
            {
            case CaptchaType.TextCaptcha:
                var textOptions = new TextCaptchaOptions()
                {
                    CaptchaLanguageGroup = CaptchaLanguageGroup,
                    CaptchaLanguage      = CaptchaLanguage
                };
                return(await service.SolveTextCaptchaAsync(Text, textOptions));

            case CaptchaType.ImageCaptcha:
                if (CaptchaImage == null)
                {
                    throw new ArgumentNullException("You must download an image first!");
                }

                var imageOptions = new ImageCaptchaOptions()
                {
                    IsPhrase             = IsPhrase,
                    CaseSensitive        = CaseSensitive,
                    CharacterSet         = CharacterSet,
                    RequiresCalculation  = RequiresCalculation,
                    MinLength            = int.Parse(MinLength),
                    MaxLength            = int.Parse(MaxLength),
                    CaptchaLanguageGroup = CaptchaLanguageGroup,
                    CaptchaLanguage      = CaptchaLanguage,
                    TextInstructions     = TextInstructions
                };
                return(await service.SolveImageCaptchaAsync(CaptchaImage.ToBase64(ImageFormat.Jpeg), imageOptions));

            case CaptchaType.ReCaptchaV2:
                return(await service.SolveRecaptchaV2Async(SiteKey, SiteUrl, SData, Enterprise, Invisible, proxy));

            case CaptchaType.ReCaptchaV3:
                return(await service.SolveRecaptchaV3Async(SiteKey, SiteUrl, Action,
                                                           float.Parse(MinScore, CultureInfo.InvariantCulture), Enterprise, proxy));

            case CaptchaType.FunCaptcha:
                return(await service.SolveFuncaptchaAsync(PublicKey, ServiceUrl, SiteUrl, NoJS, proxy));

            case CaptchaType.HCaptcha:
                return(await service.SolveHCaptchaAsync(SiteKey, SiteUrl, proxy));

            case CaptchaType.KeyCaptcha:
                return(await service.SolveKeyCaptchaAsync(UserId, SessionId, WebServerSign1, WebServerSign2,
                                                          SiteUrl, proxy));

            case CaptchaType.GeeTest:
                return(await service.SolveGeeTestAsync(GT, Challenge, ApiServer, SiteUrl, proxy));

            case CaptchaType.Capy:
                return(await service.SolveCapyAsync(SiteKey, SiteUrl, proxy));
            }

            throw new NotSupportedException($"Captcha type {captchaType} is not supported by the tester yet!");
        }
        /// <summary>Gets a <see cref="CaptchaService"/> to be used for solving captcha challenges.</summary>
        public static CaptchaService GetService(CaptchaSettings settings)
        {
            CaptchaService service = settings.CurrentService switch
            {
                CaptchaServiceType.AntiCaptcha => new AntiCaptchaService(settings.AntiCaptchaApiKey),
                CaptchaServiceType.AzCaptcha => new AzCaptchaService(settings.AZCaptchaApiKey),
                CaptchaServiceType.CaptchasIO => new CaptchasIOService(settings.CaptchasDotIoApiKey),
                CaptchaServiceType.CustomTwoCaptcha => new CustomTwoCaptchaService(settings.CustomTwoCaptchaApiKey,
                                                                                   new Uri($"http://{settings.CustomTwoCaptchaDomain}:{settings.CustomTwoCaptchaPort}")),
                CaptchaServiceType.CapMonster => new CapMonsterService(string.Empty,
                                                                       new Uri($"http://{settings.CapMonsterHost}:{settings.CapMonsterPort}")),
                CaptchaServiceType.DeathByCaptcha => new DeathByCaptchaService(settings.DeathByCaptchaUsername, settings.DeathByCaptchaPassword),
                CaptchaServiceType.DeCaptcher => new DeCaptcherService(settings.DeCaptcherUsername, settings.DeCaptcherPassword),
                CaptchaServiceType.ImageTyperz => new ImageTyperzService(settings.ImageTyperzApiKey),
                CaptchaServiceType.RuCaptcha => new RuCaptchaService(settings.RuCaptchaApiKey),
                CaptchaServiceType.SolveCaptcha => new SolveCaptchaService(settings.SolveCaptchaApiKey),
                CaptchaServiceType.SolveRecaptcha => new SolveRecaptchaService(settings.SolveRecaptchaApiKey),
                CaptchaServiceType.TrueCaptcha => new TrueCaptchaService(settings.TrueCaptchaUsername, settings.TrueCaptchaApiKey),
                CaptchaServiceType.TwoCaptcha => new TwoCaptchaService(settings.TwoCaptchaApiKey),
                _ => throw new NotSupportedException(),
            };

            service.Timeout = TimeSpan.FromSeconds(settings.TimeoutSeconds);
            return(service);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Gets a <see cref="CaptchaService"/> to be used for solving captcha challenges.
        /// </summary>
        public static CaptchaService GetService(CaptchaSettings settings)
        {
            CaptchaService service = settings.CurrentService switch
            {
                CaptchaServiceType.AntiCaptcha => new AntiCaptchaService(settings.AntiCaptchaApiKey),
                CaptchaServiceType.AzCaptcha => new AzCaptchaService(settings.AZCaptchaApiKey),
                CaptchaServiceType.CaptchasIO => new CaptchasIOService(settings.CaptchasDotIoApiKey),
                CaptchaServiceType.CustomTwoCaptcha => new CustomTwoCaptchaService(settings.CustomTwoCaptchaApiKey,
                                                                                   GetUri(settings.CustomTwoCaptchaDomain, settings.CustomTwoCaptchaPort),
                                                                                   null, settings.CustomTwoCaptchaOverrideHostHeader),
                CaptchaServiceType.CapMonster => new CapMonsterService(string.Empty,
                                                                       GetUri(settings.CapMonsterHost, settings.CapMonsterPort)),
                CaptchaServiceType.DeathByCaptcha => new DeathByCaptchaService(settings.DeathByCaptchaUsername, settings.DeathByCaptchaPassword),
                CaptchaServiceType.DeCaptcher => new DeCaptcherService(settings.DeCaptcherUsername, settings.DeCaptcherPassword),
                CaptchaServiceType.ImageTyperz => new ImageTyperzService(settings.ImageTyperzApiKey),
                CaptchaServiceType.RuCaptcha => new RuCaptchaService(settings.RuCaptchaApiKey),
                CaptchaServiceType.SolveCaptcha => new SolveCaptchaService(settings.SolveCaptchaApiKey),
                CaptchaServiceType.SolveRecaptcha => new SolveRecaptchaService(settings.SolveRecaptchaApiKey),
                CaptchaServiceType.TrueCaptcha => new TrueCaptchaService(settings.TrueCaptchaUsername, settings.TrueCaptchaApiKey),
                CaptchaServiceType.TwoCaptcha => new TwoCaptchaService(settings.TwoCaptchaApiKey),
                CaptchaServiceType.NineKW => new NineKWService(settings.NineKWApiKey),
                CaptchaServiceType.CustomAntiCaptcha => new CustomAntiCaptchaService(settings.CustomAntiCaptchaApiKey,
                                                                                     GetUri(settings.CustomAntiCaptchaDomain, settings.CustomAntiCaptchaPort)),
                CaptchaServiceType.AnyCaptcha => new AnyCaptchaService(settings.AnyCaptchaApiKey),
                _ => throw new NotSupportedException(),
            };

            service.Timeout         = TimeSpan.FromSeconds(settings.TimeoutSeconds);
            service.PollingInterval = TimeSpan.FromMilliseconds(settings.PollingIntervalMilliseconds);
            return(service);
        }
Ejemplo n.º 4
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            CaptchaService captchaService =
                context.HttpContext.RequestServices.GetRequiredService <CaptchaService>();

            var descriptor = context.ActionDescriptor as ControllerActionDescriptor;

            if (descriptor != null)
            {
                var parameters = descriptor.MethodInfo.GetParameters();

                var modelParameter = parameters.FirstOrDefault(x => x.ParameterType.IsSubclassOf(typeof(CaptchaArgs)));

                var model = (CaptchaArgs)context.ActionArguments[modelParameter.Name];

                if (!captchaService.VerifyToken(model.CaptchaToken, model.CaptchaText))
                {
                    context.Result =
                        ((Controller)context.Controller).BadRequest(
                            new Error("CaptchaValidationError", "Captcha text not valid", ErrorType.Soft));
                }

                base.OnActionExecuting(context);
            }
        }
Ejemplo n.º 5
0
 public ActionResult SetComment(FormCollection collection)
 {
     try
     {
         if (!Request.Url.Authority.Contains("localhost"))
         {
             var service = new CaptchaService();
             if (!service.IsValidCaptcha(collection["captch"]))
             {
                 SessionParameters.HasLoginPasswordError = true;
                 throw new Exception(Resources.CommonComponent.Enterthesecuritycodeisnotvalid);
             }
         }
         var ip = WebUtility.GetClientIp();
         if (string.IsNullOrEmpty(collection["Name"]))
         {
             ShowMessage(Resources.Congress.PleaseEnterYourName, Resources.Common.MessaageTitle,
                         messageIcon: MessageIcon.Error);
             return(Content("false"));
         }
         if (string.IsNullOrEmpty(collection["Description"]))
         {
             ShowMessage(Resources.Congress.PleaseEnterYourComment, Resources.Common.MessaageTitle,
                         messageIcon: MessageIcon.Error);
             return(Content("false"));
         }
         var comment = CongressComponent.Instance.BaseInfoComponents.ArticleUserCommentFacade.FirstOrDefault(x => x.ArticleId == collection["ArticleId"].ToGuid() && x.IP == ip);
         if (comment == null || !string.IsNullOrEmpty(comment.Description))
         {
             comment = new ArticleUserComment()
             {
                 IP = ip
             };
             RadynTryUpdateModel(comment, collection);
             if (!CongressComponent.Instance.BaseInfoComponents.ArticleUserCommentFacade.Insert(comment))
             {
                 ShowMessage(Resources.Congress.ErrorInInsertComment, Resources.Common.MessaageTitle,
                             messageIcon: MessageIcon.Error);
                 return(Content("false"));
             }
         }
         else
         {
             RadynTryUpdateModel(comment, collection);
             if (!CongressComponent.Instance.BaseInfoComponents.ArticleUserCommentFacade.Update(comment))
             {
                 ShowMessage(Resources.Congress.ErrorInInsertComment, Resources.Common.MessaageTitle,
                             messageIcon: MessageIcon.Error);
                 return(Content("false"));
             }
         }
         return(Content("true"));
     }
     catch (Exception ex)
     {
         ShowExceptionMessage(ex);
         return(Content("false"));
     }
 }
Ejemplo n.º 6
0
        public async Task SetCaptchaAction(CaptchaConfig.Action action = CaptchaConfig.Action.Kick)
        {
            var config = CaptchaService.GetCaptchaConfig(Context.Guild.Id);

            config.MaxFailuresAction = action;
            CaptchaService.SaveCaptchaConfig(config);
            await ReplyAsync($"Max Failure Action: {action}");
        }
Ejemplo n.º 7
0
 public ActionResult RegisterNewsLetter(FormCollection collection)
 {
     try
     {
         var messageStack = new List <string>();
         if (!Request.Url.Authority.Contains("localhost"))
         {
             var service = new CaptchaService();
             if (!service.IsValidCaptcha(collection["captch"]))
             {
                 messageStack.Add(Resources.CommonComponent.Enterthesecuritycodeisnotvalid);
             }
         }
         if (string.IsNullOrEmpty(collection["mail"]))
         {
             messageStack.Add(Resources.Congress.PleaseEnterYourEmail);
         }
         else
         {
             if (!Utility.Utils.IsEmail(collection["mail"]))
             {
                 messageStack.Add(Resources.Congress.UnValid_Enter_Email);
             }
         }
         var messageBody = messageStack.Aggregate("", (current, item) => current + Tag.Li(item));
         if (messageBody != "")
         {
             return(Json(new { Result = false, Message = messageBody }, JsonRequestBehavior.AllowGet));
         }
         var model = CongressComponent.Instance.BaseInfoComponents.NewsLetterFacade.Get(this.Homa.Id, collection["mail"]);
         if (model == null)
         {
             var newsLetter = new NewsLetter {
                 CongressId = this.Homa.Id, Email = collection["mail"]
             };
             return
                 (Json(
                      CongressComponent.Instance.BaseInfoComponents.NewsLetterFacade.Insert(newsLetter)
                         ? new { Result = true, Message = Resources.Congress.YourEmailSuccedRegisterInNewsLetter }
                         : new { Result = false, Message = Resources.Common.ErrorInInsert },
                      JsonRequestBehavior.AllowGet));
         }
         return(Json(new { Result = false, Message = Resources.Congress.YourEmailRegisteredInCongressNewsLetter }, JsonRequestBehavior.AllowGet));
     }
     catch (Exception ex)
     {
         if (ex.InnerException != null)
         {
             ShowMessage(ex.Message + " " + ex.InnerException.Message, "", messageIcon: MessageIcon.Security);
         }
         else
         {
             ShowMessage(ex.Message, "", messageIcon: MessageIcon.Security);
         }
         ViewBag.Message = ex.Message;
         return(Json(new { Result = false, Message = ViewBag.Message }, JsonRequestBehavior.AllowGet));
     }
 }
Ejemplo n.º 8
0
        public async Task SetCaptchaChannel()
        {
            var config = CaptchaService.GetCaptchaConfig(Context.Guild.Id);

            config.ChannelId = Context.Channel.Id;
            CaptchaService.SaveCaptchaConfig(config);

            await ReplyAsync($"Captcha channel set to the current channel.");
        }
Ejemplo n.º 9
0
        public void GetCaptcha_ShouldBeTWOPlus2()
        {
            var stub = new Mock<IRandomNumber>();
            stub.Setup(randomer => randomer.GetPattern()).Returns(() => 1);
            stub.Setup(randomer => randomer.GetOperator()).Returns(() => 1);
            stub.Setup(randomer => randomer.GetOperand()).Returns(() => 2);

            CaptchaService service = new CaptchaService(stub.Object);
            Assert.AreEqual("TWO + 2", service.GetCaptcha().Get());
        }
Ejemplo n.º 10
0
        public async Task ToggleCaptcha()
        {
            var config = CaptchaService.GetCaptchaConfig(Context.Guild.Id);

            config.UseCaptcha = !config.UseCaptcha;
            CaptchaService.SaveCaptchaConfig(config);

            await ReplyAsync($"UseCaptcha: {config.UseCaptcha}\n" +
                             "Note: Please ensure you set a captcha channel (using the `SetChannel` command) as the bot will message there in the event that it cannot dm the user directly");
        }
Ejemplo n.º 11
0
        public void SolveCaptchasWithSimpleSolver()
        {
            SimpleCaptchaSolver solver  = new SimpleCaptchaSolver();
            StringInputParser   parser  = new StringInputParser();
            CaptchaService      service = new CaptchaService(parser, solver);

            Assert.Equal(3, service.SolveCaptcha("1122"));
            Assert.Equal(4, service.SolveCaptcha("1111"));
            Assert.Equal(0, service.SolveCaptcha("1234"));
            Assert.Equal(9, service.SolveCaptcha("91212129"));
        }
Ejemplo n.º 12
0
        public async Task CaptchaSettings()
        {
            var config = CaptchaService.GetCaptchaConfig(Context.Guild.Id);

            await ReplyAsync($"**CAPTCHA SETTINGS**\n" +
                             $"Use Captcha: {config.UseCaptcha}\n" +
                             $"Temp Role: {Context.Guild.GetRole(config.CaptchaTempRole)?.Mention ?? "N/A"}\n" +
                             $"Max Captcha Failures: {config.MaxFailures}\n" +
                             $"Max Captcha Failures Action: {config.MaxFailuresAction}\n" +
                             $"Captcha channel: {Context.Guild.GetTextChannel(config.ChannelId)?.Mention ?? "N/A, it is recommended that you set this asap"}");
        }
Ejemplo n.º 13
0
        public void GetCaptcha_ShouldBe2PlusTWO()
        {
            var stub = new Mock <IRandomNumber>();

            stub.Setup(randomer => randomer.GetPattern()).Returns(() => 2);
            stub.Setup(randomer => randomer.GetOperator()).Returns(() => 1);
            stub.Setup(randomer => randomer.GetOperand()).Returns(() => 2);

            CaptchaService service = new CaptchaService(stub.Object);

            Assert.AreEqual("2 + TWO", service.GetCaptcha().Get());
        }
Ejemplo n.º 14
0
        public void SolveCaptchasWithCircularSolver()
        {
            CircularCaptchaSolver solver  = new CircularCaptchaSolver();
            StringInputParser     parser  = new StringInputParser();
            CaptchaService        service = new CaptchaService(parser, solver);

            Assert.Equal(6, service.SolveCaptcha("1212"));
            Assert.Equal(0, service.SolveCaptcha("1221"));
            Assert.Equal(4, service.SolveCaptcha("123425"));
            Assert.Equal(12, service.SolveCaptcha("123123"));
            Assert.Equal(4, service.SolveCaptcha("12131415"));
        }
Ejemplo n.º 15
0
        public async Task CaptchaAsync()
        {
            DirectoryInfo dir = new DirectoryInfo(CaptchaPath);

            FileInfo[] Files = dir.GetFiles("*.png");

            int index = Rand.Next(Files.Length);

            var message = await Context.Channel.SendFileAsync(Files[index].FullName, "Reply with text in Image.");

            var captchaState = new CaptchaState(message, Path.GetFileNameWithoutExtension(Files[index].Name));

            CaptchaService.AddCaptcha(captchaState);
        }
Ejemplo n.º 16
0
        public async Task SetCaptchaWarnings(int count = 3)
        {
            var config = CaptchaService.GetCaptchaConfig(Context.Guild.Id);

            if (config.SetMaxFailures(count))
            {
                CaptchaService.SaveCaptchaConfig(config);
                await ReplyAsync("Max Failures for captcha: {count}");
            }
            else
            {
                await ReplyAsync($"Maximum failures must be greater than or equal to 1");
            }
        }
Ejemplo n.º 17
0
        private void cbbCapchaType_SelectedIndexChanged(object sender, EventArgs e)
        {
            CaptchaService captchaServicename = (CaptchaService)Enum.ToObject(typeof(CaptchaService), cbbCapchaType.SelectedIndex);

            captchaService = captchaServicename;
            try
            {
                lbbalan.Text = "checking...";
                new Thread(() =>
                {
                    checkapi();
                }).Start();
            }
            catch { }
        }
Ejemplo n.º 18
0
        static void Main(string[] args)
        {
            // Part One
            FileInputParser     parser  = new FileInputParser();
            SimpleCaptchaSolver solver  = new SimpleCaptchaSolver();
            CaptchaService      service = new CaptchaService(parser, solver);

            Console.WriteLine(service.SolveCaptcha("inputs/part-one.txt"));

            // Part Two
            CircularCaptchaSolver circularSolver  = new CircularCaptchaSolver();
            CaptchaService        circularService = new CaptchaService(parser, circularSolver);

            Console.WriteLine(circularService.SolveCaptcha("inputs/part-one.txt"));
        }
        /// <summary>
        ///     Agendar una cita por horario
        /// </summary>
        /// <param name="GeneralCitaDto"></param>
        /// <returns></returns>
        public async Task <ActionResult> AgendarCita(GeneralCitaDTO GeneralCitaDto)
        {
            var numeroFolio = Enumeracion.EnumVarios.Prefijo + "Excepción general";

            try
            {
                if (string.IsNullOrEmpty(GeneralCitaDto.RespuestaCaptcha))
                {
                    return(Json(
                               Enumeracion.EnumVarios.Prefijo +
                               Enumeracion.MensajesServidor[Enumeracion.EnumConstErrores.ErrorCaptchaNoProporcionada],
                               JsonRequestBehavior.AllowGet));
                }

                bool esCaptchaValido = CaptchaService.ValidarCaptcha(GeneralCitaDto.RespuestaCaptcha);

                if (!esCaptchaValido)
                {
                    return(Json(
                               Enumeracion.EnumVarios.Prefijo +
                               Enumeracion.MensajesServidor[Enumeracion.EnumConstErrores.ErrorCaptchaNoValido],
                               JsonRequestBehavior.AllowGet));
                }

                var citaDto     = new CitaDTO();
                var citaService = new CitaService();
                numeroFolio = citaService.AgendarCita(GeneralCitaDto);


                if (!string.IsNullOrEmpty(numeroFolio) && !numeroFolio.Contains(Enumeracion.EnumVarios.Prefijo))
                {
                    GeneralCitaDto.NumeroFolio = numeroFolio;

                    citaDto.NumeroFolio = numeroFolio;
                    citaDto             = citaService.GetCita(GeneralCitaDto);

                    await SendMail(Enumeracion.EnumConsCorreo.CuerpoCorreoCitaAgendada,
                                   Enumeracion.EnumConsCorreo.TituloCorreoCitaAgendada, Enumeracion.EnumConsCorreo.NotaCitaAgendada, citaDto);
                }
            }
            catch (Exception ex)
            {
                //Log
                EscribirLog(new ExceptionContext(ControllerContext, ex));
            }

            return(Json(numeroFolio, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 20
0
        public async Task <ActionResult> Login(LoginViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("نام کاربری یا رمز عبور را وارد کنید");
                }
                if (!WebUtility.IsLocal() && SessionParameters.HasLoginPasswordError)
                {
                    var service = new CaptchaService();
                    if (!service.IsValidCaptcha(model.Captch))
                    {
                        throw new Exception(Resources.CommonComponent.Enterthesecuritycodeisnotvalid);
                    }
                }
                var userName = model.Username;
                var password = model.Password;
                var referee  = await CongressComponent.Instance.BaseInfoComponents.RefereeFacade.LoginAsync(userName, password, this.Homa.Id);

                if (referee == null)
                {
                    throw new Exception(Resources.Security.Please_enter_the_correct_values);
                }
                if (!referee.Enabled)
                {
                    throw new Exception("اطلاعات کابری شما غیر فعال است");
                }
                SessionParameters.HasLoginPasswordError = false;
                SessionParameters.CongressReferee       = referee;
                return(!string.IsNullOrEmpty(Request.QueryString["returnUrl"])
                    ? this.RadynRedirect(Request.QueryString["returnUrl"])
                    : this.Redirect("~/Congress/RefereePanel/RefereeCartablIndex"));
            }
            catch (Exception ex)
            {
                SessionParameters.HasLoginPasswordError = true;
                ShowMessage(ex.Message, "", messageIcon: MessageIcon.Security);
                ViewBag.Message = ex.Message;
                model           = new LoginViewModel()
                {
                    Username = model.Username
                };
                return(View(model));
            }
        }
        public async Task <CaptchaSolveResult> Solve(CaptchaService captchaProvider)
        {
            try
            {
                var result = await captchaProvider.SolveHCaptchaAsync(SiteKey, SiteUrl.AbsoluteUri);

                return(new CaptchaSolveResult
                {
                    Response = result.Response,
                    Success = true
                });
            }
            catch
            {
                return(new CaptchaSolveResult
                {
                    Response = "",
                    Success = false
                });
            }
        }
        /// <summary>
        ///     Consulta de una cita
        /// </summary>
        /// <param name="CitaDto"></param>
        /// <returns></returns>
        public ActionResult VerSolicitud(CitaDTO CitaDto)
        {
            Enumeracion.MensajesServidor = new LenguajeCiudadanoService().ConsultaLenguajeCiudadanoServer();

            if (string.IsNullOrEmpty(CitaDto.RespuestaCaptcha))
            {
                return(Json(
                           Enumeracion.EnumVarios.Prefijo +
                           Enumeracion.MensajesServidor[Enumeracion.EnumConstErrores.ErrorCaptchaNoProporcionada],
                           JsonRequestBehavior.AllowGet));
            }

            bool esCaptchaValido = CaptchaService.ValidarCaptcha(CitaDto.RespuestaCaptcha);

            if (!esCaptchaValido)
            {
                return(Json(
                           Enumeracion.EnumVarios.Prefijo +
                           Enumeracion.MensajesServidor[Enumeracion.EnumConstErrores.ErrorCaptchaNoValido],
                           JsonRequestBehavior.AllowGet));
            }

            var citaService = new CitaService();

            CitaDto = citaService.GetCita(CitaDto);

            if (CitaDto == null)
            {
                return(Json(
                           Enumeracion.EnumVarios.Prefijo +
                           Enumeracion.MensajesServidor[Enumeracion.EnumConstErrores.CitaNoEncontrada],
                           JsonRequestBehavior.AllowGet));
            }


            CitaDto.EsRepresentante = (CitaDto.Promovente.CURP != CitaDto.Paciente.CURP);
            CitaDto.ConFolio        = true;
            return(PartialView(CitaDto));
        }
Ejemplo n.º 23
0
 public ResolveState Resolve(CaptchaStatics statics, CaptchaService service)
 {
     if (service == CaptchaService.CAP_MONSTER)
     {
         Capmonter capmonter = new Capmonter(statics);
         return(capmonter.ResoloveCaptcha());
     }
     else if (service == CaptchaService.ANTI_CAPTCHA)
     {
         AntiCaptcha antiCaptcha = new AntiCaptcha(statics);
         return(antiCaptcha.ResovleCaptcha());
     }
     else if (service == CaptchaService.BYPASS)
     {
         AntiCaptcha antiCaptcha = new AntiCaptcha(statics);
         return(antiCaptcha.ResovleCaptcha());
     }
     else
     {
         _2Captcha _2Captcha = new _2Captcha(statics.Apikey);
         return(_2Captcha.SolveRecaptchaV2(YolikerStatics.GooglePublicKey, YolikerStatics.LikeCustomUri, out statics.SolvedCaptchaResponse));
     }
 }
Ejemplo n.º 24
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            if (DisplayCaptcha && !dnfValid.IsValid())
            {
                ShowMessage(Notify.NotifyType.Error, Resources.Resource.Client_Feedback_WrongData);
                dnfValid.TryNew();
                return;
            }

            if (!(string.IsNullOrEmpty(txtEmail.Text.Trim()) || string.IsNullOrEmpty(txtPassword.Text.Trim())))
            {
                if (!AuthorizeService.SignIn(txtEmail.Text, txtPassword.Text, false, true))
                {
                    CaptchaService.AddIPtoList(Request.UserHostAddress);
                    dnfValid.TryNew();
                    ShowMessage(Notify.NotifyType.Error, Resources.Resource.Client_MasterPage_WrongPassword);
                }
                else
                {
                    CaptchaService.RemoveIPfromList(Request.UserHostAddress);
                    Response.Redirect("~/");
                }
            }
        }
Ejemplo n.º 25
0
 public CaptchaController(
     CaptchaService captchaService,
     IServiceProvider serviceProvider) : base(serviceProvider)
 {
     this.captchaService = captchaService;
 }
Ejemplo n.º 26
0
        public async Task <ActionResult> Login(LoginViewModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    throw new Exception("نام کاربری یا رمز عبور را وارد کنید");
                }
                if (!WebUtility.IsLocal() && SessionParameters.HasLoginPasswordError)
                {
                    var service = new CaptchaService();
                    if (!service.IsValidCaptcha(model.Captch))
                    {
                        throw new Exception(Resources.CommonComponent.Enterthesecuritycodeisnotvalid);
                    }
                }
                var userName = model.Username;
                var password = model.Password;
                if (FormsAuthentication.Authenticate(userName, StringUtils.Encrypt(password)))
                {
                    FormsAuthentication.SetAuthCookie(userName, false);
                    switch (userName.ToLower())
                    {
                    case "host":
                        SessionParameters.UserType      = UserType.Host;
                        SessionParameters.UserOperation = await SecurityComponent.Instance.OperationFacade.GetAllAsync();

                        break;
                    }
                    SessionParameters.Culture = "fa-IR";
                    SessionParameters.HasLoginPasswordError = false;
                    return(!string.IsNullOrEmpty(Request.QueryString["returnUrl"])
                        ? this.Redirect(Request.QueryString["returnUrl"])
                        : this.Redirect("~/Account/Index"));
                }
                var user = await SecurityComponent.Instance.UserFacade.LoginAsync(userName, password);

                if (user == null)
                {
                    throw new Exception(Resources.Security.Please_enter_the_correct_values);
                }
                FormsAuthentication.SetAuthCookie(user.Username, false);
                SessionParameters.User          = user;
                SessionParameters.UserOperation = await SecurityComponent.Instance.OperationFacade.GetAllByUserIdAsync(user.Id);

                SessionParameters.UserType = UserType.User;
                SessionParameters.Culture  = "fa-IR";
                SessionParameters.HasLoginPasswordError = false;
                return(!string.IsNullOrEmpty(Request.QueryString["returnUrl"])
                    ? this.Redirect(Request.QueryString["returnUrl"])
                    : this.Redirect("~/Account/Index"));
            }
            catch (Exception ex)
            {
                SessionParameters.HasLoginPasswordError = true;
                ShowMessage(ex.Message, "", messageIcon: MessageIcon.Security);
                ViewBag.Message = ex.Message;
                model           = new LoginViewModel()
                {
                    Username = model.Username
                };
                return(View(model));
            }
        }
Ejemplo n.º 27
0
 public void GetCaptcha_ShouldReturnCaptchaObject()
 {
     CaptchaService service = new CaptchaService();
     Assert.IsInstanceOf(typeof(Captcha), service.GetCaptcha());
 }
Ejemplo n.º 28
0
        public void GetCaptchaPatternTWO_ShouldBe1PlusNINE_WhenRandomIs2119()
        {
            CaptchaService captchaService = StubRandomNumberCaptcha(2, 1, 1, 9);

            Assert.AreEqual("1+NINE", captchaService.GetCaptcha());
        }
Ejemplo n.º 29
0
 public CaptchaSharpProvider(RuriLibSettingsService settings)
 {
     service = CaptchaServiceFactory.GetService(settings.RuriLibSettings.CaptchaSettings);
     CheckBalanceBeforeSolving = settings.RuriLibSettings.CaptchaSettings.CheckBalanceBeforeSolving;
     ServiceType = settings.RuriLibSettings.CaptchaSettings.CurrentService;
 }
Ejemplo n.º 30
0
        /// <inheritdoc />
        public override void Process(BotData data)
        {
            base.Process(data);

            // If the clearance info is already set and we're not getting it fresh each time, skip
            if (data.UseProxies)
            {
                if (data.Proxy.Clearance != "" && !data.GlobalSettings.Proxies.AlwaysGetClearance)
                {
                    data.Log(new LogEntry("Skipping CF Bypass because there is already a valid cookie", Colors.White));
                    data.Cookies["cf_clearance"] = data.Proxy.Clearance;
                    data.Cookies["__cfduid"]     = data.Proxy.Cfduid;
                    return;
                }
            }

            var localUrl = ReplaceValues(url, data);
            var uri      = new Uri(localUrl);

            // Initialize the captcha provider
            CaptchaService service = Captchas.GetService(data.GlobalSettings.Captchas);

            // Initialize the Cloudflare Solver
            CloudflareSolver cf = new CloudflareSolver(service, ReplaceValues(UserAgent, data))
            {
                ClearanceDelay  = 3000,
                MaxCaptchaTries = 1,
                MaxTries        = 3
            };

            // Create the cookie container
            CookieContainer cookies = new CookieContainer();

            foreach (var cookie in data.Cookies)
            {
                cookies.Add(new Cookie(cookie.Key, cookie.Value, "/", uri.Host));
            }

            // Initialize the http handler
            HttpClientHandler handler = new HttpClientHandler
            {
                AllowAutoRedirect      = AutoRedirect,
                CookieContainer        = cookies,
                AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
                SslProtocols           = SecurityProtocol.ToSslProtocols()
            };

            // Assign the proxy to the inner handler if necessary
            if (data.UseProxies)
            {
                if (data.Proxy.Type != Extreme.Net.ProxyType.Http)
                {
                    throw new Exception($"The proxy type {data.Proxy.Type} is not supported by this block yet");
                }

                handler.Proxy    = new WebProxy(data.Proxy.Proxy, false);
                handler.UseProxy = true;

                if (!string.IsNullOrEmpty(data.Proxy.Username))
                {
                    handler.DefaultProxyCredentials = new NetworkCredential(data.Proxy.Username, data.Proxy.Password);
                }
            }

            // Initialize the http client
            HttpClient http = new HttpClient(handler);

            http.Timeout = TimeSpan.FromSeconds(data.GlobalSettings.General.RequestTimeout);
            http.DefaultRequestHeaders.Add("User-Agent", ReplaceValues(UserAgent, data));

            SolveResult result = new SolveResult();

            try
            {
                result = cf.Solve(http, handler, uri, ReplaceValues(UserAgent, data)).Result;
            }
            catch (AggregateException ex)
            {
                // Join all the aggregate exception inner exception messages
                var message = string.Join(Environment.NewLine, ex.InnerExceptions.Select(e => e.Message));

                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.Log(new LogEntry(message, Colors.Tomato));
                    data.ResponseCode = message;
                    return;
                }
                throw new Exception(message);
            }
            catch (Exception ex)
            {
                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.Log(new LogEntry(ex.Message, Colors.Tomato));
                    data.ResponseSource = ex.Message;
                    return;
                }
                throw;
            }

            if (result.Success)
            {
                data.Log(new LogEntry($"[Success] Protection bypassed: {result.DetectResult.Protection}", Colors.GreenYellow));
            }
            else if (result.DetectResult.Protection == CloudflareProtection.Unknown)
            {
                data.Log(new LogEntry($"Unknown protection, skipping the bypass!", Colors.Tomato));
            }
            else
            {
                var message = $"CF Bypass Failed: {result.FailReason}";

                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.Log(new LogEntry(message, Colors.Tomato));
                    data.ResponseSource = message;
                    return;
                }
                throw new Exception(message);
            }

            // Now that we got the cookies, proceed with the normal request
            HttpResponseMessage response = null;

            try
            {
                response = http.GetAsync(uri).Result;
            }
            catch (Exception ex)
            {
                if (data.ConfigSettings.IgnoreResponseErrors)
                {
                    data.ResponseSource = ex.Message;
                    return;
                }
                throw new Exception(ex.Message);
            }
            finally
            {
                handler.Dispose();
                http.Dispose();
            }

            var responseString = response.Content.ReadAsStringAsync().Result;

            // Save the cloudflare cookies
            var clearance = "";
            var cfduid    = "";

            foreach (Cookie cookie in cookies.GetCookies(uri))
            {
                switch (cookie.Name)
                {
                case "cf_clearance":
                    clearance = cookie.Value;
                    break;

                case "__cfduid":
                    cfduid = cookie.Value;
                    break;
                }
            }

            // Save the cookies in the proxy
            if (data.UseProxies)
            {
                data.Proxy.Clearance = clearance;
                data.Proxy.Cfduid    = cfduid;
            }

            if (clearance != "")
            {
                data.Log(new LogEntry("Got Cloudflare clearance!", Colors.GreenYellow));
                data.Log(new LogEntry(clearance + Environment.NewLine + cfduid + Environment.NewLine, Colors.White));
            }

            // Get address
            data.Address = response.RequestMessage.RequestUri.AbsoluteUri;
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry($"Address: {data.Address}", Colors.Cyan));
            }

            // Get code
            data.ResponseCode = ((int)response.StatusCode).ToString();
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry($"Response code: {data.ResponseCode}", Colors.Cyan));
            }

            // Get headers
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Received headers:", Colors.DeepPink));
            }
            data.ResponseHeaders.Clear();
            foreach (var header in response.Headers)
            {
                var h = new KeyValuePair <string, string>(header.Key, header.Value.First());
                data.ResponseHeaders.Add(h.Key, h.Value);
                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"{h.Key}: {h.Value}", Colors.LightPink));
                }
            }

            // Add the Content-Length header if it was not sent by the server
            if (!data.ResponseHeaders.ContainsKey("Content-Length"))
            {
                if (data.ResponseHeaders.ContainsKey("Content-Encoding") && data.ResponseHeaders["Content-Encoding"].Contains("gzip"))
                {
                    data.ResponseHeaders["Content-Length"] = GZip.Zip(responseString).Length.ToString();
                }
                else
                {
                    data.ResponseHeaders["Content-Length"] = responseString.Length.ToString();
                }

                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"Content-Length: {data.ResponseHeaders["Content-Length"]}", Colors.LightPink));
                }
            }

            // Get cookies
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Received cookies:", Colors.Goldenrod));
            }
            foreach (Cookie cookie in cookies.GetCookies(uri))
            {
                data.Cookies[cookie.Name] = cookie.Value;
                if (PrintResponseInfo)
                {
                    data.Log(new LogEntry($"{cookie.Name}: {cookie.Value}", Colors.LightGoldenrodYellow));
                }
            }

            // Print source
            data.ResponseSource = responseString;
            if (PrintResponseInfo)
            {
                data.Log(new LogEntry("Response Source:", Colors.Green));
                data.Log(new LogEntry(data.ResponseSource, Colors.GreenYellow));
            }
        }
 internal CaptchaChallengeSolver(CloudflareHandler handler, Uri siteUrl, DetectResult detectResult, string userAgent, CaptchaService captchaProvider)
     : base(handler, siteUrl, detectResult, userAgent)
 {
     this.captchaProvider = captchaProvider;
 }
Ejemplo n.º 32
0
        public void GetCaptchaPatternTWO_ShouldBe9MinusNINE_WhenRandomIs2939()
        {
            CaptchaService captchaService = StubRandomNumberCaptcha(2, 9, 3, 9);

            Assert.AreEqual("9-NINE", captchaService.GetCaptcha());
        }