Generating CAPTCHAs using Dancer::Plugin::Captcha::SecurityImage
Many sites uses a CAPTCHA to prevent bots using comments for spam. If you want to add this feature to your site, you can do it using Dancer::Plugin::SecurityImage.
For a CAPTCHA test to work, you need to generate an image with slightly obsfucated text which computer OCR (Optical Character Recognition) software will not be able to read, and store the text contained in the image in the user's session. Once they submit the form, you compare the text they entered with the text stored in the session, and you know if they entered the right text or not.
Dancer::Plugin::Captcha::SecurityImage makes this easy.
Description of common functions
create_captcha
This function expects argument which will be passed to the GD::SecurityImage constructor and methods.
validate_captcha
This function expects the value user entered in the form. It will check it
against the code stored in the Dancer session and return true
if they match.
clear_captcha
This function will remove the CAPTCHA value from your session data so that it won't match again.
Simple example
use Dancer; use Dancer::Plugin::Captcha::SecurityImage; session 'simple'; get '/captcha' => sub { create_captcha { new => { width => 80, height => 30, lines => 10, gd_font => 'giant', }, create => [ normal => 'rect' ], particle => [ 100 ], out => { force => 'jpeg' }, #format of picture ('jpeg', 'png') random => $random_string = rand_pass(6), #random string for CAPTCHA }; }; post '/verify' => sub { #captcha validation my $p = request->params; if (!validate_captcha $p->{captcha}) { return "wrong code"; } clear_captcha; }; sub rand_pass { my $len = shift; my $pass; for (1..$len) {$pass .= chr(rand(94)+33)} return $pass; }
AUTHOR
This article was written by Andrew Inishev, Google Code-in student, mentored by David Precious.