blib/lib/Experian/IDAuth.pm

filter: Statementstmt 92.3% 24 / 26 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 9 / 9 Podpod n/a totaltotal 94.2% 33 / 35 CC 1 SCAR 0.3
CC
1
Cov
92%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
↑ Summary
1 package Experian::IDAuth;
2  
3 7 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 7 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 7 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
6  
7 our $VERSION = '2.53';
8  
9 7 ▶use Locale::Country;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 7 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 7 ▶use Syntax::Keyword::Try;
Subroutine BEGIN: called CC=1 SCAR=0.0
12 7 ▶use WWW::Mechanize;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 ## no critic (DiscouragedModules)
14 7 ▶use XML::Simple;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 0 ▶use XML::Twig;
Subroutine BEGIN: called CC=1 SCAR=2.6
16 use SOAP::Lite;
17 use File::MimeInfo::Magic;
18 use IO::Socket::SSL 'SSL_VERIFY_NONE';
19 use Carp;
20 use Digest::SHA qw(hmac_sha256_base64);
21  
22 sub new {
23 my ($class, %args) = @_;
24 my $obj = bless {}, $class;
25 $obj->set($obj->defaults, %args);
26 return $obj;
27 }
28  
29 sub defaults {
30 my $self = shift;
31 return (
32 username => 'experian_user',
33 password => '?',
34 private_key => 'private_key',
35 public_key => 'public_key',
36 members_url => 'https://proveid.experian.com',
37 api_uri => 'http://corpwsdl.oneninetwo',
38 api_proxy => 'https://xml.proveid.experian.com/IDSearch.cfc',
39 header_ns_url => 'http://xml.proveid.experian.com/xsd/Headers',
40 folder => '/tmp/proveid',
41  
42 # if you're using a logger,
43 #logger => Log::Log4per::get_logger,
44 );
45 }
46  
47 sub set {
48 my ($self, %args) = @_;
49 $self->{$_} = $args{$_} for keys %args;
50 return $self;
51 }
52  
53 sub get_result {
54 my $self = shift;
55  
56 my $search_option = $self->{search_option};
57  
58 croak "invalid search_option $search_option" if $search_option !~ /(?:ProveID_KYC|CheckID)/;
59  
60 $self->_do_192_authentication;
61  
62 return $self->_get_result_proveid if $search_option eq 'ProveID_KYC';
63  
64 return $self->_get_result_checkid;
65 }
66  
67 sub save_pdf_result {
68 my $self = shift;
69  
70 # Parse and convert the result to hash
71 my $result = $self->_xml_as_hash or croak 'no xml result in place';
72  
73 # 192 reference which we should pass to 192 to download the result
74 my $our_ref = $result->{OurReference} or croak "No 'OurReference'; invalid save-pdf request";
75  
76 my $url = $self->{members_url};
77 my $mech = WWW::Mechanize->new();
78 $mech->ssl_opts(
79 verify_hostname => 0,
80 SSL_verify_mode => SSL_VERIFY_NONE,
81 SSL_key_file => "/etc/rmg/ssl/key/experian.key",
82 SSL_cert_file => "/etc/rmg/ssl/crt/experian.crt"
83 );
84  
85 try {
86  
87 # Get the login page
88 $mech->get("$url/signin/");
89  
90 # Login to the members environments
91 $mech->submit_form(
92 with_fields => {
93 login => $self->{username},
94 password => $self->{password},
95 });
96  
97 # Download pdf result on given reference number
98 $mech->get("$url/archive/index.cfm?event=archive.pdf&id=$our_ref");
99 } catch ($e) {
100 croak "errors downloading pdf: $e";
101 }
102  
103 # Save the result to our pdf path
104 my $folder_pdf = "$self->{folder}/pdf";
105  
106 # make directory if necessary
107 if (not -d $folder_pdf) {
108 Path::Tiny::path($folder_pdf)->mkpath;
109 }
110 my $file_pdf = $self->_pdf_report_filename;
111 $mech->save_content($file_pdf);
112  
113 # Check if the downloaded file is a pdf.
114 unless ($self->has_downloaded_pdf) {
115 unlink $file_pdf;
116 croak "discarding downloaded file $file_pdf, not a pdf!";
117 }
118  
119 return 1;
120 }
121  
122 sub has_downloaded_pdf {
123 my $self = shift;
124 my $file_pdf = $self->_pdf_report_filename;
125 return 0 unless -e $file_pdf;
126 open my $fh, '<', $file_pdf or croak "Could not open $file_pdf: $!";
127 my $mime_type = mimetype($fh);
128 close $fh;
129 return $mime_type =~ /PDF/i;
130 }
131  
132 sub has_done_request {
133 my $self = shift;
134 return -f $self->_xml_report_filename;
135 }
136  
137 sub get_192_xml_report {
138 my $self = shift;
139 return Path::Tiny::path($self->_xml_report_filename)->slurp;
140 }
141  
142 sub valid_country {
143 my $self = shift;
144 my $country = shift;
145 for (
146  
147 # To make CheckID work well for non-UK countries we need to pass
148 # in drivers license, Passport MRZ, national ID number
149 #qw( ad at au be ca ch cz dk es fi fr gb gg hu ie im it je lu nl no pt se sk us )
150 qw ( gb im )
151 )
152 {
153 return 1 if $country eq $_;
154 }
155 return 0;
156 }
157  
158 sub _build_request {
159 my $self = shift;
160  
161 $self->{request_as_xml} =
162 '<xml><![CDATA[<Search>'
163 . $self->_build_authentication_tag
164 . $self->_build_country_code_tag
165 . $self->_build_person_tag
166 . $self->_build_addresses_tag
167 . $self->_build_telephones_tag
168 . $self->_build_search_reference_tag
169 . $self->_build_search_option_tag
170 . '</Search>]]></xml>';
171  
172 return 1;
173 }
174  
175 # This is built based Section 3b on the Experian User Guide
176 sub _2fa_header {
177 my $self = shift;
178  
179 my $loginid = $self->{username};
180 my $password = $self->{password};
181 my $private_key = $self->{private_key};
182 my $public_key = $self->{public_key};
183  
184 my $timestamp = time();
185  
186 my $hash = hmac_sha256_base64($loginid, $password, $timestamp, $private_key);
187  
188 # Digest::SHA doesn't pad it's outputs so we have to do it manually.
189 while (length($hash) % 4) {
190 $hash .= '=';
191 }
192  
193 my $hmac_sig = $hash . '_' . $timestamp . '_' . $public_key;
194  
195 return SOAP::Header->name('head:Signature')->value($hmac_sig);
196 }
197  
198 # Send the given SOAP request to 192.com
199 sub _send_request {
200 my $self = shift;
201  
202 my $request = $self->{request_as_xml} // croak 'needs request';
203  
204 # Hide password
205 (my $request1 = $request) =~ s/\<Password\>.+\<\/Password\>/\<Password\>XXXXXXX<\/Password\>/;
206  
207 # Create soap object
208 my $soap = SOAP::Lite->readable(1)->uri($self->{api_uri})->proxy($self->{api_proxy})->ns($self->{header_ns_url}, 'head');
209  
210 $soap->transport->ssl_opts(
211 verify_hostname => 0,
212 SSL_verify_mode => SSL_VERIFY_NONE
213 );
214 $soap->transport->timeout(60);
215  
216 # Do it
217 my $som = $soap->search(SOAP::Data->type('xml' => $request), $self->_2fa_header());
218 croak "ERRTEXT: " . $som->fault->faultstring if $som->fault;
219  
220 my $result = $som->result;
221 $self->{result_as_xml} = $result;
222  
223 return 1;
224 }
225  
226 sub _build_authentication_tag {
227 my $self = shift;
228 return "<Authentication><Username>$self->{username}</Username><Password>$self->{password}</Password></Authentication>";
229 }
230  
231 sub _build_country_code_tag {
232 my $self = shift;
233 my $two_digit_country = $self->{residence};
234 my $three_digit_country = uc Locale::Country::country_code2code($two_digit_country, LOCALE_CODE_ALPHA_2, LOCALE_CODE_ALPHA_3);
235  
236 croak "Client " . $self->{client_id} . " could not get country from residence [$two_digit_country]" unless $three_digit_country;
237  
238 return "<CountryCode>$three_digit_country</CountryCode>";
239 }
240  
241 sub _build_person_tag {
242 my $self = shift;
243  
244 my $dob = $self->{date_of_birth} or croak "No date of birth for " . $self->{client_id};
245  
246 if ($dob =~ /^(\d\d\d\d)/) {
247 my $birth_year = $1;
248  
249 # Check client not older than 100 or less than 18 years old
250 my (undef, undef, undef, undef, undef, $curyear) = gmtime(time);
251 $curyear += 1900;
252 my $maxyear = $curyear - 17;
253 my $minyear = $curyear - 100;
254  
255 if ($birth_year > $maxyear or $birth_year < $minyear) {
256 return undef;
257 }
258 } else {
259 croak "Invalid date of birth [$dob] for " . $self->{client_id};
260 }
261  
262 return
263 '<Person>'
264 . '<Name><Forename>'
265 . $self->{first_name}
266 . '</Forename>'
267 . '<Surname>'
268 . $self->{last_name}
269 . '</Surname></Name>'
270 . "<DateOfBirth>$dob</DateOfBirth>"
271 . '</Person>';
272  
273 }
274  
275 sub _build_addresses_tag {
276 my $self = shift;
277  
278 my $postcode = $self->{postcode};
279 my $premise = $self->{premise} // croak 'needs premise';
280 my $country_code = $self->_build_country_code_tag;
281  
282 return qq(<Addresses><Address Current="1"><Premise>$premise</Premise>) . qq(<Postcode>$postcode</Postcode>$country_code</Address></Addresses>);
283 }
284  
285 sub _build_telephones_tag {
286 my $self = shift;
287  
288 my $telephone_type = 'U';
289 my $number;
290 if ($self->{phone} =~ /^([\+\d\s]+)/) {
291 $number = $1;
292 }
293  
294 return '<Telephones>' . qq(<Telephone Type="$telephone_type">) . "<Number>$number</Number>" . "</Telephone>" . '</Telephones>';
295 }
296  
297 sub _build_search_reference_tag {
298 my $self = shift;
299 my $shortopt = ($self->{search_option} eq 'ProveID_KYC') ? 'PK' : 'C';
300 my $time = time();
301 return "<YourReference>${shortopt}_" . $self->{client_id} . "_$time</YourReference>";
302 }
303  
304 sub _build_search_option_tag {
305 my $self = shift;
306 return "<SearchOptions><ProductCode>$self->{search_option}</ProductCode></SearchOptions>";
307 }
308  
309 sub _xml_as_hash {
310 my $self = shift;
311 my $xml = $self->{result_as_xml} or return undef;
312 return XML::Simple::XMLin(
313 $xml,
314 KeyAttr => {DocumentID => 'type'},
315 ForceArray => ['DocumentID'],
316 ContentKey => '-content',
317 );
318 }
319  
320 sub _get_result_proveid {
321 my $self = shift;
322  
323 my $report = $self->{result_as_xml} or croak 'needs xml report';
324  
325 my $twig;
326 try {
327 $twig = XML::Twig->parse($report);
328 } catch ($e) {
329 croak "could not parse xml report: $e"
330 }
331  
332 my ($report_summary_twig) = $twig->get_xpath('/Search/Result/Summary/ReportSummary/DatablocksSummary');
333  
334 return unless $report_summary_twig;
335  
336 my %report_summary;
337 for my $dblock ($report_summary_twig->get_xpath('DatablockSummary')) {
338 my $name = $dblock->findvalue('Name');
339 my $value = $dblock->findvalue('Decision');
340 $report_summary{$name} = $value;
341 }
342 my ($kyc_summary) = $twig->get_xpath('/Search/Result/Summary/KYCSummary');
343 my ($credit_reference) = $twig->get_xpath('/Search/Result/CreditReference/CreditReferenceSummary');
344  
345 return unless $credit_reference and $kyc_summary;
346  
347 my $decision = {
348 matches => [],
349 kyc_summary_score => 0
350 };
351  
352 # calculate kyc summary score
353  
354 if ( (my $name_count = $kyc_summary->findvalue('FullNameAndAddress/Count')) > 0
355 && (my $dob_count = $kyc_summary->findvalue('DateOfBirth/Count')) > 0)
356 {
357 $decision->{kyc_summary_score} = $name_count + $dob_count;
358 }
359  
360 # check if client has died or fraud
361 my $cr_deceased = $credit_reference->findvalue('DeceasedMatch') || 0;
362 $report_summary{Deceased} ||= 0;
363 my $confidence_level = 0;
364 if ($report_summary{Deceased}) {
365  
366 # We only taking Deceased flag in ReportSummary into account
367 # if ConfidenceLevel 7 or above
368 my ($deceased_record) = $twig->get_xpath('/Search/Result/Deceased/DeceasedRecord');
369 $confidence_level = $deceased_record->findvalue('ConfidenceLevel') || 0;
370 }
371 if (($report_summary{Deceased} == 1 and $confidence_level > 6)
372 or $cr_deceased == 1)
373 {
374 $decision->{deceased} = 1;
375 }
376  
377 $report_summary{Fraud} ||= 0;
378 if ($report_summary{Fraud} == 1) {
379 $decision->{fraud} = 1;
380 }
381  
382 # get number of total verifications
383 my $cr_total = $credit_reference->findvalue('TotalNumberOfVerifications')
384 || 0;
385 $decision->{num_verifications} = $cr_total;
386  
387 # check if client is in any suspicious list
388 # we don't care about: COAMatch
389 #
390 # Add NoOfCCJ separately since we don't fail that one.
391  
392 $decision->{CCJ} = 1 if $credit_reference->findvalue('NoOfCCJ');
393  
394 my @matches =
395 map { $_->[0] }
396 grep { $_->[1] > 0 }
397 map { [$_, $credit_reference->findvalue($_) || 0] } qw(BOEMatch PEPMatch OFACMatch CIFASMatch);
398  
399 if (@matches) {
400 my @hard_fails = grep {
401 my $f = $_;
402 grep { "${f}Match" eq $_ } @matches
403 } qw(BOE PEP OFAC CIFAS);
404 $decision->{$_} = 1 for @hard_fails;
405 $decision->{deny} = 1 if @hard_fails;
406  
407 $decision->{matches} = \@matches;
408 }
409  
410 # if client is in Directors list, we should not fully authenticate him
411 if ($report_summary{Directors}) {
412 $decision->{director} = 1;
413 $decision->{matches} = [@{$decision->{matches}}, 'Directors'];
414 }
415  
416 # check if client can be fully authenticated
417 my @kyc_two =
418 grep { $_ >= 2 }
419 map { $kyc_summary->findvalue("$_/Count") || 0 } qw(FullNameAndAddress SurnameAndAddress Address DateOfBirth);
420 if (@kyc_two or $cr_total >= 2) {
421 $decision->{fully_authenticated} = 1;
422 }
423  
424 return $decision;
425 }
426  
427 sub _get_result_checkid {
428  
429 my $self = shift;
430 my $passed = 0;
431  
432 # Convert xml to hashref
433 my $result = $self->_xml_as_hash or croak 'no xml result';
434  
435 if ((
436 ($result->{'Result'}->{'ElectoralRoll'}->{'Type'} eq 'Result' and $result->{'Result'}->{'ElectoralRoll'}->{'Summary'}->{'Decision'} == 1)
437 or ( $result->{'Result'}->{'Directors'}->{'Type'} eq 'Result'
438 and $result->{'Result'}->{'Directors'}->{'Summary'}->{'Decision'} == 1)
439 or ( $result->{'Result'}->{'Telephony'}->{'Type'} eq 'Result'
440 and $result->{'Result'}->{'Telephony'}->{'Summary'}->{'Decision'} == 1)))
441 {
442  
443 # Check Directors DecisionReasons
444 if ($result->{'Result'}->{'Directors'}->{'Type'} eq 'Result') {
445 DIRECTORS_DECISION_REASONS:
446 foreach my $decision_reason (@{$result->{'Result'}->{'Directors'}->{'Summary'}->{'DecisionReasons'}->{'DecisionReason'}}) {
447 if ( $decision_reason->{'Element'} eq 'Director/Person/DateOfBirth'
448 and $decision_reason->{'Decision'} == 1)
449 {
450 $passed = 1;
451 last DIRECTORS_DECISION_REASONS;
452 }
453 }
454  
455 if (not $passed) {
456 ELECTORALROLL_DECISION_REASONS:
457 foreach my $decision_reason (@{$result->{'Result'}->{'ElectoralRoll'}->{'Summary'}->{'DecisionReasons'}->{'DecisionReason'}}) {
458 if ( $decision_reason->{'Element'} eq 'ElectoralRollRecord/Person/DateOfBirth'
459 and $decision_reason->{'Decision'} == 1)
460 {
461 $passed = 1;
462 last ELECTORALROLL_DECISION_REASONS;
463 }
464 }
465 }
466 }
467 }
468  
469 return $passed;
470 }
471  
472 sub _do_192_authentication {
473 my $self = shift;
474  
475 my $search_option = $self->{search_option};
476  
477 my $force_recheck = $self->{force_recheck} || 0;
478  
479 my $residence = $self->{residence};
480  
481 # check for 192 supported countries
482 croak "Invalid residence: " . $self->{client_id} . ", Residence $residence" unless ($self->valid_country($self->{residence}));
483  
484 if (!$force_recheck && $self->has_done_request) {
485 $self->{result_as_xml} = $self->get_192_xml_report;
486 return 1;
487 }
488  
489 # No previous result so prepare a request
490  
491 try {
492 $self->_build_request
493 } catch {
494 croak "Cannot build xml_request for [" . $self->{client_id} . "/$search_option]"
495 }
496  
497 try {
498 $self->_send_request
499 } catch ($e) {
500 croak "could not send xml request: $e"
501 };
502  
503 my $result = $self->_xml_as_hash;
504 croak "ErrorCode: $result->{ErrorCode}, ErrorMessage: $result->{ErrorMessage}" if $result->{ErrorCode};
505  
506 # Remove old pdf in case this client has done the 192 pdf request before
507 my $file_pdf = $self->_pdf_report_filename;
508 unlink $file_pdf if -e $file_pdf;
509  
510 # Save xml result
511 my $folder_xml = "$self->{folder}/xml";
512 Path::Tiny::path($folder_xml)->mkpath unless -d $folder_xml;
513  
514 my $file_xml = $self->_xml_report_filename;
515 Path::Tiny::path($file_xml)->spew($self->{result_as_xml});
516  
517 croak "Couldn't save 192.com xml result for " . $self->{client_id} unless -e $file_xml;
518  
519 $self->save_pdf_result;
520  
521 return 1;
522 }
523  
524 sub _xml_report_filename {
525 my $self = shift;
526 my $search_option = $self->{search_option};
527 return "$self->{folder}/xml/" . $self->{client_id} . ".$search_option";
528 }
529  
530 sub _pdf_report_filename {
531 my $self = shift;
532 my $search_option = $self->{search_option};
533 return "$self->{folder}/pdf/" . $self->{client_id} . ".$search_option.pdf";
534 }
535  
536 1;
537  
538 =head1 NAME
539  
540 Experian::IDAuth - Experian's ID Authenticate service
541  
542 =head1 DESCRIPTION
543  
544 This module provides an interface to Experian's Identity Authenticate service.
545 L<http://www.experian.co.uk/identity-and-fraud/products/authenticate.html>
546  
547 First create a subclass of this module to override the defaults method
548 with your own data.
549  
550 package My::Experian;
551 use strict;
552 use warnings;
553 use base 'Experian::IDAuth';
554  
555 sub defaults {
556 my $self = shift;
557  
558 return (
559 $self->SUPER::defaults,
560 username => 'my_user',
561 password => 'my_pass',
562 residence => $residence,
563 postcode => $postcode || '',
564 date_of_birth => $date_of_birth || '',
565 first_name => $first_name || '',
566 last_name => $last_name || '',
567 phone => $phone || '',
568 email => $email || '',
569 );
570 }
571  
572 1;
573  
574 Then use this module.
575  
576 use My::Experian;
577  
578 # search_option can either be ProveID_KYC or CheckID
579 my $prove_id = My::Experian->new(
580 search_option => 'ProveID_KYC',
581 );
582  
583 my $prove_id_result = $prove_id->get_result();
584  
585 if (!$prove_id->has_done_request) {
586 # connection problems
587 die;
588 }
589  
590 if ($prove_id_result->{deceased} || $prove_id_result->{fraud}) {
591 # client flagged as deceased or fraud
592 }
593 if ($prove_id_result->{deny}) {
594 # client on any of PEP, OFAC, or BOE list
595 # you can check $prove_id_result->{PEP} etc if you want more detail
596 }
597 if ($prove_id_result->{fully_authenticated}) {
598 # client successfully authenticated,
599 # DOES NOT MEAN NO CONCERNS
600  
601 # check number of credit verifications done
602 print "Number of credit verifications: " . $prove_id_result->{num_verifications} . "\n";
603 }
604  
605 # CheckID is a more simpler version and can be used if ProveID_KYC fails
606 my $check_id = My::Experian->new(
607 search_option => 'CheckID',
608 );
609  
610 if (!$check_id->has_done_request) {
611 # connection problems
612 die;
613 }
614  
615 if ($check_id->get_result()) {
616 # client successfully authenticated
617 }
618  
619 =head1 METHODS
620  
621 =head2 new()
622  
623 Creates a new object of your derived class. The parent class should contain most of the attributes required for new(). But you can set search_option to either ProveID_KYC or CheckID
624  
625 =head2 get_result()
626  
627 Return the Experian results as a hashref
628  
629 =head2 save_pdf_result()
630  
631 Save the Experian credentials as a PDF
632  
633 =head2 defaults()
634  
635 Return default value
636  
637 =head2 get_192_xml_report()
638  
639 Return 192 xml report
640  
641 =head2 has_done_request()
642  
643 Check the request finished or not
644  
645 =head2 has_downloaded_pdf
646  
647 Check the file is downloaded an is a pdf file
648  
649 =head2 set
650  
651 set attributes of object
652  
653 =head2 valid_country
654  
655 Check a country is valid
656  
657 =head1 AUTHOR
658  
659 binary.com, C<perl at binary.com>
660  
661 =head1 BUGS
662  
663 Please report any bugs or feature requests to C<bug-experian-idauth at rt.cpan.org>,
664 or through the web interface at
665 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Experian-IDAuth>.
666 We will be notified, and then you'll automatically be notified of progress
667 on your bug as we make changes.
668  
669 =head1 SUPPORT
670  
671 You can find documentation for this module with the perldoc command.
672  
673 perldoc Experian::IDAuth
674  
675  
676 You can also look for information at:
677  
678 =over 4
679  
680 =item * RT: CPAN's request tracker (report bugs here)
681  
682 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Experian-IDAuth>
683  
684 =item * AnnoCPAN: Annotated CPAN documentation
685  
686 L<http://annocpan.org/dist/Experian-IDAuth>
687  
688 =item * CPAN Ratings
689  
690 L<http://cpanratings.perl.org/d/Experian-IDAuth>
691  
692 =item * Search CPAN
693  
694 L<http://search.cpan.org/dist/Experian-IDAuth/>
695  
696 =back
697  
698  
699 =head1 DEPENDENCIES
700  
701 Locale::Country
702 Path::Tiny
703 WWW::Mechanize
704 XML::Simple
705 XML::Twig
706 SOAP::Lite
707 IO::Socket
708 File::MimeInfo::Magic
709 Syntax::Keyword::Try
710  
711 =cut
712  
713 1; # End of Experian::IDAuth
714  
↑ Summary