lib/Experian/IDAuth.pm

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