Skip to content

Instantly share code, notes, and snippets.

@btrott
Created April 29, 2010 03:52
Show Gist options
  • Save btrott/383106 to your computer and use it in GitHub Desktop.
Save btrott/383106 to your computer and use it in GitHub Desktop.
Demo of Captcha::reCAPTCHA using Plack
#!/usr/bin/perl
# Simple demonstration of Captcha::reCAPTCHA,
# using Plack and other simple & modern tools
# (port of examples/captcha.pl to Plack)
use strict;
use warnings;
use Captcha::reCAPTCHA;
use Data::Section::Simple qw( get_data_section );
use Plack::Request;
use Text::MicroTemplate qw( build_mt encoded_string );
# Your reCAPTCHA keys from
# https://admin.recaptcha.net/recaptcha/createsite/
use constant PUBLIC_KEY => '<public key here>';
use constant PRIVATE_KEY => '<private key here>';
my $renderer = build_mt( get_data_section( 'form.html' ) );
sub {
my $req = Plack::Request->new( shift );
my $c = Captcha::reCAPTCHA->new;
my $p = $req->parameters;
my( $is_valid, $err );
if ( $p->{recaptcha_response_field} ) {
my $res = $c->check_answer(
PRIVATE_KEY, $req->address,
$p->{recaptcha_challenge_field},
$p->{recaptcha_response_field},
);
if ( $res->{is_valid} ) {
$is_valid = 1;
} else {
$err = $res->{error};
}
}
my $form = $c->get_html( PUBLIC_KEY, $err );
my $html = $renderer->( $is_valid, $form );
my $res = $req->new_response( 200 );
$res->content_type( 'text/html' );
$res->body( $html );
return $res->finalize;
}
__DATA__
@@ form.html
? my( $is_valid, $form ) = @_;
<html>
<body>
<form action="" method="post">
? if ( $is_valid ) {
Yes!
? }
<?= encoded_string $form ?>
<br/>
<input type="submit" value="submit" />
</form>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment