예제 #1
0
        /// <summary>
        ///     Makes the specified captcha "intelligent".
        /// </summary>
        /// <param name="captchaManager">The specified captcha manager.</param>
        /// <param name="captcha">
        ///     The specified <see cref="ICaptcha" />.
        /// </param>
        /// <param name="parameterContainer">
        ///     The specified <see cref="IParameterContainer" />.
        /// </param>
        /// <returns>
        ///     An instance of <see cref="ICaptcha" />.
        /// </returns>
        public virtual ICaptcha MakeIntelligent(ICaptchaManager captchaManager, ICaptcha captcha, IParameterContainer parameterContainer)
        {
            Validate.ArgumentNotNull(captchaManager, "captchaManager");
            Validate.ArgumentNotNull(captcha, "captcha");
            if (captcha.BuildInfo.HtmlHelper.ViewData[DefaultCaptchaManager.CaptchaNotValidViewDataKey] != null)
            {
                return(captcha);
            }
            var captchaDecorator = captcha as IntelligentCaptchaDecorator;

            if (captchaDecorator != null && captchaDecorator.PolicyType.Equals(PolicyType))
            {
                return(captcha);
            }

            var tokenName = captchaManager.TokenElementName + PolicyType;
            var markup    = new StringBuilder(RenderMarkup(captcha, tokenName));
            var script    = new StringBuilder();

            foreach (IIntelligencePolicy intelligencePolicy in Policies)
            {
                ICaptcha cp = intelligencePolicy.MakeIntelligent(captchaManager, captcha, parameterContainer);
                markup.AppendLine(cp.RenderMarkup().ToHtmlString());
                script.AppendLine(cp.RenderScript().ToHtmlString());
            }
            return(new IntelligentCaptchaDecorator(captcha, captcha1 => markup.ToString(), captcha1 => script.ToString(),
                                                   PolicyType));
        }
예제 #2
0
        public IActionResult CheckCaptcha(string id, string code)
        {
            ICaptcha captcha = _provider.GetRequiredService <ICaptcha>();
            bool     flag    = captcha.Validate(id, code, false);

            return(new JsonResult(flag));
        }
예제 #3
0
 public ContactController(IStringLocalizer <ContactController> localizer, ICaptcha captcha, IOptions <EnginexEmailSettings> enginexEmail, ILogger logger)
 {
     this.localizer    = localizer;
     this.captcha      = captcha;
     this.enginexEmail = enginexEmail;
     this.logger       = logger;
 }
예제 #4
0
        public IActionResult Captcha(string id)
        {
            ICaptcha     captcha = _provider.GetRequiredService <ICaptcha>();
            CaptchaData  data    = captcha.Generate(id);
            MemoryStream ms      = new MemoryStream(data.Bytes);

            return(File(ms, "image/gif"));
        }
예제 #5
0
 public SearchController(IDatabase database, ILogger <SearchController> logger, IAuthHandler authHandler,
                         ICaptcha captcha)
 {
     _database    = database;
     _logger      = logger;
     _authHandler = authHandler;
     _captcha     = captcha;
 }
예제 #6
0
 public PostController(IDatabase database, IAuthHandler authHandler, IActivityLogger activityLogger,
                       ILogger <PostController> logger, ICaptcha captcha)
 {
     _database       = database;
     _authHandler    = authHandler;
     _activityLogger = activityLogger;
     _logger         = logger;
     _captcha        = captcha;
 }
예제 #7
0
        private CaptchaInfo CreateCaptcha(SecurityParameter[] parameters, ICaptcha provider)
        {
            int             captchaHeight   = Convert.ToInt32(GetParameterValue(parameters, "CaptchaHeight") ?? "100");
            int             captchaWidth    = Convert.ToInt32(GetParameterValue(parameters, "CaptchaWidth") ?? "100");
            int             captchaNumChars = Convert.ToInt32(GetParameterValue(parameters, "CaptchaNumChars") ?? "5");
            CaptchaSettings settings        = new CaptchaSettings(captchaHeight, captchaWidth, "GenericSerif", captchaNumChars, false);

            return(provider.Generate(settings));
        }
예제 #8
0
파일: Board.cs 프로젝트: Janek91/Chan.Net
        public async Task <Thread> CreateThreadAsync(string message, ICaptcha captcha, OptionalPostArgs args)
        {
            uint resp = await PostManager.CreatePost(this, null, message, captcha, args).ConfigureAwait(false);

            var newThread = new Thread(this, resp);

            newThread.AutoUpdater.SuscribePost(newThread);

            return(newThread);
        }
예제 #9
0
 protected override void OnLoad(EventArgs e)
 {
     base.OnLoad(e);
     if (!this.Visible)
     {
         captcha = captchProvider.GetCaptcha();
         Control innerCaptchaControl = captcha.GetControl();
         innerCaptchaControl.Visible = false;
         this.Controls.Clear();
     }
 }
예제 #10
0
 public AccountController(IMemoryCache memoryCache, IAuthHandler authHandler,
                          IWebHostEnvironment webHostEnvironment, IActivityLogger activityLogger, ILogger <AccountController> logger,
                          ICaptcha captcha)
 {
     _memoryCache        = memoryCache;
     _authHandler        = authHandler;
     _webHostEnvironment = webHostEnvironment;
     _activityLogger     = activityLogger;
     _logger             = logger;
     _captcha            = captcha;
 }
예제 #11
0
        /// <summary>
        ///     Makes the captcha "intelligent".
        /// </summary>
        /// <param name="captcha">
        ///     The specified <see cref="ICaptcha" />.
        /// </param>
        /// <param name="parameters">The specified parameters, if any.</param>
        /// <returns>
        ///     An instance of <see cref="ICaptcha" />.
        /// </returns>
        public static ICaptcha AsIntelligent(this ICaptcha captcha, params ParameterModel[] parameters)
        {
            List <ParameterModel> list = CaptchaUtils.GetParameters(parameters);
            var container      = new CombinedParameterContainer(new ParameterModelContainer(list), captcha.BuildInfo.ParameterContainer);
            var captchaManager = CaptchaUtils.CaptchaManagerFactory(container);

            if (captchaManager.IntelligencePolicy == null)
            {
                throw new NullReferenceException("The IntelligencePolicy property is null.");
            }
            return(captchaManager.IntelligencePolicy.MakeIntelligent(captchaManager, captcha, container));
        }
예제 #12
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="IntelligentCaptchaDecorator" /> class.
 /// </summary>
 public IntelligentCaptchaDecorator(ICaptcha captcha, Func <ICaptcha, string> renderMarkup,
                                    Func <ICaptcha, string> renderScript, string policyType)
 {
     Validate.ArgumentNotNull(captcha, "captcha");
     Validate.ArgumentNotNull(renderMarkup, "renderMarkup");
     Validate.ArgumentNotNull(renderScript, "renderScript");
     Validate.ArgumentNotNull(policyType, "policyType");
     _captcha      = captcha;
     _renderMarkup = renderMarkup;
     _renderScript = renderScript;
     PolicyType    = policyType;
 }
 public CrosscuttingService()
 {
     if (mailSvc == null)
     {
         mailSvc = ContainerHelper.Instance.Resolve<IMailService>();
         mailSvc.ConfigureServer("smtp.yeah.net", 25, "pfagent", "pf18616379842");
     }
     if (captchaSvc == null)
     {
         captchaSvc = ContainerHelper.Instance.Resolve<ICaptcha>();
     }
 }
예제 #14
0
파일: Thread.cs 프로젝트: Janek91/Chan.Net
        public async Task <Post> CreatePostAsync(string message, ICaptcha captcha, OptionalPostArgs args)
        {
            uint id = await PostManager.CreatePost(Board, this, message, captcha, args).ConfigureAwait(false);

            var newPost = new Post()
            {
                Thread     = this,
                Message    = message,
                PostNumber = id,
                Name       = args.Name
            };

            AutoUpdater.SuscribePost(newPost);

            return(newPost);
        }
        private void SaveTokenValue(ICaptcha captcha)
        {
            switch (StorageType)
            {
            case StorageType.TempData:
                captcha.BuildInfo.HtmlHelper.ViewContext.TempData[captcha.BuildInfo.TokenValue] = DateTime.UtcNow;
                break;

            case StorageType.Session:
                var dictionary = CaptchaUtils.GetFromSession(SessionKey, () => new ConcurrentDictionary <KeyTimeEntry <string>, DateTime>());
                dictionary.ClearIfNeed(SessionValuesMaxCount);
                dictionary.TryAdd(captcha.BuildInfo.TokenValue, DateTime.UtcNow);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
        private void SaveTokenValue(ICaptcha captcha)
        {
            switch (StorageType)
            {
            case StorageType.TempData:
                captcha.BuildInfo.HtmlHelper.ViewContext.TempData[captcha.BuildInfo.TokenValue] = true;
                break;

            case StorageType.Session:
                var hashSet = CaptchaUtils.GetFromSession(SessionKey, () => new HashSet <KeyTimeEntry <string> >());
                hashSet.ClearIfNeed(SessionValuesMaxCount);
                hashSet.Add(captcha.BuildInfo.TokenValue);
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
예제 #17
0
        /// <summary>
        /// The validate.
        /// </summary>
        /// <param name="form">
        /// The form to be validated.
        /// </param>
        /// <returns>
        /// The validation result.
        /// </returns>
        private static bool Validate(ICaptcha form)
        {
            var image = CaptchaImage.GetCachedCaptcha(form.Guid);

            var actualValue = form.Captcha;
            var expectedValue = image == null
                                    ? String.Empty
                                    : image.Text;

            HttpContext.Current.Cache.Remove(form.Guid);

            if (String.IsNullOrEmpty(actualValue) || String.IsNullOrEmpty(expectedValue) ||
                !String.Equals(actualValue, expectedValue, StringComparison.OrdinalIgnoreCase))
            {
                return false;
            }

            return true;
        }
        /// <summary>
        ///     Makes the specified captcha "intelligent".
        /// </summary>
        /// <param name="captchaManager">The specified captcha manager.</param>
        /// <param name="captcha">
        ///     The specified <see cref="ICaptcha" />.
        /// </param>
        /// <param name="parameterContainer">
        ///     The specified <see cref="IParameterContainer" />.
        /// </param>
        /// <returns>
        ///     An instance of <see cref="ICaptcha" />.
        /// </returns>
        public virtual ICaptcha MakeIntelligent(ICaptchaManager captchaManager, ICaptcha captcha, IParameterContainer parameterContainer)
        {
            Validate.ArgumentNotNull(captchaManager, "captchaManager");
            Validate.ArgumentNotNull(captcha, "captcha");
            if (captcha.BuildInfo.HtmlHelper.ViewData[DefaultCaptchaManager.CaptchaNotValidViewDataKey] != null)
            {
                return(captcha);
            }
            var captchaDecorator = captcha as IntelligentCaptchaDecorator;

            if (captchaDecorator != null && captchaDecorator.PolicyType.Equals(PolicyType))
            {
                return(captcha);
            }
            SaveTokenValue(captcha);
            var tokenName = captchaManager.TokenElementName + PolicyType;

            return(new IntelligentCaptchaDecorator(captcha, c => RenderMarkup(c, tokenName), RenderScript, PolicyType));
        }
예제 #19
0
        protected override void OnInit(EventArgs e)
        {
            if (this.Site != null && this.Site.DesignMode)
            {
            }
            else
            {
                base.OnInit(e);
                // an exception always happens here in design mode
                // this try is just to fix the display in design view in VS

                try
                {
                    captchProvider = CaptchaManager.Providers[providerName];
                    captcha        = captchProvider.GetCaptcha();
                    this.Controls.Add(captcha.GetControl());
                }
                catch { }
            }
        }
예제 #20
0
        public async Task <AjaxResult> Register(RegisterDto dto)
        {
            Check.NotNull(dto, nameof(dto));

            if (!ModelState.IsValid)
            {
                return(new AjaxResult("提交信息验证失败", AjaxResultType.Error));
            }
            ICaptcha captcha = _provider.GetRequiredService <ICaptcha>();

            if (!captcha.Validate(dto.CaptchaId, dto.Captcha))
            {
                return(new AjaxResult("验证码错误,请刷新重试", AjaxResultType.Error));
            }

            dto.UserName ??= dto.Email;
            dto.NickName ??= $"User_{Random.NextLetterAndNumberString(8)}"; //随机用户昵称
            dto.RegisterIp = HttpContext.GetClientIp();

            OperationResult <User> result = await IdentityContract.Register(dto);

            if (result.Succeeded)
            {
                User   user = result.Data;
                string code = await UserManager.GenerateEmailConfirmationTokenAsync(user);

                code = UrlBase64ReplaceChar(code);
                string url  = $"{Request.Scheme}://{Request.Host}/#/passport/confirm-email?userId={user.Id}&code={code}";
                string body =
                    $"亲爱的用户 <strong>{user.NickName}</strong>[{user.UserName}],您好!<br>"
                    + $"欢迎注册,激活邮箱请 <a href=\"{url}\" target=\"_blank\"><strong>点击这里</strong></a><br>"
                    + $"如果上面的链接无法点击,您可以复制以下地址,并粘贴到浏览器的地址栏中打开。<br>"
                    + $"{url}<br>"
                    + $"祝您使用愉快!";
                await SendMailAsync(user.Email, "柳柳软件 注册邮箱激活邮件", body);

                return(result.ToAjaxResult(m => new { m.UserName, m.NickName, m.Email }));
            }
            return(result.ToAjaxResult());
        }
예제 #21
0
 public SyncWizardController(ITempSessionService tempSessionService, ITrackGetter trackGetter,
                             IQueryExecutorFactory queryExecutorFactory,
                             IYandexService yandexService, IAuthorizationSettings authorizationSettings,
                             IJsonSerializer jsonSerializer,
                             IJsonTrackGetter jsonTrackGetter,
                             IDomainService domainService,
                             IProgressBar progressBar,
                             IImportResultLogger importResultLogger,
                             ICaptcha captcha)
 {
     this.tempSessionService    = tempSessionService;
     this.trackGetter           = trackGetter;
     this.queryExecutorFactory  = queryExecutorFactory;
     this.yandexService         = yandexService;
     this.authorizationSettings = authorizationSettings;
     this.jsonSerializer        = jsonSerializer;
     this.jsonTrackGetter       = jsonTrackGetter;
     this.domainService         = domainService;
     this.progressBar           = progressBar;
     this.importResultLogger    = importResultLogger;
     this.captcha = captcha;
 }
예제 #22
0
        public async Task <IActionResult> Whois(string host, [FromServices] ICaptcha captcha)
        {
            if (!captcha.IsValidatedInSession())
            {
                return(Content("SHOW-CAPTCHA"));
            }

            // This should be rewritten in C# one day, but for now we just proxy to the PHP version.
            var msg = new HttpRequestMessage(
                HttpMethod.Post,
                _env.IsDevelopment() ? "http://127.0.0.1/whois.php" : "http://127.0.0.1/legacy/whois.php"
                );

            msg.Headers.Add("Host", _env.IsDevelopment() ? "legacy.dnstools.test" : HttpContext.Request.Host.Host);
            msg.Content = new FormUrlEncodedContent(new Dictionary <string, string>
            {
                { "host", host }
            });

            var response = await _clientFactory.CreateClient().SendAsync(msg, HttpContext.RequestAborted);

            return(Content(await response.Content.ReadAsStringAsync()));
        }
예제 #23
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="interactions"></param>
 /// <param name="loginService"></param>
 /// <param name="clientStore"></param>
 /// <param name="schemeProvider"></param>
 /// <param name="customerManager"></param>
 /// <param name="captcha"></param>
 /// <param name="environment"></param>
 /// <param name="emailSender"></param>
 /// <param name="templateGenerator"></param>
 /// <param name="eventService"></param>
 /// <param name="localizer"></param>
 /// <param name="logger"></param>
 public AccountController(
     IMediator mediator,
     IIdentityServerInteractionService interactions,
     IClientStore clientStore,
     IAuthenticationSchemeProvider schemeProvider,
     UserManager <Customer> customerManager,
     ICaptcha captcha,
     IHostingEnvironment environment,
     IEventService eventService,
     IStringLocalizer <AccountController> localizer,
     ILogger <AccountController> logger)
 {
     this.mediator        = mediator;
     this.interactions    = interactions;
     this.clientStore     = clientStore;
     this.schemeProvider  = schemeProvider;
     this.customerManager = customerManager;
     this.captcha         = captcha;
     this.environment     = environment;
     this.eventService    = eventService;
     this.localizer       = localizer;
     this.logger          = logger;
 }
예제 #24
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="imageFile">Only the name of the captcha file, not the path</param>
        /// <param name="text"></param>
        /// <returns></returns>
        public bool IsValid(ICaptcha model)
        {
            var path = Path.GetFileName(model.CaptchaPath);

            if (String.IsNullOrEmpty(path))
            {
                return(false);
            }
            if (String.IsNullOrEmpty(model.CaptchaCode))
            {
                return(false);
            }
            switch (path.ToUpper())
            {
            case "CAPTCHA-01.JPG":
                return(model.CaptchaCode.ToUpper() == "69JLPD");

            case "CAPTCHA-02.JPG":
                return(model.CaptchaCode.ToUpper() == "G5HIJM");

            case "CAPTCHA-03.JPG":
                return(model.CaptchaCode.ToUpper() == "1B2B94");

            case "CAPTCHA-04.JPG":
                return(model.CaptchaCode.ToUpper() == "ASD&56");

            case "CAPTCHA-05.JPG":
                return(model.CaptchaCode.ToUpper() == "ASA9B2");

            case "CAPTCHA-06.JPG":
                return(model.CaptchaCode.ToUpper() == "1792BR");

            default:
                return(false);
            }
        }
 public CaptchaHeadViewComponent(ICaptcha captcha) => Captcha = captcha;
예제 #26
0
 public AccountController(UserContext context, ICryptoService cryptoService, ICaptcha captcha)
 {
     db = context;
     this.cryptoService = cryptoService;
     this.captcha       = captcha;
 }
예제 #27
0
        protected override void OnInit(EventArgs e)
        {
            if (this.Site != null && this.Site.DesignMode)
            {

            }
            else
            {
                base.OnInit(e);
                // an exception always happens here in design mode
                // this try is just to fix the display in design view in VS

                    try
                    {
                        captchProvider = CaptchaManager.Providers[providerName];
                        captcha = captchProvider.GetCaptcha();
                        this.Controls.Add(captcha.GetControl());
                    }
                    catch { }

            }
        }
예제 #28
0
파일: Thread.cs 프로젝트: Janek91/Chan.Net
 public Post CreatePost(string message, ICaptcha captcha, OptionalPostArgs args)
 {
     return(CreatePostAsync(message, captcha, args).GetAwaiter().GetResult());
 }
예제 #29
0
 protected ServerObject()
 {
     captcha       = IoC.GetService <ICaptcha>();
     authorization = IoC.GetService <IAuthorization>();
 }
예제 #30
0
 /// <summary>
 ///     Renders only captcha markup, if any.
 /// </summary>
 /// <returns>
 ///     An instance of string.
 /// </returns>
 private static string RenderMarkup(ICaptcha captcha, string tokenElementName)
 {
     return(string.Format(InputHtml, captcha.BuildInfo.TokenValue, tokenElementName));
 }
예제 #31
0
        public static async Task <uint> CreatePost(Board board, Thread thread, string message, ICaptcha captcha, OptionalPostArgs args)
        {
            string url = string.Format("https://sys.4chan.org/{0}/post", board.BoardId);

            var postData = new Dictionary <string, object>();

            postData.Add("MAX_FILE_SIZE", "4194304");
            postData.Add("mode", "regist");
            postData.Add("name", args.Name);
            postData.Add("com", message);

            if (thread != null)
            {
                postData.Add("resto", thread.PostNumber.ToString());
            }

            if (!string.IsNullOrEmpty(args.Options))
            {
                postData.Add("email", args.Options);
            }

            if (!string.IsNullOrEmpty(args.Password))
            {
                postData.Add("pwd", args.Password);
            }
            else
            {
                var sb = new StringBuilder();
                var r  = new Random();

                for (var i = 0; i < 15; i++)
                {
                    sb.Append((char)(r.Next('a', 'z')));
                }

                postData.Add("pwd", sb.ToString());
            }

            if (!captcha.Solved)
            {
                throw new CaptchaException();
            }

            if (args.File != null)
            {
                var filename = "file";
                if (!string.IsNullOrEmpty(args.Filename))
                {
                    filename = args.Filename;
                }

                if (!mappings.ContainsKey(Path.GetExtension(filename).ToLower()))
                {
                    throw new UnsupportedFiletypeException(Path.GetExtension(filename));
                }

                var file = new byte[args.File.Length];

                await args.File.ReadAsync(file, 0, file.Length).ConfigureAwait(false);

                postData.Add("upfile",
                             new Internet.FileParameter(file, filename,
                                                        mappings[Path.GetExtension(filename).ToLower()]));
            }

            var request = WebRequest.Create(url) as HttpWebRequest;

            request.CookieContainer = new CookieContainer();

            string formDataBoundary = string.Format("----------{0:N}", Guid.NewGuid());

            byte[] formData = Internet.GetMultipartFormData(postData, formDataBoundary);

            request.Method      = "POST";
            request.ContentType = "multipart/form-data; boundary=" + formDataBoundary;

            request.Headers["Content-Length"] = formData.Length.ToString();
            request.Headers["User-Agent"]     = Internet.UserAgent;

            captcha.Authenticate(request, postData);

            using (Stream requeStream = await request.GetRequestStreamAsync().ConfigureAwait(false))
            {
                requeStream.Write(formData, 0, formData.Length);
            }

            var response = await request.GetResponseAsync() as HttpWebResponse;

            if (response.StatusCode == HttpStatusCode.NotFound)
            {
                throw new ThreadNotFoundException();
            }

            using (var respStream = new StreamReader(response.GetResponseStream()))
            {
                string text = respStream.ReadToEnd();

                if (text.Contains("CAPTCHA"))
                {
                    throw new CaptchaException();
                }

                if (text.Contains("banned") || text.Contains("warn"))
                {
                    throw new BannedException();
                }

                try
                {
                    Match  postIdMatch = Regex.Match(text, "no:(\\d+)");
                    string postIdStr   = postIdMatch.Groups[1].Captures[0].Value;

                    return(uint.Parse(postIdStr));
                }
                catch (ArgumentOutOfRangeException)
                {
                    throw new UnknownPostException();
                }
            }
        }
 public CaptchaDivViewComponent(ICaptcha captcha) => Captcha = captcha;
예제 #33
0
 public CaptchaDialog(ICaptcha captcha, CaptchaContent captchaContent) {
     Captcha = captcha;
     CaptchaContent = captchaContent;
     InitializeComponent();
     SetupView();
 }
예제 #34
0
        private CaptchaContent GetCaptchaContent(ICaptcha captcha) {
            var dvachCaptcha = captcha as DvachCaptcha;
            if (dvachCaptcha != null) {
                var c = dvachCaptcha;
                return string.IsNullOrWhiteSpace(c.Key)
                    ? null
                    : new CaptchaContent(CaptchaContentType.Image, ((UrlService)UrlService).GetDvachCaptchaImageUrl(c.Key));
            }

            return null;
        }
예제 #35
0
 public override Task<CaptchaContent> GetCaptchaContentAsync(ICaptcha captcha) {
     return Task.FromResult(GetCaptchaContent(captcha));
 }
 public ClusterController(ICaptcha captcha)
 {
     this.captcha = captcha;
 }
예제 #37
0
 public SmartApiController(SmartMedicalBLL bll, ICaptcha captcha)
 {
     _bll     = bll;
     _captcha = captcha;
 }