| 1 | package Vee::Authorization; |
|---|
| 2 | |
|---|
| 3 | use strict; |
|---|
| 4 | use warnings; |
|---|
| 5 | |
|---|
| 6 | use base 'Exporter'; |
|---|
| 7 | |
|---|
| 8 | =head1 NAME |
|---|
| 9 | |
|---|
| 10 | Vee::Authorization - Custom authorization for Catalyst |
|---|
| 11 | |
|---|
| 12 | =head1 SYNOPSIS |
|---|
| 13 | |
|---|
| 14 | $c->can_i('create_post', $thread->id); |
|---|
| 15 | |
|---|
| 16 | =head1 DESCRIPTION |
|---|
| 17 | |
|---|
| 18 | Quick authorization module, to check whether the currently logged-in user has |
|---|
| 19 | been given a particular permission. |
|---|
| 20 | |
|---|
| 21 | =head1 FUNCTIONS |
|---|
| 22 | |
|---|
| 23 | =head2 has_permission |
|---|
| 24 | |
|---|
| 25 | Returns 1 if the current user has the given permission in the given scope, 0 if |
|---|
| 26 | the permission has been explicitly denied, or undef if there is no applicable |
|---|
| 27 | rule. |
|---|
| 28 | |
|---|
| 29 | =cut |
|---|
| 30 | |
|---|
| 31 | sub has_permission { |
|---|
| 32 | my ($c, $permission, $scope) = @_; |
|---|
| 33 | $scope = $scope ? [ $scope, '' ] : ''; |
|---|
| 34 | return 0 unless $c->user; |
|---|
| 35 | |
|---|
| 36 | my @usergroups = $c->model('UserGroups')->search({ user_id => [ 0, $c->user->obj->id ] })->get_column('group_id')->all; |
|---|
| 37 | # my %seen; |
|---|
| 38 | |
|---|
| 39 | # TODO: get group parents! |
|---|
| 40 | my @groupperms = $c->model('GroupPermissions')->search({ |
|---|
| 41 | group_id => { -in => \@usergroups }, |
|---|
| 42 | permission => [ $permission, 'splat' ], |
|---|
| 43 | scope => $scope, |
|---|
| 44 | }, { |
|---|
| 45 | order_by => \'scope = "" DESC, permission = "splat" DESC', |
|---|
| 46 | group_by => [ 'scope', 'permission' ], |
|---|
| 47 | columns => [ 'polarity' ], |
|---|
| 48 | }); |
|---|
| 49 | if (!@groupperms) { |
|---|
| 50 | return undef |
|---|
| 51 | } elsif (grep { $_->polarity eq 'deny' } @groupperms) { |
|---|
| 52 | return 0 |
|---|
| 53 | } else { |
|---|
| 54 | return 1 |
|---|
| 55 | } |
|---|
| 56 | } |
|---|
| 57 | |
|---|
| 58 | # infuse Catalyst with some awesome |
|---|
| 59 | { |
|---|
| 60 | no strict 'refs'; |
|---|
| 61 | *{'Vee::can_i'} = \&has_permission; |
|---|
| 62 | } |
|---|
| 63 | |
|---|
| 64 | =head1 AUTHOR |
|---|
| 65 | |
|---|
| 66 | Maintainer: Alex "Eevee" Munroe (C<veekun@veekun.com>) |
|---|
| 67 | |
|---|
| 68 | See the included F<AUTHORS> file for a full list of contributers. |
|---|
| 69 | |
|---|
| 70 | =head1 LICENSE |
|---|
| 71 | |
|---|
| 72 | See the included F<LICENSE> file. |
|---|
| 73 | |
|---|
| 74 | =cut |
|---|
| 75 | |
|---|
| 76 | 1; |
|---|