@@ -, +, @@ - In patrons.t, change expected HTTP 403 to 401 when accessing the endpoint without authentication (401 = not authenticated, 403 = authenticated, but no permission). --- Koha/REST/V1.pm | 53 ++++++++++++++++++++++++++++------------- api/v1/swagger/swagger.json | 1 + t/db_dependent/api/v1/patrons.t | 4 ++-- 3 files changed, 39 insertions(+), 19 deletions(-) --- a/Koha/REST/V1.pm +++ a/Koha/REST/V1.pm @@ -20,7 +20,7 @@ use Mojo::Base 'Mojolicious'; use File::Find::Rule; -use C4::Auth qw( check_cookie_auth get_session ); +use C4::Auth qw( check_cookie_auth get_session haspermission ); use C4::Context; use Koha::Logger; use Koha::Patrons; @@ -28,21 +28,6 @@ use Koha::Patrons; sub startup { my $self = shift; - my $route = $self->routes->under->to( - cb => sub { - my $c = shift; - - my ($status, $sessionID) = check_cookie_auth($c->cookie('CGISESSID')); - if ($status eq "ok") { - my $session = get_session($sessionID); - my $user = Koha::Patrons->find($session->param('number')); - $c->stash('koha.user' => $user); - } - - return 1; - } - ); - # Force charset=utf8 in Content-Type header for JSON responses $self->types->type(json => 'application/json; charset=utf8'); @@ -54,7 +39,6 @@ sub startup { } $self->plugin(Swagger2 => { - route => $route, url => $self->home->rel_file("api/v1/swagger/swagger.min.json"), }); } @@ -103,4 +87,39 @@ sub _isMinificationRequired { return 1 if $latestModification < -C $pathToSwaggerMinJson; # compare modification time } +sub authenticate_api_request { + my ($next, $c, $action_spec) = @_; + + my ($session, $user); + my ($status, $sessionID) = check_cookie_auth($c->cookie('CGISESSID')); + if ($status eq "ok") { + $session = get_session($sessionID); + $user = Koha::Patrons->find($session->param('number')); + $c->stash('koha.user' => $user); + } + else { + return $c->render_swagger( + { error => "Invalid authorization key" }, + {}, + 401 + ); + } + + if ($action_spec->{'x-koha-permission'}) { + if (C4::Auth::haspermission($user->userid, $action_spec->{'x-koha-permission'})) { + return $next->($c); + } + else { + return $c->render_swagger( + { error => "No permission" }, + {}, + 403 + ); + } + } + else { + return $next->($c); + } +} + 1; --- a/api/v1/swagger/swagger.json +++ a/api/v1/swagger/swagger.json @@ -13,6 +13,7 @@ } }, "basePath": "/api/v1", + "x-mojo-around-action": "Koha::REST::V1::authenticate_api_request", "paths": { "$ref": "paths.json" }, --- a/t/db_dependent/api/v1/patrons.t +++ a/t/db_dependent/api/v1/patrons.t @@ -47,10 +47,10 @@ my $borrower = $builder->build({ }); $t->get_ok('/api/v1/patrons') - ->status_is(403); + ->status_is(401); $t->get_ok("/api/v1/patrons/" . $borrower->{ borrowernumber }) - ->status_is(403); + ->status_is(401); my $loggedinuser = $builder->build({ source => 'Borrower', --