PageRenderTime 28ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/recaptcha-plugins/dotnet/library/RecaptchaValidator.cs

http://recaptcha.googlecode.com/
C# | 168 lines | 121 code | 24 blank | 23 comment | 13 complexity | d7a63f097098584a7803b4a4711ce5c2 MD5 | raw file
  1. // Copyright (c) 2007 Adrian Godong, Ben Maurer
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. using System;
  21. using System.Diagnostics;
  22. using System.IO;
  23. using System.Net;
  24. using System.Net.Sockets;
  25. using System.Text;
  26. using System.Web;
  27. namespace Recaptcha
  28. {
  29. /// <summary>
  30. /// Calls the reCAPTCHA server to validate the answer to a reCAPTCHA challenge. Normally,
  31. /// you will use the RecaptchaControl class to insert a web control on your page. However
  32. /// </summary>
  33. public class RecaptchaValidator
  34. {
  35. private const string VerifyUrl = "http://www.google.com/recaptcha/api/verify";
  36. private string privateKey;
  37. private string remoteIp;
  38. private string challenge;
  39. private string response;
  40. private IWebProxy proxy;
  41. public string PrivateKey
  42. {
  43. get { return this.privateKey; }
  44. set { this.privateKey = value; }
  45. }
  46. public string RemoteIP
  47. {
  48. get
  49. {
  50. return this.remoteIp;
  51. }
  52. set
  53. {
  54. IPAddress ip = IPAddress.Parse(value);
  55. if (ip == null ||
  56. (ip.AddressFamily != AddressFamily.InterNetwork &&
  57. ip.AddressFamily != AddressFamily.InterNetworkV6))
  58. {
  59. throw new ArgumentException("Expecting an IP address, got " + ip);
  60. }
  61. this.remoteIp = ip.ToString();
  62. }
  63. }
  64. public string Challenge
  65. {
  66. get { return this.challenge; }
  67. set { this.challenge = value; }
  68. }
  69. public string Response
  70. {
  71. get { return this.response; }
  72. set { this.response = value; }
  73. }
  74. public IWebProxy Proxy
  75. {
  76. get { return this.proxy; }
  77. set { this.proxy = value; }
  78. }
  79. private void CheckNotNull(object obj, string name)
  80. {
  81. if (obj == null)
  82. {
  83. throw new ArgumentNullException(name);
  84. }
  85. }
  86. public RecaptchaResponse Validate()
  87. {
  88. this.CheckNotNull(this.PrivateKey, "PrivateKey");
  89. this.CheckNotNull(this.RemoteIP, "RemoteIp");
  90. this.CheckNotNull(this.Challenge, "Challenge");
  91. this.CheckNotNull(this.Response, "Response");
  92. if (this.challenge == string.Empty || this.response == string.Empty)
  93. {
  94. return RecaptchaResponse.InvalidSolution;
  95. }
  96. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(VerifyUrl);
  97. request.ProtocolVersion = HttpVersion.Version10;
  98. request.Timeout = 30 * 1000 /* 30 seconds */;
  99. request.Method = "POST";
  100. request.UserAgent = "reCAPTCHA/ASP.NET";
  101. if (this.proxy != null)
  102. {
  103. request.Proxy = this.proxy;
  104. }
  105. request.ContentType = "application/x-www-form-urlencoded";
  106. string formdata = String.Format(
  107. "privatekey={0}&remoteip={1}&challenge={2}&response={3}",
  108. HttpUtility.UrlEncode(this.PrivateKey),
  109. HttpUtility.UrlEncode(this.RemoteIP),
  110. HttpUtility.UrlEncode(this.Challenge),
  111. HttpUtility.UrlEncode(this.Response));
  112. byte[] formbytes = Encoding.ASCII.GetBytes(formdata);
  113. using (Stream requestStream = request.GetRequestStream())
  114. {
  115. requestStream.Write(formbytes, 0, formbytes.Length);
  116. }
  117. string[] results;
  118. try
  119. {
  120. using (WebResponse httpResponse = request.GetResponse())
  121. {
  122. using (TextReader readStream = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
  123. {
  124. results = readStream.ReadToEnd().Split(new string[] { "\n", "\\n" }, StringSplitOptions.RemoveEmptyEntries);
  125. }
  126. }
  127. }
  128. catch (WebException ex)
  129. {
  130. EventLog.WriteEntry("Application", ex.Message, EventLogEntryType.Error);
  131. return RecaptchaResponse.RecaptchaNotReachable;
  132. }
  133. switch (results[0])
  134. {
  135. case "true":
  136. return RecaptchaResponse.Valid;
  137. case "false":
  138. return new RecaptchaResponse(false, results[1].Trim(new char[] { '\'' }));
  139. default:
  140. throw new InvalidProgramException("Unknown status response.");
  141. }
  142. }
  143. }
  144. }