From b892d1a208332f32fa27a94acb11f385fef7bbb9 Mon Sep 17 00:00:00 2001 From: Lari Taskula Date: Tue, 19 Nov 2019 13:56:43 +0000 Subject: [PATCH] Bug 24067: Add new subroutine check_resource_ownership This patch adds a new subroutine called check_resource_ownership. The method is called when API consumer has no permission but the request may still be authorized if the user is accessing only their own resources. In this case, it will find a method called "owner_authorization" from the controller specified by the endpoint. Testable in following patches. Sponsored-by: Koha-Suomi Oy --- Koha/REST/V1/Auth.pm | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/Koha/REST/V1/Auth.pm b/Koha/REST/V1/Auth.pm index 8bffc977da..ef4a6ed9e6 100644 --- a/Koha/REST/V1/Auth.pm +++ b/Koha/REST/V1/Auth.pm @@ -326,6 +326,44 @@ sub allow_guarantor { } } +=head3 check_resource_ownership + +For endpoints under /api/v1/public namespace, you can allow API consumers to +access their own resources without having librarian permissions. + +See C for documentation on usage in OpenAPI spec. + +In order to authorize API consumer to their own resources, you must define a +method called C in controller class. This subroutine +usually reads request parameters and compares them to the Koha::Patron stored +in C<$c->stash('koha.user')>. + +=cut + +sub check_resource_ownership { + my ($c, $user) = @_; + + return 0 if not $c or not $user; + my $spec = $c->match->endpoint->pattern->defaults->{'openapi.op_spec'}; + my $xmojoto = $spec->{'x-mojo-to'}; + if ( $xmojoto =~ /([A-Za-z0-9:]+)#([A-Za-z0-9_]+)/ ) { + my $controller = "Koha::REST::V1::$1"; + if ( ! Module::Load::Conditional::can_load( + modules => {$controller => undef} )) { + return 0; + } + else { + if (my $owner_auth = $controller->can('owner_authorization')) { + return $owner_auth->( + $c, $2, $user, $spec->{'x-koha-authorization'} + ) ? 1 : 0; + } + } + } + + return 0; +} + =head3 check_object_ownership Determines ownership of an object from request parameters. -- 2.17.1