Pages

Thursday, January 29, 2015

Grails CAPTCHA

Easiest CAPTHCA implementation ever! Check here http://grails.org/plugin/simple-captcha

In BuildConfig.groovy insert this line:

compile ":simple-captcha:1.0.0"

In gsp page copy this code block:

<img src="${createLink(controller: 'simpleCaptcha', action: 'captcha')}"/><br/>
<input type="text" name="captcha"><br/>

<input type="submit" value="Register">

There will appear an image with capthca and the entered value will be passed as params.captcha.

In the controller that your <g:form> refers to put this code:

Outside of any action:

def simpleCaptchaService

In the controller:

boolean captchaValid = simpleCaptchaService.validateCaptcha(params.captcha)

if (captchaValid) {
   def user = new User(userName:params.userName)
   user.save()
   ...
} else {
   flash.message = "Wrong capthca"
   redirect(controller:"user", action:"login")

}

Now you will have a working captcha.

There also is a configuration closure that you can put into the Config.groovy

simpleCaptcha {
// font size used in CAPTCHA images
fontSize = 30
height = 200
width = 200
// number of characters in CAPTCHA text
length = 6

// amount of space between the bottom of the CAPTCHA text and the bottom of the CAPTCHA image
bottomPadding = 16

// distance between the diagonal lines used to obfuscate the text
lineSpacing = 10

// the charcters shown in the CAPTCHA text must be one of the following
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

// this param will be passed as the first argument to this java.awt.Font constructor
// http://docs.oracle.com/javase/6/docs/api/java/awt/Font.html#Font(java.lang.String,%20int,%20int)
font = "Serif"

}

Beginning Grails, Groovy and Griffon, error #1

Just found an error in the book. When you create a filter, the author suggests you to copy this code block to your app:

if (session?.user?.id != params?.id) {
flash.message = "You can only modify yourself!"
redirect(controller:"user", action: "index")
return false

}

But actually the params.id is a String and the session.user.id is a Long type, so this condition turns out to be executed every time, even when both values are 2, for example.

The working code would be like this:

if (session?.user?.id?.toInteger() != params?.id?.toInteger()) {
flash.message = "You can only modify yourself!"
redirect(controller:"user"action"index")
return false

}