Line # Revision Author
1 3 ahitrov@rambler.ru package Contenido::Captcha;
2
3 use strict;
4 use warnings 'all';
5
6 use Authen::Captcha;
7 use Digest::MD5 qw(md5_hex);
8
9
10 sub new {
11 my ($class, $keeper, %captcha_args) = @_;
12
13 my $self = {
14 captcha => Authen::Captcha->new(%captcha_args),
15 memd => $keeper->MEMD,
16 };
17 bless $self, $class;
18 }
19
20 sub create_code {
21 my ($self, %opts) = @_;
22
23 my $code = $$self{captcha}->generate_random_string($opts{length}||4);
24 my $md5 = md5_hex($code.int 10**10*rand);
25
26 $$self{memd}->set("captcha:".$md5, $code, $opts{expire}||600);
27
28 $md5;
29 }
30
31 sub create_image {
32 my ($self, $md5) = @_;
33
34 my $code = $$self{memd}->get("captcha:".$md5||'');
35 return unless $code;
36
37 $$self{captcha}->create_image_file($code);
38 }
39
40 sub check_code {
41 my ($self, $md5, $code) = @_;
42
43 return 0 unless $code;
44
45 my $real = $$self{memd}->get("captcha:".$md5||'');
46 return 0 unless $real && $real eq $code;
47
48 $$self{memd}->delete("captcha:".$md5||'');
49
50 1;
51 }
52
53 sub width {
54 my $self = shift;
55 $$self{captcha}->width;
56 }
57
58 sub height {
59 my $self = shift;
60 $$self{captcha}->height;
61 }
62
63 1;