86f6bd5e9021a9cd1d1cd29c27a99b94ed7af683
[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 => 7;
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 my $t = Test::Mojo->new('Koha::REST::V1');
35 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
36
37 subtest 'list() tests' => sub {
38     plan tests => 2;
39
40     $schema->storage->txn_begin;
41     unauthorized_access_tests('GET', undef, undef);
42     $schema->storage->txn_rollback;
43
44     subtest 'librarian access tests' => sub {
45         plan tests => 13;
46
47         $schema->storage->txn_begin;
48
49         my $librarian = $builder->build_object(
50             {
51                 class => 'Koha::Patrons',
52                 value => { flags => 2**4 }    # borrowers flag = 4
53             }
54         );
55         my $password = 'thePassword123';
56         $librarian->set_password( { password => $password, skip_validation => 1 } );
57         my $userid = $librarian->userid;
58
59         $t->get_ok("//$userid:$password@/api/v1/patrons")
60           ->status_is(200);
61
62         $t->get_ok("//$userid:$password@/api/v1/patrons?cardnumber=" . $librarian->cardnumber)
63           ->status_is(200)
64           ->json_is('/0/cardnumber' => $librarian->cardnumber);
65
66         $t->get_ok("//$userid:$password@/api/v1/patrons?address2=" . $librarian->address2)
67           ->status_is(200)
68           ->json_is('/0/address2' => $librarian->address2);
69
70         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
71         AddDebarment({ borrowernumber => $patron->borrowernumber });
72
73         $t->get_ok("//$userid:$password@/api/v1/patrons?restricted=" . Mojo::JSON->true . "&cardnumber=" . $patron->cardnumber )
74           ->status_is(200)
75           ->json_has('/0/restricted')
76           ->json_is( '/0/restricted' => Mojo::JSON->true )
77           ->json_hasnt('/1');
78
79         $schema->storage->txn_rollback;
80     };
81 };
82
83 subtest 'get() tests' => sub {
84     plan tests => 2;
85
86     $schema->storage->txn_begin;
87     unauthorized_access_tests('GET', -1, undef);
88     $schema->storage->txn_rollback;
89
90     subtest 'librarian access tests' => sub {
91         plan tests => 6;
92
93         $schema->storage->txn_begin;
94
95         my $librarian = $builder->build_object(
96             {
97                 class => 'Koha::Patrons',
98                 value => { flags => 2**4 }    # borrowers flag = 4
99             }
100         );
101         my $password = 'thePassword123';
102         $librarian->set_password( { password => $password, skip_validation => 1 } );
103         my $userid = $librarian->userid;
104
105         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
106
107         $t->get_ok("//$userid:$password@/api/v1/patrons/" . $patron->id)
108           ->status_is(200)
109           ->json_is('/patron_id'        => $patron->id)
110           ->json_is('/category_id'      => $patron->categorycode )
111           ->json_is('/surname'          => $patron->surname)
112           ->json_is('/patron_card_lost' => Mojo::JSON->false );
113
114         $schema->storage->txn_rollback;
115     };
116 };
117
118 subtest 'add() tests' => sub {
119     plan tests => 2;
120
121     $schema->storage->txn_begin;
122
123     my $patron = $builder->build_object( { class => 'Koha::Patrons' } )->to_api;
124
125     unauthorized_access_tests('POST', undef, $patron);
126
127     $schema->storage->txn_rollback;
128
129     subtest 'librarian access tests' => sub {
130         plan tests => 21;
131
132         $schema->storage->txn_begin;
133
134         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
135         my $newpatron = $patron->to_api;
136         # delete RO attributes
137         delete $newpatron->{patron_id};
138         delete $newpatron->{restricted};
139         delete $newpatron->{anonymized};
140
141         # Create a library just to make sure its ID doesn't exist on the DB
142         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
143         my $deleted_library_id = $library_to_delete->id;
144         # Delete library
145         $library_to_delete->delete;
146
147         my $librarian = $builder->build_object(
148             {
149                 class => 'Koha::Patrons',
150                 value => { flags => 2**4 }    # borrowers flag = 4
151             }
152         );
153         my $password = 'thePassword123';
154         $librarian->set_password( { password => $password, skip_validation => 1 } );
155         my $userid = $librarian->userid;
156
157         $newpatron->{library_id} = $deleted_library_id;
158
159         warning_like {
160             $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
161               ->status_is(409)
162               ->json_is('/error' => "Duplicate ID"); }
163             qr/^DBD::mysql::st execute failed: Duplicate entry/;
164
165         $newpatron->{library_id} = $patron->branchcode;
166
167         # Create a library just to make sure its ID doesn't exist on the DB
168         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
169         my $deleted_category_id = $category_to_delete->id;
170         # Delete library
171         $category_to_delete->delete;
172
173         $newpatron->{category_id} = $deleted_category_id; # Test invalid patron category
174
175         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
176           ->status_is(400)
177           ->json_is('/error' => "Given category_id does not exist");
178         $newpatron->{category_id} = $patron->categorycode;
179
180         $newpatron->{falseproperty} = "Non existent property";
181
182         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
183           ->status_is(400);
184
185         delete $newpatron->{falseproperty};
186
187         my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' });
188         $newpatron = $patron_to_delete->to_api;
189         # delete RO attributes
190         delete $newpatron->{patron_id};
191         delete $newpatron->{restricted};
192         delete $newpatron->{anonymized};
193         $patron_to_delete->delete;
194
195         $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
196           ->status_is(201, 'Patron created successfully')
197           ->header_like(
198             Location => qr|^\/api\/v1\/patrons/\d*|,
199             'SWAGGER3.4.1'
200           )
201           ->json_has('/patron_id', 'got a patron_id')
202           ->json_is( '/cardnumber' => $newpatron->{ cardnumber })
203           ->json_is( '/surname'    => $newpatron->{ surname })
204           ->json_is( '/firstname'  => $newpatron->{ firstname });
205
206         warning_like {
207             $t->post_ok("//$userid:$password@/api/v1/patrons" => json => $newpatron)
208               ->status_is(409)
209               ->json_has( '/error', 'Fails when trying to POST duplicate cardnumber' )
210               ->json_like( '/conflict' => qr/(borrowers\.)?cardnumber/ ); }
211             qr/^DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key '(borrowers\.)?cardnumber'/;
212
213         $schema->storage->txn_rollback;
214     };
215 };
216
217 subtest 'update() tests' => sub {
218     plan tests => 2;
219
220     $schema->storage->txn_begin;
221     unauthorized_access_tests('PUT', 123, {email => 'nobody@example.com'});
222     $schema->storage->txn_rollback;
223
224     subtest 'librarian access tests' => sub {
225         plan tests => 22;
226
227         $schema->storage->txn_begin;
228
229         my $authorized_patron = $builder->build_object(
230             {
231                 class => 'Koha::Patrons',
232                 value => { flags => 2**4 } # borrowers flag = 4
233             }
234         );
235         my $password = 'thePassword123';
236         $authorized_patron->set_password(
237             { password => $password, skip_validation => 1 } );
238         my $userid = $authorized_patron->userid;
239
240         my $unauthorized_patron = $builder->build_object(
241             {
242                 class => 'Koha::Patrons',
243                 value => { flags => 0 }
244             }
245         );
246         $unauthorized_patron->set_password( { password => $password, skip_validation => 1 } );
247         my $unauth_userid = $unauthorized_patron->userid;
248
249         my $patron_1  = $authorized_patron;
250         my $patron_2  = $unauthorized_patron;
251         my $newpatron = $unauthorized_patron->to_api;
252         # delete RO attributes
253         delete $newpatron->{patron_id};
254         delete $newpatron->{restricted};
255         delete $newpatron->{anonymized};
256
257         $t->put_ok("//$userid:$password@/api/v1/patrons/-1" => json => $newpatron)
258           ->status_is(404)
259           ->json_has('/error', 'Fails when trying to PUT nonexistent patron');
260
261         # Create a library just to make sure its ID doesn't exist on the DB
262         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
263         my $deleted_category_id = $category_to_delete->id;
264         # Delete library
265         $category_to_delete->delete;
266
267         # Use an invalid category
268         $newpatron->{category_id} = $deleted_category_id;
269
270         $t->put_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron)
271           ->status_is(400)
272           ->json_is('/error' => "Given category_id does not exist");
273
274         # Restore the valid category
275         $newpatron->{category_id} = $patron_2->categorycode;
276
277         # Create a library just to make sure its ID doesn't exist on the DB
278         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
279         my $deleted_library_id = $library_to_delete->id;
280         # Delete library
281         $library_to_delete->delete;
282
283         # Use an invalid library_id
284         $newpatron->{library_id} = $deleted_library_id;
285
286         warning_like {
287             $t->put_ok("//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron)
288               ->status_is(400)
289               ->json_is('/error' => "Given library_id does not exist"); }
290             qr/^DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/;
291
292         # Restore the valid library_id
293         $newpatron->{library_id} = $patron_2->branchcode;
294
295         # Use an invalid attribute
296         $newpatron->{falseproperty} = "Non existent property";
297
298         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
299           ->status_is(400)
300           ->json_is('/errors/0/message' =>
301                     'Properties not allowed: falseproperty.');
302
303         # Get rid of the invalid attribute
304         delete $newpatron->{falseproperty};
305
306         # Set both cardnumber and userid to already existing values
307         $newpatron->{cardnumber} = $patron_1->cardnumber;
308         $newpatron->{userid}     = $patron_1->userid;
309
310         warning_like {
311             $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
312               ->status_is(409)
313               ->json_has( '/error' => "Fails when trying to update to an existing cardnumber or userid")
314               ->json_like( '/conflict' => qr/(borrowers\.)?cardnumber/ ); }
315             qr/^DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key '(borrowers\.)?cardnumber'/;
316
317         $newpatron->{ cardnumber } = $patron_1->id . $patron_2->id;
318         $newpatron->{ userid }     = "user" . $patron_1->id.$patron_2->id;
319         $newpatron->{ surname }    = "user" . $patron_1->id.$patron_2->id;
320
321         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
322           ->status_is(200, 'Patron updated successfully')
323           ->json_has($newpatron);
324         is(Koha::Patrons->find( $patron_2->id )->cardnumber,
325            $newpatron->{ cardnumber }, 'Patron is really updated!');
326
327         $schema->storage->txn_rollback;
328     };
329 };
330
331 subtest 'delete() tests' => sub {
332     plan tests => 2;
333
334     $schema->storage->txn_begin;
335     unauthorized_access_tests('DELETE', 123, undef);
336     $schema->storage->txn_rollback;
337
338     subtest 'librarian access test' => sub {
339         plan tests => 4;
340
341         $schema->storage->txn_begin;
342
343         my $authorized_patron = $builder->build_object(
344             {
345                 class => 'Koha::Patrons',
346                 value => { flags => 2**4 }    # borrowers flag = 4
347             }
348         );
349         my $password = 'thePassword123';
350         $authorized_patron->set_password(
351             { password => $password, skip_validation => 1 } );
352         my $userid = $authorized_patron->userid;
353
354         $t->delete_ok("//$userid:$password@/api/v1/patrons/-1")
355           ->status_is(404, 'Patron not found');
356
357         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
358
359         $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber)
360           ->status_is(200, 'Patron deleted successfully');
361
362         $schema->storage->txn_rollback;
363     };
364 };
365
366 subtest 'guarantors_can_see_charges() tests' => sub {
367
368     plan tests => 11;
369
370     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
371     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
372
373     $schema->storage->txn_begin;
374
375     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_fines => 0 } });
376     my $password = 'thePassword123';
377     $patron->set_password({ password => $password, skip_validation => 1 });
378     my $userid = $patron->userid;
379     my $patron_id = $patron->borrowernumber;
380
381     t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 0 );
382
383     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } )
384       ->status_is( 403 )
385       ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' );
386
387     t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 1 );
388
389     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } )
390       ->status_is( 200 )
391       ->json_is( {} );
392
393     ok( $patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' );
394
395     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->false } )
396       ->status_is( 200 )
397       ->json_is( {} );
398
399     ok( !$patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' );
400
401     $schema->storage->txn_rollback;
402 };
403
404 subtest 'guarantors_can_see_checkouts() tests' => sub {
405
406     plan tests => 11;
407
408     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
409     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
410
411     $schema->storage->txn_begin;
412
413     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_checkouts => 0 } });
414     my $password = 'thePassword123';
415     $patron->set_password({ password => $password, skip_validation => 1 });
416     my $userid = $patron->userid;
417     my $patron_id = $patron->borrowernumber;
418
419     t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 0 );
420
421     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } )
422       ->status_is( 403 )
423       ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' );
424
425     t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 1 );
426
427     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } )
428       ->status_is( 200 )
429       ->json_is( {} );
430
431     ok( $patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' );
432
433     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->false } )
434       ->status_is( 200 )
435       ->json_is( {} );
436
437     ok( !$patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' );
438
439     $schema->storage->txn_rollback;
440 };
441
442 # Centralized tests for 401s and 403s assuming the endpoint requires
443 # borrowers flag for access
444 sub unauthorized_access_tests {
445     my ($verb, $patron_id, $json) = @_;
446
447     my $endpoint = '/api/v1/patrons';
448     $endpoint .= ($patron_id) ? "/$patron_id" : '';
449
450     subtest 'unauthorized access tests' => sub {
451         plan tests => 5;
452
453         my $verb_ok = lc($verb) . '_ok';
454
455         $t->$verb_ok($endpoint => json => $json)
456           ->status_is(401);
457
458         my $unauthorized_patron = $builder->build_object(
459             {
460                 class => 'Koha::Patrons',
461                 value => { flags => 0 }
462             }
463         );
464         my $password = "thePassword123!";
465         $unauthorized_patron->set_password(
466             { password => $password, skip_validation => 1 } );
467         my $unauth_userid = $unauthorized_patron->userid;
468
469         $t->$verb_ok( "//$unauth_userid:$password\@$endpoint" => json => $json )
470           ->status_is(403)
471           ->json_has('/required_permissions');
472     };
473 }