File Coverage

blib/lib/WWW/JSON/Role/Authentication.pm
Criterion Covered Total %
statement 13 13 100.0
branch 5 10 50.0
condition n/a
subroutine 2 2 100.0
pod n/a
total 20 25 80.0


line stmt bran cond sub pod time code
1             package WWW::JSON::Role::Authentication;
2 8     8   64284 use Moo::Role;
  8         22  
  8         45  
3             has authentication => (
4             is => 'rw',
5             lazy => 1,
6             clearer => 1,
7             default => sub { +{} },
8             isa => sub {
9             return if ref( $_[0] ) eq 'CODE';
10             die "Only 1 authentication method can be supplied "
11             unless keys( %{ $_[0] } ) <= 1;
12             },
13             trigger => 1,
14              
15             );
16              
17             sub _trigger_authentication {
18 2     2   34 my ( $self, $auth ) = @_;
19 2 50       11 return unless ($auth);
20 2 50       9 return if ref($auth) eq 'CODE';
21              
22 2         8 my ( $name, $data ) = %$auth;
23 2         10 my $role = __PACKAGE__ . '::' . $name;
24              
25 2 50       16 Moo::Role->apply_roles_to_object( $self, $role )
26             unless $self->does($role);
27              
28 2         106 my $handler = '_auth_' . $name;
29 2         4 my $validator = '_validate_' . $name;
30              
31 2 50       15 die "No handler found for auth type [$name]"
32             unless ( $self->can($handler) );
33 2 50       19 $self->$validator($data) if ( $self->can($validator) );
34             }
35              
36             around http_request => sub {
37             my ( $orig, $self ) = ( shift, shift );
38             if ( ref( $self->authentication ) eq 'CODE' ) {
39             $self->authentication->( $self, @_ );
40             }
41             elsif ( my ( $auth_type, $auth ) = %{ $self->authentication } ) {
42             my $handler = '_auth_' . $auth_type;
43             $self->$handler( $auth, @_ );
44             }
45             $self->$orig(@_);
46             };
47              
48             with qw/WWW::JSON::Role::Authentication::Basic
49             WWW::JSON::Role::Authentication::OAuth1
50             WWW::JSON::Role::Authentication::OAuth2
51             WWW::JSON::Role::Authentication::Header
52             /;
53             1;