Captchas are small images you can embedded in your webpage forms that help defeat bot-spammers from accessing and exploiting your site. They generally consist of an image of a short string of random characters visually obsfucated in some way (See
http://en.wikipedia.org/wiki/Captcha for more information).
The following plugin generates a small captcha image when the CaptchaController is invoked and stores the "key" of the image in a session variable (session.captcha).
In general, the developer would design a page to use the captcha as follows:
- In a view's form, add a text INPUT field named captcha to the form and a IMG tag pointing to the CaptchaController.
- In the form handling controller, compare the {{session.captcha}} to the {{params.captcha}}. If they match, we can assume that a human, not a bot, submitted the form.
Getting and Installing the Plugin
The plugin currently resides at
http://www.boomchucka.com/grails/grails-Captcha-0.5.zip
You can install the plugin into your grails project by doing the following:
{noformat}
%> cd your_grails_project
%> grails install-plugin http://www.boomchucka.com/grails/grails-Captcha-0.5.zip
{noformat}
Using the Plugin
First, create or modify the views that you want to implement captchas on. For example, a simple login view (like grails-app/views/user/login.gsp) might be:
{noformat}
<form action="handleLogin" method="post">
Userid: <input type="text" name="userid" /><br />
Password: <input type="password" name="password" /><br />
Enter Code: <input type="text" name="captcha">
<img src="${createLink(controller:'captcha', action:'index')}" /><br />
<input type="submit" value="Login" />
</form>
{noformat}
The IMG tag source of {{createLink(controller:'captcha', action:'index')}} does the heavy-lifting for you, generating the captcha image that is displayed to the user and setting the {{session.captcha}}. You are pairing that image with a text field named {{captcha}} so the user may input the letters he sees in the captcha image.
Next, in your controller that handles the form input, compare what the user entered to what is stored in the {{session.captcha}} value, for example:
grails-app/controllers/UserController.groovy:
{noformat}
class UserController {
def handleLogin = {
if (params.captcha.toUpperCase() == session.captcha) {
// ...continue processing…
}
else {
flash.message = "Access code did not match."
redirect(action:login)
}
}
def login = {}
}
{noformat}
Future Enhancements
In the future, the captcha image will use more visual trickery to defeat the bots. Also, I'll add support for audio captchas as well.
1 Comment
Post a Comment
Site Login