Skip to content

Instantly share code, notes, and snippets.

@coderberry
Created October 17, 2011 00:45
Show Gist options
  • Select an option

  • Save coderberry/1291660 to your computer and use it in GitHub Desktop.

Select an option

Save coderberry/1291660 to your computer and use it in GitHub Desktop.
CaptchaConverter.groovy
package com.berry
import com.berry.BCrypt
import grails.converters.JSON
class CaptchaController {
def index = {
// Generate the SALT to be used for encryption and place in session
def captchaSalt = session.captchaSalt ?: BCrypt.gensalt()
session.selectedCaptchaText = null
session.captchaSalt = captchaSalt
// Modify below for custom images
def images = [
'house': 'images/captchaImages/01.png',
'key': 'images/captchaImages/04.png',
'flag': 'images/captchaImages/06.png',
'clock': 'images/captchaImages/15.png',
'bug': 'images/captchaImages/16.png',
'pen': 'images/captchaImages/19.png',
'light bulb': 'images/captchaImages/21.png',
'musical note': 'images/captchaImages/40.png',
'heart': 'images/captchaImages/43.png',
'world': 'images/captchaImages/99.png'
]
// Create the image array to be returned in JSON format
def size = images.size()
def num = Math.min(params.numImages ? params.int('numImages') : 5, size)
def keys = images.keySet().toList()
def used = []
def random = new Random()
(1..num).each { i ->
def idx = random.nextInt(keys.size())
def item = keys.get(idx)
keys.remove(idx)
used << item
}
// Select the 'chosen' text to be used for authentication and place in session
def selectedText = used[random.nextInt(used.size())]
def hashedSelectedText = BCrypt.hashpw(selectedText, captchaSalt);
session.selectedCaptchaText = hashedSelectedText
// println "SELECTED: ${hashedSelectedText}"
// println "USED: ${used.inspect()}"
// Generate object to be returned
def ret = [
text: selectedText,
images: []
]
used.each { u ->
ret['images'] << [hash: BCrypt.hashpw(u, captchaSalt), file: images[u]]
}
render ret as JSON
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment