Bug 29523: Add Koha::Object->accessible

This patch introduces a method for checking if an object can be
retrieved by the current user. It depends on the plural class
implementation of the ->search_limited method.

To test:
1. Apply this patch
2. Run:
   $ kshell
  k$ prove t/db_dependent/Koha/Object.t
=> SUCCESS: Tests pass!
3. Sign off :-D

Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
Signed-off-by: David Nind <david@davidnind.com>
Signed-off-by: Martin Renvoize <martin.renvoize@ptfs-europe.com>
Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>

Signed-off-by: Jonathan Druart <jonathan.druart@bugs.koha-community.org>

Signed-off-by: Marcel de Rooy <m.de.rooy@rijksmuseum.nl>
Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
This commit is contained in:
Tomás Cohen Arazi 2021-11-19 09:55:15 -03:00
parent d822e687d2
commit c24b46b403
Signed by: tomascohen
GPG key ID: 0A272EA1B2F3C15F
2 changed files with 70 additions and 1 deletions

View file

@ -893,6 +893,19 @@ sub _get_object_class {
return ${type};
}
sub _get_objects_class {
my ( $self ) = @_;
return unless $self;
if ( $self->_result->can('koha_objects_class') ) {
return $self->_result->koha_objects_class;
}
my $type = ref($self);
$type =~ s|Schema::Result::||;
return $type . "s";
}
=head3 AUTOLOAD
The autoload method is used only to get and set values for an objects properties.
@ -977,6 +990,28 @@ sub _handle_to_api_child {
return $res;
}
=head3 accessible
if ( $object->accessible ) { ... }
Whether the object should be accessible in the current context (requesting user).
It relies on the plural class properly implementing the I<search_limited> method.
=cut
sub accessible {
my ($self) = @_;
return $self->_get_objects_class->search_limited(
{
map { $_ => $self->$_ }
$self->_result->result_source->primary_columns
}
)->count > 0
? 1
: 0;
}
sub DESTROY { }
=head1 AUTHOR

View file

@ -17,7 +17,7 @@
use Modern::Perl;
use Test::More tests => 21;
use Test::More tests => 22;
use Test::Exception;
use Test::Warn;
@ -1120,3 +1120,37 @@ subtest 'messages() and add_message() tests' => sub {
$schema->storage->txn_rollback;
};
subtest 'accessible() tests' => sub {
plan tests => 2;
$schema->storage->txn_begin;
my $library_1 = $builder->build_object( { class => 'Koha::Libraries' } );
my $library_2 = $builder->build_object( { class => 'Koha::Libraries' } );
my $patron = $builder->build_object(
{
class => 'Koha::Patrons',
value => {
flags => 2**2, # only has catalogue permissions
branchcode => $library_1->id
}
}
);
my $patron_1 = $builder->build_object(
{ class => 'Koha::Patrons', value => { branchcode => $library_1->id } }
);
my $patron_2 = $builder->build_object(
{ class => 'Koha::Patrons', value => { branchcode => $library_2->id } }
);
t::lib::Mocks::mock_userenv( { patron => $patron } );
ok( $patron_1->accessible, 'Has access to the patron' );
ok( !$patron_2->accessible, 'Does not have access to the patron' );
$schema->storage->txn_rollback;
};