We’ve all encoutered reCAPTCHA, as it’s one of the few effective ways to protect form submissions from bots on the internet.
Acquired by google in 2009, it comes with multiple plugins for various web environment, here is a plugin for DWScript.
The plugin (aka unit) can be found in the DWSlibs github repository, and it follows the naming conventions of the other reCAPTACH plugins, ie.
- ReCaptcha.GetHtmlCode can be used to generate the html code for a reCAPTCHA
- ReCaptcha.CheckAnswer allows to check the user answer against google’s servers
And here is a simple usage example. Obtain your reCAPTCHA API keys, save the sample code as “recap.dws” (replace with your API keys where appropriate), and open it in the browser.
Once you validate the captcha, it will display the outcome and offer a new captcha.
<html> <body> <pre><?pas uses Security.reCaptcha; if WebRequest.ContentField['recaptcha_challenge_field'] <> '' then begin PrintLn('Previous reCaptcha results:'); var r := ReCaptcha.CheckAnswer('YourPrivateKey'); PrintLn(r.IsValid); PrintLn(r.Error); end; ?></pre> <form action="recap.dws" method="post"> <?pas= ReCaptcha.GetHtmlCode('YourPublicKey') ?> </form> </body> </html>
The CheckAnswer overload used here is the short one, which assumes it is running for the POST with standard reCAPTCHA field names, so it grabs them and the remote IP automatically.
The following line from GetHtmlCode looks very odd. Is this correct?
var p := publicKey + (if error” then error+’&error=’+error);
Hmm, yes, there is an extra “error+”, which for some reason did not prevent the code from working, fixed now.