File Coverage

blib/lib/Plack/Middleware/Auth/AccessToken.pm
Criterion Covered Total %
statement 38 38 100.0
branch 13 16 81.2
condition 8 10 80.0
subroutine 9 9 100.0
pod 2 3 66.6
total 70 76 92.1


line stmt bran cond sub pod time code
1             package Plack::Middleware::Auth::AccessToken;
2             {
3             $Plack::Middleware::Auth::AccessToken::VERSION = '0.11';
4             }
5             #ABSTRACT: Secret access token (aka OAuth Bearer) authentification
6              
7 2     2   24952 use strict;
  2         3  
  2         66  
8 2     2   10 use warnings;
  2         4  
  2         60  
9 2     2   921 use parent 'Plack::Middleware';
  2         391  
  2         15  
10 2     2   18573 use Plack::Util::Accessor qw(authenticator token_type reject_http);
  2         10  
  2         14  
11 2     2   101 use Plack::Util ();
  2         3  
  2         38  
12 2     2   1766 use Plack::Request;
  2         117461  
  2         627  
13              
14             sub prepare_app {
15 2     2 1 690 my $self = shift;
16              
17 2 50 50     7 die 'authenticator must be a code reference'
18             unless (ref $self->authenticator || '') eq 'CODE';
19              
20 2 100       100 $self->token_type('bearer')
21             unless defined $self->token_type;
22              
23 2 50 66     23 die 'reject_http should be a code reference'
24             if (ref $self->reject_http and ref $self->reject_http ne 'CODE');
25             }
26              
27             sub call {
28 9     9 1 33131 my ($self, $env) = @_;
29              
30 9         10 my $token;
31              
32 9 100       22 if (my $auth = $env->{HTTP_AUTHORIZATION}) {
33 4         15 my $token_type = $self->token_type;
34 4 50       94 $token = $1 if $auth =~ /^\s*$token_type\s+(.+)/i;
35             } else {
36 5         31 my $req = Plack::Request->new($env);
37 5         46 $token = $req->query_parameters->get('access_token');
38             }
39              
40 9 100       317 if (defined $token) {
41 7 100 100     19 if ($self->reject_http and $env->{'psgi.url_scheme'} eq 'http') {
    100          
42 1         10 $self->reject_http->($token);
43             } elsif ($self->authenticator->($token, $env)) {
44 4         73 return $self->app->($env);
45             }
46             } else {
47 2         7 return $self->unauthorized;
48             }
49              
50 3         44 return $self->unauthorized('Bad credentials')
51             }
52              
53             sub unauthorized {
54 5     5 0 6 my $self = shift;
55 5   100     19 my $body = shift || 'Authorization required';
56              
57 5         38 return [ 401,
58             [ 'Content-Type' => 'text/plain',
59             'Content-Length' => length $body ], [ $body ] ];
60             }
61              
62             1;
63              
64             __END__