Bug 20624: Net::OAuth2::AuthorizationServer is not a hard dependency
[koha.git] / t / db_dependent / api / v1 / patrons.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 under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 3 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along
15 # with Koha; if not, write to the Free Software Foundation, Inc.,
16 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18 use Modern::Perl;
19
20 use Test::More tests => 5;
21 use Test::Mojo;
22 use Test::Warn;
23
24 use t::lib::TestBuilder;
25 use t::lib::Mocks;
26
27 use C4::Auth;
28 use Koha::Database;
29 use Koha::Patron::Debarments qw/AddDebarment/;
30
31 my $schema  = Koha::Database->new->schema;
32 my $builder = t::lib::TestBuilder->new;
33
34 # FIXME: sessionStorage defaults to mysql, but it seems to break transaction handling
35 # this affects the other REST api tests
36 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
37
38 my $remote_address = '127.0.0.1';
39 my $t              = Test::Mojo->new('Koha::REST::V1');
40
41 subtest 'list() tests' => sub {
42     plan tests => 2;
43
44     $schema->storage->txn_begin;
45     unauthorized_access_tests('GET', undef, undef);
46     $schema->storage->txn_rollback;
47
48     subtest 'librarian access tests' => sub {
49         plan tests => 13;
50
51         $schema->storage->txn_begin;
52
53         Koha::Patrons->search->delete;
54
55         my ( $patron_id, $session_id ) = create_user_and_session({ authorized => 1 });
56         my $patron = Koha::Patrons->find($patron_id);
57
58         my $tx = $t->ua->build_tx(GET => '/api/v1/patrons');
59         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
60         $tx->req->env({ REMOTE_ADDR => '127.0.0.1' });
61         $t->request_ok($tx)
62           ->status_is(200);
63
64         $tx = $t->ua->build_tx(GET => '/api/v1/patrons?cardnumber=' . $patron->cardnumber);
65         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
66         $tx->req->env({ REMOTE_ADDR => '127.0.0.1' });
67         $t->request_ok($tx)
68           ->status_is(200)
69           ->json_is('/0/cardnumber' => $patron->cardnumber);
70
71         $tx = $t->ua->build_tx(GET => '/api/v1/patrons?address2='.
72                                   $patron->address2);
73         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
74         $tx->req->env({ REMOTE_ADDR => '127.0.0.1' });
75         $t->request_ok($tx)
76           ->status_is(200)
77           ->json_is('/0/address2' => $patron->address2);
78
79         my $patron_2 = $builder->build_object({ class => 'Koha::Patrons' });
80         AddDebarment({ borrowernumber => $patron_2->id });
81         # re-read from DB
82         $patron_2->discard_changes;
83         my $ub = $patron_2->unblessed;
84
85         $tx = $t->ua->build_tx( GET => '/api/v1/patrons?restricted=' . Mojo::JSON->true );
86         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
87         $tx->req->env({ REMOTE_ADDR => '127.0.0.1' });
88         $t->request_ok($tx)
89           ->status_is(200)
90           ->json_has('/0/restricted')
91           ->json_is( '/0/restricted' => Mojo::JSON->true )
92           ->json_hasnt('/1');
93
94         $schema->storage->txn_rollback;
95     };
96 };
97
98 subtest 'get() tests' => sub {
99     plan tests => 3;
100
101     $schema->storage->txn_begin;
102     unauthorized_access_tests('GET', -1, undef);
103     $schema->storage->txn_rollback;
104
105     subtest 'access own object tests' => sub {
106         plan tests => 4;
107
108         $schema->storage->txn_begin;
109
110         my ( $patron_id, $session_id ) = create_user_and_session({ authorized => 0 });
111
112         # Access patron's own data even though they have no borrowers flag
113         my $tx = $t->ua->build_tx(GET => "/api/v1/patrons/" . $patron_id);
114         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
115         $tx->req->env({ REMOTE_ADDR => '127.0.0.1' });
116         $t->request_ok($tx)
117           ->status_is(200);
118
119         my $guarantee = $builder->build_object({
120             class => 'Koha::Patrons',
121             value => {
122                 guarantorid => $patron_id,
123             }
124         });
125
126         # Access guarantee's data even though guarantor has no borrowers flag
127         $tx = $t->ua->build_tx(GET => "/api/v1/patrons/" . $guarantee->id );
128         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
129         $tx->req->env({ REMOTE_ADDR => '127.0.0.1' });
130         $t->request_ok($tx)
131           ->status_is(200);
132
133         $schema->storage->txn_rollback;
134     };
135
136     subtest 'librarian access tests' => sub {
137         plan tests => 6;
138
139         $schema->storage->txn_begin;
140
141         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
142         my ( undef, $session_id ) = create_user_and_session({ authorized => 1 });
143
144         my $tx = $t->ua->build_tx(GET => "/api/v1/patrons/" . $patron->id);
145         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
146         $t->request_ok($tx)
147           ->status_is(200)
148           ->json_is('/patron_id'        => $patron->id)
149           ->json_is('/category_id'      => $patron->categorycode )
150           ->json_is('/surname'          => $patron->surname)
151           ->json_is('/patron_card_lost' => Mojo::JSON->false );
152
153         $schema->storage->txn_rollback;
154     };
155 };
156
157 subtest 'add() tests' => sub {
158     plan tests => 2;
159
160     $schema->storage->txn_begin;
161
162     my $patron = Koha::REST::V1::Patrons::_to_api(
163         $builder->build_object( { class => 'Koha::Patrons' } )->TO_JSON );
164
165     unauthorized_access_tests('POST', undef, $patron);
166
167     $schema->storage->txn_rollback;
168
169     subtest 'librarian access tests' => sub {
170         plan tests => 20;
171
172         $schema->storage->txn_begin;
173
174         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
175         my $newpatron = Koha::REST::V1::Patrons::_to_api( $patron->TO_JSON );
176         # delete RO attributes
177         delete $newpatron->{patron_id};
178         delete $newpatron->{restricted};
179
180         # Create a library just to make sure its ID doesn't exist on the DB
181         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
182         my $deleted_library_id = $library_to_delete->id;
183         # Delete library
184         $library_to_delete->delete;
185
186         my ( undef, $session_id ) = create_user_and_session({ authorized => 1 });
187
188         $newpatron->{library_id} = $deleted_library_id;
189         my $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron );
190         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
191         warning_like {
192             $t->request_ok($tx)
193               ->status_is(409)
194               ->json_is('/error' => "Duplicate ID"); }
195             qr/^DBD::mysql::st execute failed: Duplicate entry/;
196
197         $newpatron->{library_id} = $patron->branchcode;
198
199         # Create a library just to make sure its ID doesn't exist on the DB
200         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
201         my $deleted_category_id = $category_to_delete->id;
202         # Delete library
203         $category_to_delete->delete;
204
205         $newpatron->{category_id} = $deleted_category_id; # Test invalid patron category
206         $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron);
207         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
208         $t->request_ok($tx)
209           ->status_is(400)
210           ->json_is('/error' => "Given category_id does not exist");
211         $newpatron->{category_id} = $patron->categorycode;
212
213         $newpatron->{falseproperty} = "Non existent property";
214         $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron);
215         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
216         $t->request_ok($tx)
217           ->status_is(400);
218         delete $newpatron->{falseproperty};
219
220         my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' });
221         $newpatron = Koha::REST::V1::Patrons::_to_api($patron_to_delete->TO_JSON);
222         # delete RO attributes
223         delete $newpatron->{patron_id};
224         delete $newpatron->{restricted};
225         $patron_to_delete->delete;
226
227         $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron);
228         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
229         $t->request_ok($tx)
230           ->status_is(201, 'Patron created successfully')
231           ->json_has('/patron_id', 'got a patron_id')
232           ->json_is( '/cardnumber' => $newpatron->{ cardnumber })
233           ->json_is( '/surname'    => $newpatron->{ surname })
234           ->json_is( '/firstname'  => $newpatron->{ firstname });
235
236         $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron);
237         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
238         warning_like {
239             $t->request_ok($tx)
240               ->status_is(409)
241               ->json_has( '/error', 'Fails when trying to POST duplicate cardnumber' )
242               ->json_has( '/conflict', 'cardnumber' ); }
243             qr/^DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key 'cardnumber'/;
244
245         $schema->storage->txn_rollback;
246     };
247 };
248
249 subtest 'update() tests' => sub {
250     plan tests => 2;
251
252     $schema->storage->txn_begin;
253     unauthorized_access_tests('PUT', 123, {email => 'nobody@example.com'});
254     $schema->storage->txn_rollback;
255
256     subtest 'librarian access tests' => sub {
257         plan tests => 23;
258
259         $schema->storage->txn_begin;
260
261         t::lib::Mocks::mock_preference('minPasswordLength', 1);
262         my ( $patron_id_1, $session_id ) = create_user_and_session({ authorized => 1 });
263         my ( $patron_id_2, undef )       = create_user_and_session({ authorized => 0 });
264
265         my $patron_1  = Koha::Patrons->find($patron_id_1);
266         my $patron_2  = Koha::Patrons->find($patron_id_2);
267         my $newpatron = Koha::REST::V1::Patrons::_to_api($patron_2->TO_JSON);
268         # delete RO attributes
269         delete $newpatron->{patron_id};
270         delete $newpatron->{restricted};
271
272         my $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/-1" => json => $newpatron );
273         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
274         $t->request_ok($tx)
275           ->status_is(404)
276           ->json_has('/error', 'Fails when trying to PUT nonexistent patron');
277
278         # Create a library just to make sure its ID doesn't exist on the DB
279         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
280         my $deleted_category_id = $category_to_delete->id;
281         # Delete library
282         $category_to_delete->delete;
283
284         $newpatron->{category_id} = $deleted_category_id;
285         $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/$patron_id_2" => json => $newpatron );
286         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
287         warning_like {
288             $t->request_ok($tx)
289               ->status_is(400)
290               ->json_is('/error' => "Given category_id does not exist"); }
291             qr/^DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/;
292         $newpatron->{category_id} = $patron_2->categorycode;
293
294         # Create a library just to make sure its ID doesn't exist on the DB
295         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
296         my $deleted_library_id = $library_to_delete->id;
297         # Delete library
298         $library_to_delete->delete;
299
300         $newpatron->{library_id} = $deleted_library_id;
301         $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/" . $patron_2->id => json => $newpatron );
302         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
303         warning_like {
304             $t->request_ok($tx)
305               ->status_is(400)
306               ->json_is('/error' => "Given library_id does not exist"); }
307             qr/^DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/;
308         $newpatron->{library_id} = $patron_2->branchcode;
309
310         $newpatron->{falseproperty} = "Non existent property";
311         $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/" . $patron_2->id => json => $newpatron );
312         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
313         $t->request_ok($tx)
314           ->status_is(400)
315           ->json_is('/errors/0/message' =>
316                     'Properties not allowed: falseproperty.');
317         delete $newpatron->{falseproperty};
318
319         # Set both cardnumber and userid to already existing values
320         $newpatron->{cardnumber} = $patron_1->cardnumber;
321         $newpatron->{userid}     = $patron_1->userid;
322
323         $tx = $t->ua->build_tx( PUT => "/api/v1/patrons/" . $patron_2->id => json => $newpatron );
324         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
325         warning_like {
326             $t->request_ok($tx)
327               ->status_is(409)
328               ->json_has( '/error' => "Fails when trying to update to an existing cardnumber or userid")
329               ->json_is(  '/conflict', 'cardnumber' ); }
330             qr/^DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key 'cardnumber'/;
331
332         $newpatron->{ cardnumber } = $patron_id_1.$patron_id_2;
333         $newpatron->{ userid }     = "user".$patron_id_1.$patron_id_2;
334         $newpatron->{ surname }    = "user".$patron_id_1.$patron_id_2;
335
336         $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/" . $patron_2->id => json => $newpatron);
337         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
338         $t->request_ok($tx)
339           ->status_is(200, 'Patron updated successfully')
340           ->json_has($newpatron);
341         is(Koha::Patrons->find( $patron_2->id )->cardnumber,
342            $newpatron->{ cardnumber }, 'Patron is really updated!');
343
344         $schema->storage->txn_rollback;
345     };
346 };
347
348 subtest 'delete() tests' => sub {
349     plan tests => 2;
350
351     $schema->storage->txn_begin;
352     unauthorized_access_tests('DELETE', 123, undef);
353     $schema->storage->txn_rollback;
354
355     subtest 'librarian access test' => sub {
356         plan tests => 4;
357
358         $schema->storage->txn_begin;
359
360         my ( undef, $session_id ) = create_user_and_session({ authorized => 1 });
361         my ( $patron_id, undef )  = create_user_and_session({ authorized => 0 });
362
363         my $tx = $t->ua->build_tx(DELETE => "/api/v1/patrons/-1");
364         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
365         $t->request_ok($tx)
366           ->status_is(404, 'Patron not found');
367
368         $tx = $t->ua->build_tx(DELETE => "/api/v1/patrons/$patron_id");
369         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
370         $t->request_ok($tx)
371           ->status_is(200, 'Patron deleted successfully');
372
373         $schema->storage->txn_rollback;
374     };
375 };
376
377 # Centralized tests for 401s and 403s assuming the endpoint requires
378 # borrowers flag for access
379 sub unauthorized_access_tests {
380     my ($verb, $patron_id, $json) = @_;
381
382     my $endpoint = '/api/v1/patrons';
383     $endpoint .= ($patron_id) ? "/$patron_id" : '';
384
385     subtest 'unauthorized access tests' => sub {
386         plan tests => 5;
387
388         my $tx = $t->ua->build_tx($verb => $endpoint => json => $json);
389         $t->request_ok($tx)
390           ->status_is(401);
391
392         my ($borrowernumber, $session_id) = create_user_and_session({
393             authorized => 0 });
394
395         $tx = $t->ua->build_tx($verb => $endpoint => json => $json);
396         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
397         $t->request_ok($tx)
398           ->status_is(403)
399           ->json_has('/required_permissions');
400     };
401 }
402
403 sub create_user_and_session {
404
405     my $args  = shift;
406     my $flags = ( $args->{authorized} ) ? 16 : 0;
407
408     my $user = $builder->build(
409         {
410             source => 'Borrower',
411             value  => {
412                 flags => $flags,
413                 gonenoaddress => 0,
414                 lost => 0,
415                 email => 'nobody@example.com',
416                 emailpro => 'nobody@example.com',
417                 B_email => 'nobody@example.com'
418             }
419         }
420     );
421
422     # Create a session for the authorized user
423     my $session = C4::Auth::get_session('');
424     $session->param( 'number',   $user->{borrowernumber} );
425     $session->param( 'id',       $user->{userid} );
426     $session->param( 'ip',       '127.0.0.1' );
427     $session->param( 'lasttime', time() );
428     $session->flush;
429
430     return ( $user->{borrowernumber}, $session->id );
431 }