File Coverage

blib/lib/Mojolicious/Plugin/Authorization.pm
Criterion Covered Total %
statement 39 39 100.0
branch 5 10 50.0
condition 6 17 35.2
subroutine 9 9 100.0
pod 1 1 100.0
total 60 76 78.9


line stmt bran cond sub pod time code
1             package Mojolicious::Plugin::Authorization;
2             BEGIN {
3 2     2   1809 $Mojolicious::Plugin::Authorization::VERSION = '1.04';
4             }
5 2     2   594 use Mojo::Base 'Mojolicious::Plugin';
  2         8684  
  2         13  
6             # The dog is good, but our real competition is the Hypnotoad.
7             sub register {
8 1     1 1 39 my ($self, $app, $args) = @_;
9 1   50     3 $args ||= {};
10 1         2 for my $sub_ref ( qw/ has_priv is_role user_privs user_role / ) {
11 4 50 33     18 die __PACKAGE__, ": missing '$sub_ref' subroutine ref in parameters\n"
12             unless $args->{$sub_ref} && ref($args->{$sub_ref}) eq 'CODE';
13             }
14 1         2 my $has_priv_cb = $args->{has_priv};
15 1         1 my $is_role_cb = $args->{is_role};
16 1         1 my $user_privs_cb = $args->{user_privs};
17 1         1 my $user_role_cb = $args->{user_role};
18 1         1 my $fail_render = $args->{fail_render};
19             $app->routes->add_condition(has_priv => sub {
20 1     1   8096 my ($r, $c, $captures, $priv) = @_;
21 1 50 33     9 my $res = ($priv && $has_priv_cb->($c,$priv)) ? 1 : 0;
22 1 50 33     376 $c->render( %$fail_render ) if $fail_render && ! $res;
23 1         3 return $res;
24 1         5 });
25 1         25 for my $helper_name ( qw/ is_role is / ) {
26             $app->routes->add_condition($helper_name => sub {
27 2     2   18104 my ($r, $c, $captures, $role) = @_;
28 2 50 33     14 my $res = ($role && $is_role_cb->($c,$role)) ? 1 : 0;
29 2 50 33     880 $c->render( %$fail_render ) if $fail_render && ! $res;
30 2         5 return $res;
31 2         13 });
32             }
33             $app->helper(privileges => sub {
34 2     2   17035 my ($c, $user, $extradata) = @_;
35 2         8 return $user_privs_cb->($c, $user, $extradata);
36 1         14 });
37 1         27 for my $helper_name ( qw/ has_priv has_privilege / ) {
38             $app->helper($helper_name => sub {
39 8     8   76280 my ($c, $priv, $extradata) = @_;
40 8         30 my $has_priv = $has_priv_cb->($c, $priv, $extradata);
41 8         3124 return $has_priv;
42 2         26 });
43             }
44 1         13 for my $helper_name ( qw/ is is_role / ) {
45             $app->helper($helper_name => sub {
46 2     2   16837 my ($c, $role, $extradata) = @_;
47 2         9 return $is_role_cb->($c, $role, $extradata);
48 2         17 });
49             }
50             $app->helper(role => sub {
51 3     3   24763 my ($c, $user, $extradata) = @_;
52 3         14 return $user_role_cb->($c, $user, $extradata);
53 1         15 });
54             }
55             1;
56             __END__