File Coverage

blib/lib/Dancer/Plugin/Auth/Tiny.pm
Criterion Covered Total %
statement 21 40 52.5
branch 1 8 12.5
condition 0 2 0.0
subroutine 7 11 63.6
pod 0 1 0.0
total 29 62 46.7


line stmt bran cond sub pod time code
1 4     4   1792277 use 5.008001;
  4         15  
  4         155  
2 4     4   24 use strict;
  4         6  
  4         112  
3 4     4   21 use warnings;
  4         7  
  4         256  
4              
5             package Dancer::Plugin::Auth::Tiny;
6             # ABSTRACT: Require logged-in user for specified routes
7             our $VERSION = '0.002'; # VERSION
8              
9 4     4   23 use Carp qw/croak/;
  4         8  
  4         279  
10              
11 4     4   22 use Dancer ':syntax';
  4         6  
  4         21  
12 4     4   5570 use Dancer::Plugin;
  4         6137  
  4         2110  
13              
14             my $conf;
15             my %dispatch = ( login => \&_build_login, );
16              
17             register 'needs' => sub {
18 0     0   0 my ( $self, $condition, @args ) = plugin_args(@_);
19              
20 0         0 my $builder = $dispatch{$condition};
21              
22 0 0       0 if ( ref $builder eq 'CODE' ) {
23 0         0 return $builder->(@args);
24             }
25             else {
26 0         0 croak "Unknown authorization condition '$condition'";
27             }
28             };
29              
30             sub extend {
31 1     1 0 22 my ( $class, @args ) = @_;
32 1 50       4 unless ( @args % 2 == 0 ) {
33 0         0 croak "arguments to $class\->extend must be key/value pairs";
34             }
35 1         9 %dispatch = ( %dispatch, @args );
36             }
37              
38             sub _build_login {
39 0     0     my ($coderef) = @_;
40             return sub {
41 0   0 0     $conf ||= { _default_conf(), %{ plugin_setting() } }; # lazy
  0            
42 0 0         if ( session $conf->{logged_in_key} ) {
43 0           goto $coderef;
44             }
45             else {
46 0           my $query_params = params("query");
47 0           my $data =
48             { $conf->{callback_key} => uri_for( request->path, $query_params ) };
49 0           for my $k ( @{ $conf->{passthrough} } ) {
  0            
50 0 0         $data->{$k} = params->{$k} if params->{$k};
51             }
52 0           return redirect uri_for( $conf->{login_route}, $data );
53             }
54 0           };
55             }
56              
57             sub _default_conf {
58             return (
59 0     0     login_route => '/login',
60             logged_in_key => 'user',
61             callback_key => 'return_url',
62             passthrough => [qw/user/],
63             );
64             }
65              
66             register_plugin for_versions => [ 1, 2 ];
67              
68             1;
69              
70              
71             # vim: ts=2 sts=2 sw=2 et:
72              
73             __END__