Bug 28271: Add the ability to set a new lost status when a claim is resolved
[koha.git] / t / db_dependent / api / v1 / auth_authenticate_api_request.t
1 #!/usr/bin/env perl
2
3 # This file is part of Koha.
4 #
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.
9 #
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.
14 #
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>.
17
18 use Modern::Perl;
19
20 use Test::More tests => 5;
21 use Test::Mojo;
22
23 use Module::Load::Conditional qw(can_load);
24
25 use Koha::ApiKeys;
26 use Koha::Database;
27 use Koha::Patrons;
28
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
31
32 my $t = Test::Mojo->new('Koha::REST::V1');
33 my $schema  = Koha::Database->new->schema;
34 my $builder = t::lib::TestBuilder->new();
35
36 my $remote_address = '127.0.0.1';
37 my $tx;
38
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' );
43
44 subtest 'token-based tests' => sub {
45
46     if ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) {
47         plan tests => 14;
48     }
49     else {
50         plan skip_all => 'Net::OAuth2::AuthorizationServer not available';
51     }
52
53     $schema->storage->txn_begin;
54
55     my $patron = $builder->build_object({
56         class => 'Koha::Patrons',
57         value  => { flags => 1 },
58     });
59
60     t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 1);
61
62     my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store;
63
64     my $formData = {
65         grant_type    => 'client_credentials',
66         client_id     => $api_key->client_id,
67         client_secret => $api_key->secret
68     };
69     $t->post_ok('/api/v1/oauth/token', form => $formData)
70         ->status_is(200)
71         ->json_is('/expires_in' => 3600)
72         ->json_is('/token_type' => 'Bearer')
73         ->json_has('/access_token');
74
75     my $access_token = $t->tx->res->json->{access_token};
76
77     my $stash;
78     my $interface;
79     my $userenv;
80
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' );
84
85     $t->app->hook(after_dispatch => sub {
86         $stash     = shift->stash;
87         $interface = C4::Context->interface;
88         $userenv   = C4::Context->userenv;
89     });
90
91     # With access token and permissions, it returns 200
92     #$patron->flags(2**4)->store;
93     $t->request_ok($tx)->status_is(200);
94
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\'" );
101
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' );
105
106     $schema->storage->txn_rollback;
107 };
108
109 subtest 'cookie-based tests' => sub {
110
111     plan tests => 8;
112
113     $schema->storage->txn_begin;
114
115     my ( $borrowernumber, $session_id ) = create_user_and_session({ authorized => 1 });
116
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 } );
120
121     my $stash;
122     my $interface;
123     my $userenv;
124
125     $t->app->hook(after_dispatch => sub {
126         $stash     = shift->stash;
127         $interface = C4::Context->interface;
128         $userenv   = C4::Context->userenv;
129     });
130
131     $t->request_ok($tx)->status_is(200);
132
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\'" );
139
140     subtest 'logged-out tests' => sub {
141         plan tests => 3;
142
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' );
148         $session->flush;
149
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 });
153
154         $t->request_ok($tx)
155           ->status_is( 401, 'Anonymous session on permission protected resource returns 401' )
156           ->json_is( { error => 'Authentication failure.' } );
157     };
158
159     $schema->storage->txn_rollback;
160 };
161
162 subtest 'anonymous requests to public API' => sub {
163
164     plan tests => 4;
165
166     $schema->storage->txn_begin;
167
168     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
169
170     my $password = 'AbcdEFG123';
171     my $userid   = 'tomasito';
172     # Add a patron
173     my $patron = $builder->build_object({ class => 'Koha::Patrons' });
174     $patron->set_password({ password => $password });
175     # Add a biblio
176     my $biblio_id = $builder->build_sample_biblio()->biblionumber;
177
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 );
182
183     $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' })
184       ->status_is( 401, 'Unauthorized anonymous attempt to access a resource' );
185
186     # Disable anonymous requests on the public namespace
187     t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 1 );
188
189     $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' })
190       ->status_is( 200, 'Successfull anonymous access to a resource' );
191
192     $schema->storage->txn_rollback;
193 };
194
195 subtest 'x-koha-library tests' => sub {
196
197     plan tests => 10;
198
199     $schema->storage->txn_begin;
200
201     my $stash;
202     my $userenv;
203
204     $t->app->hook(after_dispatch => sub {
205         $stash   = shift->stash;
206         $userenv = C4::Context->userenv;
207     });
208
209     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
210     my $superlibrarian = $builder->build_object({
211         class => 'Koha::Patrons',
212         value => { flags => 1 }
213     });
214     my $password = 'thePassword123';
215     $superlibrarian->set_password({ password => $password, skip_validation => 1 });
216     my $superlibrarian_userid = $superlibrarian->userid;
217
218     my $unprivileged = $builder->build_object({
219         class => 'Koha::Patrons',
220         value => { flags => undef }
221     });
222     $unprivileged->set_password({ password => $password, skip_validation => 1 });
223     my $unprivileged_userid = $unprivileged->userid;
224
225     my $library = $builder->build_object( { class => 'Koha::Libraries' } );
226
227     ## Independent branches tests
228     t::lib::Mocks::mock_preference('IndependentBranches', 1);
229
230     $t->get_ok(
231         "//$unprivileged_userid:$password@/api/v1/cities",
232         { 'x-koha-library' => $unprivileged->branchcode }
233     );
234
235     is( $userenv->{branch}, $unprivileged->branchcode, 'branch set correctly' );
236
237     $t->get_ok( "//$unprivileged_userid:$password@/api/v1/cities" =>
238           { 'x-koha-library' => $library->id } )->status_is(403)
239       ->json_is(
240         '/error' => 'Unauthorized attempt to set library to ' . $library->id );
241
242     $t->get_ok( "//$superlibrarian_userid:$password@/api/v1/cities" =>
243           { 'x-koha-library' => $library->id } )->status_is(200);
244
245     is( $userenv->{branch}, $library->id, 'branch set correctly' );
246
247     ## !Independent branches tests
248     t::lib::Mocks::mock_preference('IndependentBranches', 1);
249     $t->get_ok(
250         "//$unprivileged_userid:$password@/api/v1/cities",
251         { 'x-koha-library' => $unprivileged->branchcode }
252     );
253     $t->get_ok(
254         "//$unprivileged_userid:$password@/api/v1/cities",
255         { 'x-koha-library' => $library->id }
256     );
257
258     $schema->storage->txn_rollback;
259 };
260
261 subtest 'x-koha-override stash tests' => sub {
262
263     plan tests => 3;
264
265     $schema->storage->txn_begin;
266
267     my $patron = $builder->build_object({
268         class => 'Koha::Patrons',
269         value => { flags => 1 }
270     });
271     my $password = 'thePassword123';
272     $patron->set_password({ password => $password, skip_validation => 1 });
273     my $userid = $patron->userid;
274
275     my $item = $builder->build_sample_item();
276
277     my $hold_data = {
278         patron_id => $patron->id,
279         biblio_id => $item->biblionumber,
280         item_id   => $item->id,
281         pickup_library_id => $patron->branchcode,
282     };
283
284     my $stash;
285
286     $t->app->hook(after_dispatch => sub {
287         $stash = shift->stash;
288     });
289
290     $t->post_ok( "//$userid:$password@/api/v1/holds" => { 'x-koha-override' => "any" } => json => $hold_data );
291
292     my $overrides = $stash->{'koha.overrides'};
293     is( ref($overrides), 'HASH', 'arrayref returned' );
294     ok( $overrides->{'any'}, "The value 'any' is found" );
295
296     $schema->storage->txn_rollback;
297 };
298
299 sub create_user_and_session {
300
301     my $args  = shift;
302     my $flags = ( $args->{authorized} ) ? 16 : 0;
303
304     my $user = $builder->build(
305         {
306             source => 'Borrower',
307             value  => {
308                 flags => $flags
309             }
310         }
311     );
312
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() );
319     $session->flush;
320
321     return ( $user->{borrowernumber}, $session->id );
322 }