blib/lib/Lemonldap/NG/Portal/Captcha/ReCaptcha.pm untested

filter: Statementstmt 0.0% 0 / 42 Branchbran 0.0% 0 / 10 Conditioncond 0.0% 0 / 3 MC/DCmcdc 0.0% 0 / 2 Subroutinesub 0.0% 0 / 6 Podpod 0.0% 0 / 3 totaltotal 0.0% 0 / 66 CC 6 SCAR 27.4
CC
6
Cov
0%
check_captcha
30.0
init
6.0
init_captcha
2.0
CRAP 15.5
1 package Lemonldap::NG::Portal::Captcha::ReCaptcha;
2  
3 use strict;
4 use Mouse;
5 use Lemonldap::NG::Common::UserAgent;
6  
7 # Add constants used by this module
8  
9 our $VERSION = '2.23.0';
10  
11 extends 'Lemonldap::NG::Portal::Main::Plugin';
12  
13 has ua => (
14 is => 'rw',
15 lazy => 1,
16 builder => sub {
17 my $ua = Lemonldap::NG::Common::UserAgent->new( $_[0]->{conf} );
18 $ua->env_proxy();
19 return $ua;
20 }
21 );
22  
23 sub init {
24 my ($self) = @_;
25 unless ($self->conf->{captchaOptions}->{dataSiteKey}
26 and $self->conf->{captchaOptions}->{secretKey} )
27 {
28 $self->logger->error('Missing required options for reCaptcha');
29 return 0;
30 }
31 return 1;
32 }
33  
34 sub init_captcha {
35 my ( $self, $req ) = @_;
36  
37 $req->data->{customScript} .=
38 '<script src="https://www.google.com/recaptcha/enterprise.js?onload=__llng_recaptchaLoad" async defer></script>'
39 . '<script src="/static/common/js/recaptchav2.js"></script>';
40  
41 # Read option from the manager configuration
42 my $dataSiteKey = $self->conf->{captchaOptions}->{dataSiteKey};
43 my $html =
44 qq'<div class="g-recaptcha" data-sitekey="$dataSiteKey" data-action="LOGIN"></div>';
45 $req->captchaHtml($html);
46 }
47  
48 sub check_captcha {
49 my ( $self, $req ) = @_;
50  
51 my $captcha_input = $req->param('g-recaptcha-response');
52 unless ($captcha_input) {
53 $self->logger->info('No captcha value submitted');
54 return 0;
55 }
56 my $response = $self->ua->post(
57 'https://www.google.com/recaptcha/api/siteverify',
58 {
59 secret => $self->conf->{captchaOptions}->{secretKey},
60 response => $captcha_input,
61 }
62 );
63 if ( $response->is_success ) {
64 my $res = eval { JSON::from_json( $response->decoded_content ) };
65 if ($@) {
66 $self->logger->error("reCaptcha: $@");
67 return 0;
68 }
69 unless ( $res->{success} ) {
70 $self->logger->info(
71 'reCaptcha errors:' . $response->decoded_content );
72 }
73 return $res->{success};
74 }
75 $self->logger->error( 'reCaptcha error: ' . $response->status_line );
76 return 0;
77 }
78  
79 1;
80