/// <summary> /// Creates a new <see cref="IBuildInfoModel" /> for update a captcha. /// </summary> /// <param name="parameterContainer"> /// The specified <see cref="IParameterContainer" />. /// </param> /// <returns> /// An instance of <see cref="IUpdateInfoModel" />. /// </returns> public IUpdateInfoModel Update(IParameterContainer parameterContainer) { Validate.ArgumentNotNull(parameterContainer, "parameterContainer"); string token; parameterContainer.TryGet(TokenParameterName, out token, null); if (string.IsNullOrEmpty(token)) { throw new KeyNotFoundException("The key is to generate not found."); } ICaptchaValue captchaValue = StorageProvider.GetValue(token, TokenType.Validation); if (captchaValue == null) { throw new ArgumentException("The key is to update incorrect."); } HttpRequestBase request; if (!parameterContainer.TryGet(RequestParameterContainer.HttpRequestParameterKey, out request) || request == null) { throw new InvalidOperationException( "The parameterContainer does not contain a HttpRequestBase with key RequestParameterContainer.HttpRequestParameterKey."); } KeyValuePair <string, ICaptchaValue> captchaPair = CreateCaptchaPair(parameterContainer, captchaValue); string newUrl = ImageUrlFactory(new UrlHelper(request.RequestContext), captchaPair); StorageProvider.Add(captchaPair); return(new DefaultUpdateInfoModel(TokenElementName, captchaPair.Key, newUrl, ImageElementName)); }
/// <summary> /// Determines whether the captcha is valid, and write error message if need. /// </summary> /// <param name="controller"> /// The specified <see cref="ControllerBase" />. /// </param> /// <param name="parameterContainer"> /// The specified <see cref="IParameterContainer" />. /// </param> /// <returns> /// <c>True</c> if the captcha is valid; otherwise, <c>false</c>. /// </returns> public virtual bool ValidateCaptcha(ControllerBase controller, IParameterContainer parameterContainer) { Validate.ArgumentNotNull(controller, "controller"); Validate.ArgumentNotNull(parameterContainer, "parameterContainer"); if (IntelligencePolicy != null) { var isValid = IntelligencePolicy.IsValid(this, controller, parameterContainer); if (isValid.HasValue) { if (isValid.Value) { return(true); } WriteError(controller, parameterContainer); return(false); } } ValueProviderResult tokenValue = controller.ValueProvider.GetValue(TokenElementName); ValueProviderResult inputText = controller.ValueProvider.GetValue(InputElementName); if (tokenValue != null && !string.IsNullOrEmpty(tokenValue.AttemptedValue) && inputText != null) { ICaptchaValue captchaValue = StorageProvider.GetValue(tokenValue.AttemptedValue, TokenType.Validation); if (captchaValue != null && !string.IsNullOrEmpty(inputText.AttemptedValue) && captchaValue.IsEqual(inputText.AttemptedValue)) { return(true); } } WriteError(controller, parameterContainer); return(false); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultCaptchaManager" /> class. /// </summary> public DefaultCaptchaManager(IStorageProvider storageProvider, string tokenParameterName, string inputElementName, string imageElementName, string tokenElementName) { Validate.ArgumentNotNull(storageProvider, "storageProvider"); Validate.ArgumentNotNullOrEmpty(tokenParameterName, "tokenParameterName"); Validate.ArgumentNotNullOrEmpty(inputElementName, "inputElementName"); Validate.ArgumentNotNullOrEmpty(imageElementName, "imageElementName"); Validate.ArgumentNotNullOrEmpty(tokenElementName, "tokenElementName"); IntelligencePolicy = new FakeInputIntelligencePolicy(); StorageProvider = storageProvider; TokenParameterName = tokenParameterName; InputElementName = inputElementName; ImageElementName = imageElementName; TokenElementName = tokenElementName; ImageUrlFactory = GenerateImageUrl; RefreshUrlFactory = GenerateRefreshUrl; MathCaptchaPairFactory = GenerateMathCaptcha; PlainCaptchaPairFactory = GenerateSimpleCaptcha; DrawingModelFactory = CreateDrawingModel; CharactersFactory = GetCharacters; AddAreaRouteValue = 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); } 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)); }
/// <summary> /// Initializes a new instance of the <see cref="T:System.Object" /> class. /// </summary> public RefreshButton(string markup, string script) { Validate.ArgumentNotNull(markup, "markup"); Validate.ArgumentNotNull(script, "script"); Markup = markup; Script = script; }
/// <summary> /// Initializes a new instance of the <see cref="CombinedParameterContainer" /> class. /// </summary> public CombinedParameterContainer(IParameterContainer firstContainer, IParameterContainer secondContainer) { Validate.ArgumentNotNull(firstContainer, "firstContainer"); Validate.ArgumentNotNull(secondContainer, "secondContainer"); _firstContainer = firstContainer; _secondContainer = secondContainer; ParameterProvider = new object[] { _firstContainer, _secondContainer }; }
/// <summary> /// Initializes a new instance of the <see cref="CookieStorageProvider" /> class. /// </summary> /// <param name="expiresMinutes">The specified expires of the cookie in minutes.</param> /// <param name="cookieName">The specified cookie name.</param> /// <param name="password">The specified password to encrypt cookie</param> /// <param name="salt">The specified salt to encrypt cookie</param> public CookieStorageProvider(int expiresMinutes, string cookieName, string password, byte[] salt) { Validate.ArgumentNotNullOrEmpty(cookieName, "cookieName"); Validate.ArgumentNotNullOrEmpty(password, "password"); Validate.ArgumentNotNull(salt, "salt"); ExpiresMinutes = expiresMinutes; _salt = salt; _password = password; CookieName = cookieName; }
/// <summary> /// Creates a captcha image for specified <see cref="IDrawingModel" /> and write it in response. /// </summary> /// <param name="response"> /// The specified <see cref="HttpResponseBase" />. /// </param> /// <param name="drawingModel"> /// The specified <see cref="IDrawingModel" />. /// </param> public virtual void WriteCaptchaImage(HttpResponseBase response, IDrawingModel drawingModel) { Validate.ArgumentNotNull(response, "response"); Validate.ArgumentNotNull(drawingModel, "drawingModel"); using (Bitmap bitmap = CaptchaUtils.ImageGeneratorFactory(drawingModel).Generate(drawingModel)) { response.ContentType = "image/gif"; bitmap.Save(response.OutputStream, ImageFormat.Gif); } }
/// <summary> /// Adds the specified token and <see cref="ICaptchaValue" /> to the storage. /// </summary> /// <param name="captchaPair"> /// The specified <see cref="KeyValuePair{TKey,TValue}" /> /// </param> public virtual void Add(KeyValuePair <string, ICaptchaValue> captchaPair) { Validate.ArgumentNotNull(captchaPair.Value, "captchaPair"); DrawingKeys.ClearIfNeed(MaxCount); ValidateKeys.ClearIfNeed(MaxCount); var entry = new KeyTimeEntry <string>(captchaPair.Key); DrawingKeys.Add(entry, captchaPair.Value); ValidateKeys.Add(entry, captchaPair.Value); }
/// <summary> /// Generates a java-script to update the captcha. /// </summary> /// <param name="updateInfo"> /// The specified <see cref="IUpdateInfoModel" />. /// </param> /// <returns> /// An instance of <see cref="ActionResult" /> to update the captcha. /// </returns> public virtual ActionResult RefreshCaptcha(IUpdateInfoModel updateInfo) { Validate.ArgumentNotNull(updateInfo, "updateInfo"); string script = string.Format(@"$('#{0}').attr(""value"", ""{1}""); $('#{2}').attr(""src"", ""{3}"");", updateInfo.TokenElementId, updateInfo.TokenValue, updateInfo.ImageElementId, updateInfo.ImageUrl); return(new JavaScriptResult { Script = script }); }
/// <summary> /// Creates a <see cref="IUpdateInfoModel" /> for create a new captcha. /// </summary> /// <param name="controller"> /// The specified <see cref="ControllerBase" />. /// </param> /// <param name="parameterContainer"> /// The specified <see cref="IParameterContainer" />. /// </param> /// <returns> /// An instance of <see cref="IUpdateInfoModel" />. /// </returns> public virtual IUpdateInfoModel GenerateNew(ControllerBase controller, IParameterContainer parameterContainer) { Validate.ArgumentNotNull(controller, "controller"); Validate.ArgumentNotNull(parameterContainer, "parameterContainer"); KeyValuePair <string, ICaptchaValue> captchaPair = CreateCaptchaPair(parameterContainer, null); StorageProvider.Add(captchaPair); var urlHelper = new UrlHelper(controller.ControllerContext.RequestContext); string imgUrl = ImageUrlFactory(urlHelper, captchaPair); return(new DefaultUpdateInfoModel(TokenElementName, captchaPair.Key, imgUrl, ImageElementName)); }
/// <summary> /// Creates a <see cref="IBuildInfoModel" /> for create a new captcha. /// </summary> /// <param name="htmlHelper"> /// The specified <see cref="HtmlHelper" />. /// </param> /// <param name="parameterContainer"> /// The specified <see cref="IParameterContainer" />. /// </param> /// <returns> /// An instance of <see cref="IBuildInfoModel" />. /// </returns> public virtual IBuildInfoModel GenerateNew(HtmlHelper htmlHelper, IParameterContainer parameterContainer) { Validate.ArgumentNotNull(htmlHelper, "htmlHelper"); Validate.ArgumentNotNull(parameterContainer, "parameterContainer"); KeyValuePair <string, ICaptchaValue> captchaPair = CreateCaptchaPair(parameterContainer, null); StorageProvider.Add(captchaPair); var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext); string imgUrl = ImageUrlFactory(urlHelper, captchaPair); string refreshUrl = RefreshUrlFactory(urlHelper, captchaPair); return(CreateBuildInfo(htmlHelper, parameterContainer, captchaPair, imgUrl, refreshUrl)); }
/// <summary> /// Initializes a new instance of the <see cref="MultiIntelligencePolicy" /> class. /// </summary> public MultiIntelligencePolicy(params IIntelligencePolicy[] policies) { Validate.ArgumentNotNull(policies, "policies"); if (policies.Length == 0) { throw new ArgumentException("Argument cannot be empty.", "policies"); } if (policies.Any(policy => policy.GetType() == typeof(MultiIntelligencePolicy))) { throw new ArgumentException("The argument can be of MultiIntelligencePolicy type.", "policies"); } Policies = policies; }
/// <summary> /// Creates a new <see cref="IDrawingModel" /> for drawing a captcha. /// </summary> /// <param name="parameterContainer"> /// The specified <see cref="IParameterContainer" />. /// </param> /// <returns> /// An instance of <see cref="IDrawingModel" />. /// </returns> public virtual IDrawingModel GetDrawingModel(IParameterContainer parameterContainer) { Validate.ArgumentNotNull(parameterContainer, "parameterContainer"); string token; if (!parameterContainer.TryGet(TokenParameterName, out token) || string.IsNullOrEmpty(token)) { throw new KeyNotFoundException("The key is to generate not found."); } ICaptchaValue captchaValue = StorageProvider.GetValue(token, TokenType.Drawing); if (captchaValue == null) { throw new ArgumentException("The key is to generate incorrect."); } return(DrawingModelFactory(parameterContainer, captchaValue)); }
/// <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)); }
/// <summary> /// Determines whether the intelligent captcha is valid. /// </summary> /// <param name="captchaManager">The specified captcha manager.</param> /// <param name="controller"> /// The specified <see cref="ControllerBase" />. /// </param> /// <param name="parameterContainer"> /// The specified <see cref="IParameterContainer" />. /// </param> /// <returns> /// <c>True</c> if the intelligent captcha is valid; <c>false</c> not valid; <c>null</c> is not intelligent captcha. /// </returns> public virtual bool?IsValid(ICaptchaManager captchaManager, ControllerBase controller, IParameterContainer parameterContainer) { Validate.ArgumentNotNull(captchaManager, "captchaManager"); Validate.ArgumentNotNull(controller, "controller"); ValueProviderResult tokenValue = controller .ValueProvider .GetValue(captchaManager.TokenElementName + PolicyType); if (tokenValue == null || string.IsNullOrEmpty(tokenValue.AttemptedValue)) { return(null); } DateTime?dateTime = GetTokenValue(controller, tokenValue.AttemptedValue); if (dateTime == null) { return(null); } return(captchaManager.StorageProvider.Remove(tokenValue.AttemptedValue) && DateTime.UtcNow - dateTime.Value > MinResponseTime); }
/// <summary> /// Determines whether the intelligent captcha is valid. /// </summary> /// <param name="captchaManager">The specified captcha manager.</param> /// <param name="controller"> /// The specified <see cref="ControllerBase" />. /// </param> /// <param name="parameterContainer"> /// The specified <see cref="IParameterContainer" />. /// </param> /// <returns> /// <c>True</c> if the intelligent captcha is valid; <c>false</c> not valid; <c>null</c> is not intelligent captcha. /// </returns> public virtual bool?IsValid(ICaptchaManager captchaManager, ControllerBase controller, IParameterContainer parameterContainer) { Validate.ArgumentNotNull(captchaManager, "captchaManager"); Validate.ArgumentNotNull(controller, "controller"); ValueProviderResult tokenValue = controller .ValueProvider .GetValue(captchaManager.TokenElementName + PolicyType); if (tokenValue == null || string.IsNullOrEmpty(tokenValue.AttemptedValue)) { return(null); } if (!RemoveTokenValue(controller, tokenValue.AttemptedValue)) { return(null); } ValueProviderResult validationVal = controller.ValueProvider.GetValue(ValidationInputName); return(captchaManager.StorageProvider.Remove(tokenValue.AttemptedValue) && validationVal != null && Reverse(validationVal.AttemptedValue) == tokenValue.AttemptedValue); }
/// <summary> /// Serializes the <see cref="ICaptchaValue" />, to the given string. /// </summary> /// <param name="captchaValue"> /// The specified <see cref="ICaptchaValue" />. /// </param> /// <returns>The result string.</returns> protected virtual string Serialize(ICaptchaValue captchaValue) { Validate.ArgumentNotNull(captchaValue, "captchaValue"); using (var pdb = new Rfc2898DeriveBytes(Password, Salt)) { string value = captchaValue.GetType().FullName + Separator + captchaValue.Serialize(); byte[] bytes = Encoding.Unicode.GetBytes(value); using (var ms = new MemoryStream()) { Rijndael alg = Rijndael.Create(); alg.Key = pdb.GetBytes(32); alg.IV = pdb.GetBytes(16); using (var cs = new CryptoStream(ms, alg.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(bytes, 0, bytes.Length); } return(Convert.ToBase64String(ms.ToArray())); } } }
/// <summary> /// Determines whether the intelligent captcha is valid. /// </summary> /// <param name="captchaManager">The specified captcha manager.</param> /// <param name="controller"> /// The specified <see cref="ControllerBase" />. /// </param> /// <param name="parameterContainer"> /// The specified <see cref="IParameterContainer" />. /// </param> /// <returns> /// <c>True</c> if the intelligent captcha is valid; <c>false</c> not valid; <c>null</c> is not intelligent captcha. /// </returns> public virtual bool?IsValid(ICaptchaManager captchaManager, ControllerBase controller, IParameterContainer parameterContainer) { Validate.ArgumentNotNull(captchaManager, "captchaManager"); Validate.ArgumentNotNull(controller, "controller"); ValueProviderResult tokenValue = controller .ValueProvider .GetValue(captchaManager.TokenElementName + PolicyType); if (tokenValue == null || string.IsNullOrEmpty(tokenValue.AttemptedValue)) { return(null); } var captchaValue = captchaManager.StorageProvider.GetValue(tokenValue.AttemptedValue, TokenType.Drawing); if (captchaValue == null) { return(null); } foreach (IIntelligencePolicy intelligencePolicy in Policies) { bool?valid = intelligencePolicy.IsValid(captchaManager, controller, parameterContainer); if (valid == null) { return(null); } if (!valid.Value) { return(false); } captchaManager.StorageProvider.Remove(tokenValue.AttemptedValue); captchaManager.StorageProvider.Add(new KeyValuePair <string, ICaptchaValue>(tokenValue.AttemptedValue, captchaValue)); } captchaManager.StorageProvider.Remove(tokenValue.AttemptedValue); return(true); }
/// <summary> /// Adds the specified token and <see cref="ICaptchaValue" /> to the storage. /// </summary> /// <param name="captchaPair"> /// The specified <see cref="KeyValuePair{TKey,TValue}" /> /// </param> public virtual void Add(KeyValuePair <string, ICaptchaValue> captchaPair) { Validate.ArgumentNotNull(captchaPair, "captchaPair"); Validate.ArgumentNotNull(captchaPair.Value, "captchaPair"); string drawingKey = CookieName + DrawingKey; HttpCookie httpCookieDrawing = HttpContext.Current.Request.Cookies[drawingKey] ?? new HttpCookie(drawingKey); HttpCookie httpCookie = HttpContext.Current.Request.Cookies[CookieName] ?? new HttpCookie(CookieName); httpCookie.Expires = httpCookieDrawing.Expires = DateTime.Now.AddMinutes(ExpiresMinutes); httpCookie.HttpOnly = httpCookieDrawing.HttpOnly = true; string serialize = Serialize(captchaPair.Value); ClearCookieIfNeed(httpCookie); ClearCookieIfNeed(httpCookieDrawing); httpCookie.Values.Add(captchaPair.Key, serialize); httpCookieDrawing.Values.Add(captchaPair.Key, serialize); HttpContext.Current.Response.Cookies.Add(httpCookie); HttpContext.Current.Response.Cookies.Add(httpCookieDrawing); }
/// <summary> /// Creates a new captcha to the specified <see cref="IBuildInfoModel" />. /// </summary> /// <param name="buildInfoModel"> /// The specified <see cref="IBuildInfoModel" />. /// </param> /// <returns>The html string with the captcha.</returns> public virtual ICaptcha GenerateCaptcha(IBuildInfoModel buildInfoModel) { Validate.ArgumentNotNull(buildInfoModel, "buildInfoModel"); return(CaptchaBuilderFactory(buildInfoModel).Build(buildInfoModel)); }
/// <summary> /// Initializes a new instance of the <see cref="RequestParameterContainer"/> class. /// </summary> public RequestParameterContainer(HttpRequestBase requestBase) { Validate.ArgumentNotNull(requestBase, "requestBase"); _requestBase = requestBase; }
/// <summary> /// Creates a captcha error image and write it in response. /// </summary> /// <param name="response"> /// The specified <see cref="HttpResponse" />. /// </param> public virtual void WriteErrorImage(HttpResponseBase response) { Validate.ArgumentNotNull(response, "response"); response.ContentType = "image/gif"; response.OutputStream.Write(ErrorBytes, 0, ErrorBytes.Length); }