3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20 use Test::More tests => 5;
23 use Module::Load::Conditional qw(can_load);
30 use t::lib::TestBuilder;
32 my $t = Test::Mojo->new('Koha::REST::V1');
33 my $schema = Koha::Database->new->schema;
34 my $builder = t::lib::TestBuilder->new();
36 my $remote_address = '127.0.0.1';
39 # FIXME: CGI::Session::Driver::DBI explicitly sets AutoCommit=1 [1] which breaks the rollback in out tests.
40 # Until we change into some other library, set SessionStorage to 'tmp'
41 # [1] https://metacpan.org/source/CGI::Session::Driver::DBI#L28
42 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
44 subtest 'token-based tests' => sub {
46 if ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) {
50 plan skip_all => 'Net::OAuth2::AuthorizationServer not available';
53 $schema->storage->txn_begin;
55 my $patron = $builder->build_object({
56 class => 'Koha::Patrons',
57 value => { flags => 1 },
60 t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 1);
62 my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store;
65 grant_type => 'client_credentials',
66 client_id => $api_key->client_id,
67 client_secret => $api_key->secret
69 $t->post_ok('/api/v1/oauth/token', form => $formData)
71 ->json_is('/expires_in' => 3600)
72 ->json_is('/token_type' => 'Bearer')
73 ->json_has('/access_token');
75 my $access_token = $t->tx->res->json->{access_token};
81 my $tx = $t->ua->build_tx(GET => '/api/v1/acquisitions/orders');
82 $tx->req->headers->authorization("Bearer $access_token");
83 $tx->req->headers->header( 'x-koha-embed' => 'fund' );
85 $t->app->hook(after_dispatch => sub {
86 $stash = shift->stash;
87 $interface = C4::Context->interface;
88 $userenv = C4::Context->userenv;
91 # With access token and permissions, it returns 200
92 #$patron->flags(2**4)->store;
93 $t->request_ok($tx)->status_is(200);
95 my $user = $stash->{'koha.user'};
96 ok( defined $user, 'The \'koha.user\' object is defined in the stash') and
97 is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and
98 is( $user->borrowernumber, $patron->borrowernumber, 'The stashed user is the right one' );
99 is( $userenv->{number}, $patron->borrowernumber, 'userenv set correctly' );
100 is( $interface, 'api', "Interface correctly set to \'api\'" );
102 my $embed = $stash->{'koha.embed'};
103 ok( defined $embed, 'The embed hashref is generated and stashed' );
104 is_deeply( $embed, { fund => {} }, 'The embed data structure is correct' );
106 $schema->storage->txn_rollback;
109 subtest 'cookie-based tests' => sub {
113 $schema->storage->txn_begin;
115 my ( $borrowernumber, $session_id ) = create_user_and_session({ authorized => 1 });
117 $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
118 $tx->req->cookies( { name => 'CGISESSID', value => $session_id } );
119 $tx->req->env( { REMOTE_ADDR => $remote_address } );
125 $t->app->hook(after_dispatch => sub {
126 $stash = shift->stash;
127 $interface = C4::Context->interface;
128 $userenv = C4::Context->userenv;
131 $t->request_ok($tx)->status_is(200);
133 my $user = $stash->{'koha.user'};
134 ok( defined $user, 'The \'koha.user\' object is defined in the stash') and
135 is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and
136 is( $user->borrowernumber, $borrowernumber, 'The stashed user is the right one' );
137 is( $userenv->{number}, $borrowernumber, 'userenv set correctly' );
138 is( $interface, 'api', "Interface correctly set to \'api\'" );
140 subtest 'logged-out tests' => sub {
143 # Generate an anonymous session
144 my $session = C4::Auth::get_session('');
145 $session->param( 'ip', $remote_address );
146 $session->param( 'lasttime', time() );
147 $session->param( 'sessiontype', 'anon' );
150 my $tx = $t->ua->build_tx( GET => '/api/v1/libraries' );
151 $tx->req->cookies({ name => 'CGISESSID', value => $session->id });
152 $tx->req->env({ REMOTE_ADDR => $remote_address });
155 ->status_is( 401, 'Anonymous session on permission protected resource returns 401' )
156 ->json_is( { error => 'Authentication failure.' } );
159 $schema->storage->txn_rollback;
162 subtest 'anonymous requests to public API' => sub {
166 $schema->storage->txn_begin;
168 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
170 my $password = 'AbcdEFG123';
171 my $userid = 'tomasito';
173 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
174 $patron->set_password({ password => $password });
176 my $biblio_id = $builder->build_sample_biblio()->biblionumber;
178 # Enable the public API
179 t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
180 # Disable anonymous requests on the public namespace
181 t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 0 );
183 $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' })
184 ->status_is( 401, 'Unauthorized anonymous attempt to access a resource' );
186 # Disable anonymous requests on the public namespace
187 t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 1 );
189 $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' })
190 ->status_is( 200, 'Successfull anonymous access to a resource' );
192 $schema->storage->txn_rollback;
195 subtest 'x-koha-library tests' => sub {
199 $schema->storage->txn_begin;
204 $t->app->hook(after_dispatch => sub {
205 $stash = shift->stash;
206 $userenv = C4::Context->userenv;
209 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
210 my $superlibrarian = $builder->build_object({
211 class => 'Koha::Patrons',
212 value => { flags => 1 }
214 my $password = 'thePassword123';
215 $superlibrarian->set_password({ password => $password, skip_validation => 1 });
216 my $superlibrarian_userid = $superlibrarian->userid;
218 my $unprivileged = $builder->build_object({
219 class => 'Koha::Patrons',
220 value => { flags => undef }
222 $unprivileged->set_password({ password => $password, skip_validation => 1 });
223 my $unprivileged_userid = $unprivileged->userid;
225 my $library = $builder->build_object( { class => 'Koha::Libraries' } );
227 ## Independent branches tests
228 t::lib::Mocks::mock_preference('IndependentBranches', 1);
231 "//$unprivileged_userid:$password@/api/v1/cities",
232 { 'x-koha-library' => $unprivileged->branchcode }
235 is( $userenv->{branch}, $unprivileged->branchcode, 'branch set correctly' );
237 $t->get_ok( "//$unprivileged_userid:$password@/api/v1/cities" =>
238 { 'x-koha-library' => $library->id } )->status_is(403)
240 '/error' => 'Unauthorized attempt to set library to ' . $library->id );
242 $t->get_ok( "//$superlibrarian_userid:$password@/api/v1/cities" =>
243 { 'x-koha-library' => $library->id } )->status_is(200);
245 is( $userenv->{branch}, $library->id, 'branch set correctly' );
247 ## !Independent branches tests
248 t::lib::Mocks::mock_preference('IndependentBranches', 1);
250 "//$unprivileged_userid:$password@/api/v1/cities",
251 { 'x-koha-library' => $unprivileged->branchcode }
254 "//$unprivileged_userid:$password@/api/v1/cities",
255 { 'x-koha-library' => $library->id }
258 $schema->storage->txn_rollback;
261 subtest 'x-koha-override stash tests' => sub {
265 $schema->storage->txn_begin;
267 my $patron = $builder->build_object({
268 class => 'Koha::Patrons',
269 value => { flags => 1 }
271 my $password = 'thePassword123';
272 $patron->set_password({ password => $password, skip_validation => 1 });
273 my $userid = $patron->userid;
275 my $item = $builder->build_sample_item();
278 patron_id => $patron->id,
279 biblio_id => $item->biblionumber,
280 item_id => $item->id,
281 pickup_library_id => $patron->branchcode,
286 $t->app->hook(after_dispatch => sub {
287 $stash = shift->stash;
290 $t->post_ok( "//$userid:$password@/api/v1/holds" => { 'x-koha-override' => "any" } => json => $hold_data );
292 my $overrides = $stash->{'koha.overrides'};
293 is( ref($overrides), 'HASH', 'arrayref returned' );
294 ok( $overrides->{'any'}, "The value 'any' is found" );
296 $schema->storage->txn_rollback;
299 sub create_user_and_session {
302 my $flags = ( $args->{authorized} ) ? 16 : 0;
304 my $user = $builder->build(
306 source => 'Borrower',
313 # Create a session for the authorized user
314 my $session = C4::Auth::get_session('');
315 $session->param( 'number', $user->{borrowernumber} );
316 $session->param( 'id', $user->{userid} );
317 $session->param( 'ip', '127.0.0.1' );
318 $session->param( 'lasttime', time() );
321 return ( $user->{borrowernumber}, $session->id );