From cb518dca8867f6b3c051558aabc1500c3abe0104 Mon Sep 17 00:00:00 2001 From: Tomas Cohen Arazi Date: Thu, 9 Jan 2020 11:13:47 -0300 Subject: [PATCH] Bug 24369: Add CORS support to the API This patch adds CORS support for API requests. It uses the AccessControlAllowOrigin syspref. To test: 1. Apply this patch 2. Run: $ kshell k$ prove t/db_dependent/api/v1/auth.t => SUCCESS: Tests pass! 3. Set the AccessControlAllowOrigin to any string (for example, *) 4. Use any API testing tool (Postman?) to place a request on the API => SUCCESS: The response headers include Access-Control-Allow-Origin, containing what you set on the syspref 5. Sign off :-D --- Koha/REST/V1.pm | 17 +++++++++++++---- t/db_dependent/api/v1/auth.t | 21 ++++++++++++++++++++- 2 files changed, 33 insertions(+), 5 deletions(-) diff --git a/Koha/REST/V1.pm b/Koha/REST/V1.pm index b1f4657d4a..610d75d38f 100644 --- a/Koha/REST/V1.pm +++ b/Koha/REST/V1.pm @@ -39,10 +39,19 @@ Overloaded Mojolicious->startup method. It is called at application startup. sub startup { my $self = shift; - # Remove /api/v1/app.pl/ from the path - $self->hook( before_dispatch => sub { - shift->req->url->base->path('/'); - }); + $self->hook( + before_dispatch => sub { + my $c = shift; + + # Remove /api/v1/app.pl/ from the path + $c->req->url->base->path('/'); + + # Handle CORS + $c->res->headers->header( 'Access-Control-Allow-Origin' => + C4::Context->preference('AccessControlAllowOrigin') ) + if C4::Context->preference('AccessControlAllowOrigin'); + } + ); # Force charset=utf8 in Content-Type header for JSON responses $self->types->type( json => 'application/json; charset=utf8' ); diff --git a/t/db_dependent/api/v1/auth.t b/t/db_dependent/api/v1/auth.t index 4f47227886..74c3162538 100644 --- a/t/db_dependent/api/v1/auth.t +++ b/t/db_dependent/api/v1/auth.t @@ -17,7 +17,7 @@ use Modern::Perl; -use Test::More tests => 1; +use Test::More tests => 2; use Test::Mojo; use Test::Warn; @@ -107,6 +107,25 @@ subtest 'under() tests' => sub { $schema->storage->txn_rollback; }; +subtest 'CORS support' => sub { + + plan tests => 6; + + t::lib::Mocks::mock_preference('AccessControlAllowOrigin',''); + $t->get_ok("/api/v1/patrons") + ->header_is( 'Access-control-allow-origin', undef, 'Header not returned' ); + # FIXME: newer Test::Mojo has header_exists_not + + t::lib::Mocks::mock_preference('AccessControlAllowOrigin',undef); + $t->get_ok("/api/v1/patrons") + ->header_is( 'Access-control-allow-origin', undef, 'Header not returned' ); + # FIXME: newer Test::Mojo has header_exists_not + + t::lib::Mocks::mock_preference('AccessControlAllowOrigin','*'); + $t->get_ok("/api/v1/patrons") + ->header_is( 'Access-control-allow-origin', '*', 'Header set' ); +}; + sub create_user_and_session { my $user = $builder->build( { -- 2.24.1