Bug 26181: Regression tests
[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
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 => 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 => 42;
226
227         $schema->storage->txn_begin;
228
229         my $authorized_patron = $builder->build_object(
230             {
231                 class => 'Koha::Patrons',
232                 value => { flags => 1 }
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         my $result = $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $patron_2->borrowernumber => json => $newpatron )
322           ->status_is(200, 'Patron updated successfully');
323
324         # Put back the RO attributes
325         $newpatron->{patron_id} = $unauthorized_patron->to_api->{patron_id};
326         $newpatron->{restricted} = $unauthorized_patron->to_api->{restricted};
327         $newpatron->{anonymized} = $unauthorized_patron->to_api->{anonymized};
328         is_deeply($result->tx->res->json, $newpatron, 'Returned patron from update matches expected');
329
330         is(Koha::Patrons->find( $patron_2->id )->cardnumber,
331            $newpatron->{ cardnumber }, 'Patron is really updated!');
332
333         my $superlibrarian = $builder->build_object(
334             {
335                 class => 'Koha::Patrons',
336                 value => { flags => 1 }
337             }
338         );
339
340         $newpatron->{cardnumber} = $superlibrarian->cardnumber;
341         $newpatron->{userid}     = $superlibrarian->userid;
342         $newpatron->{email}      = 'nosense@no.no';
343         # delete RO attributes
344         delete $newpatron->{patron_id};
345         delete $newpatron->{restricted};
346         delete $newpatron->{anonymized};
347
348         # attempt to update
349         $authorized_patron->flags( 2**4 )->store; # borrowers flag = 4
350         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
351           ->status_is(403, "Non-superlibrarian user change of superlibrarian email forbidden")
352           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
353
354         # attempt to unset
355         $newpatron->{email} = undef;
356         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
357           ->status_is(403, "Non-superlibrarian user change of superlibrarian email to undefined forbidden")
358           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
359
360         $newpatron->{email}           = $superlibrarian->email;
361         $newpatron->{secondary_email} = 'nonsense@no.no';
362
363         # attempt to update
364         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
365           ->status_is(403, "Non-superlibrarian user change of superlibrarian secondary_email forbidden")
366           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
367
368         # attempt to unset
369         $newpatron->{secondary_email} = undef;
370         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
371           ->status_is(403, "Non-superlibrarian user change of superlibrarian secondary_email to undefined forbidden")
372           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
373
374         $newpatron->{secondary_email}  = $superlibrarian->emailpro;
375         $newpatron->{altaddress_email} = 'nonsense@no.no';
376
377         # attempt to update
378         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
379           ->status_is(403, "Non-superlibrarian user change of superlibrarian altaddress_email forbidden")
380           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
381
382         # attempt to unset
383         $newpatron->{altaddress_email} = undef;
384         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
385           ->status_is(403, "Non-superlibrarian user change of superlibrarian altaddress_email to undefined forbidden")
386           ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
387
388         # update patron without sending email
389         delete $newpatron->{email};
390         delete $newpatron->{secondary_email};
391         delete $newpatron->{altaddress_email};
392         $t->put_ok( "//$userid:$password@/api/v1/patrons/" . $superlibrarian->borrowernumber => json => $newpatron )
393           ->status_is(200, "Non-superlibrarian user can edit superlibrarian successfully if not changing email");
394 #  ->json_is( { error => "Not enough privileges to change a superlibrarian's email" } );
395
396         $schema->storage->txn_rollback;
397     };
398 };
399
400 subtest 'delete() tests' => sub {
401     plan tests => 2;
402
403     $schema->storage->txn_begin;
404     unauthorized_access_tests('DELETE', 123, undef);
405     $schema->storage->txn_rollback;
406
407     subtest 'librarian access test' => sub {
408         plan tests => 8;
409
410         $schema->storage->txn_begin;
411
412         my $authorized_patron = $builder->build_object(
413             {
414                 class => 'Koha::Patrons',
415                 value => { flags => 2**4 }    # borrowers flag = 4
416             }
417         );
418         my $password = 'thePassword123';
419         $authorized_patron->set_password(
420             { password => $password, skip_validation => 1 } );
421         my $userid = $authorized_patron->userid;
422
423         $t->delete_ok("//$userid:$password@/api/v1/patrons/-1")
424           ->status_is(404, 'Patron not found');
425
426         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
427
428         t::lib::Mocks::mock_preference('AnonymousPatron', $patron->borrowernumber);
429         $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber)
430           ->status_is(403, 'Anonymous patron cannot be deleted')
431           ->json_is( { error => 'Anonymous patron cannot be deleted' } );
432
433         t::lib::Mocks::mock_preference('AnonymousPatron', 0); # back to default
434         $t->delete_ok("//$userid:$password@/api/v1/patrons/" . $patron->borrowernumber)
435           ->status_is(204, 'SWAGGER3.2.4')
436           ->content_is('', 'SWAGGER3.3.4');
437
438         $schema->storage->txn_rollback;
439     };
440 };
441
442 subtest 'guarantors_can_see_charges() tests' => sub {
443
444     plan tests => 11;
445
446     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
447     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
448
449     $schema->storage->txn_begin;
450
451     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_fines => 0 } });
452     my $password = 'thePassword123';
453     $patron->set_password({ password => $password, skip_validation => 1 });
454     my $userid = $patron->userid;
455     my $patron_id = $patron->borrowernumber;
456
457     t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 0 );
458
459     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } )
460       ->status_is( 403 )
461       ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' );
462
463     t::lib::Mocks::mock_preference( 'AllowPatronToSetFinesVisibilityForGuarantor', 1 );
464
465     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->true } )
466       ->status_is( 200 )
467       ->json_is( {} );
468
469     ok( $patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' );
470
471     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_charges" => json => { allowed => Mojo::JSON->false } )
472       ->status_is( 200 )
473       ->json_is( {} );
474
475     ok( !$patron->discard_changes->privacy_guarantor_fines, 'privacy_guarantor_fines has been set correctly' );
476
477     $schema->storage->txn_rollback;
478 };
479
480 subtest 'guarantors_can_see_checkouts() tests' => sub {
481
482     plan tests => 11;
483
484     t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
485     t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
486
487     $schema->storage->txn_begin;
488
489     my $patron = $builder->build_object({ class => 'Koha::Patrons', value => { privacy_guarantor_checkouts => 0 } });
490     my $password = 'thePassword123';
491     $patron->set_password({ password => $password, skip_validation => 1 });
492     my $userid = $patron->userid;
493     my $patron_id = $patron->borrowernumber;
494
495     t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 0 );
496
497     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } )
498       ->status_is( 403 )
499       ->json_is( '/error', 'The current configuration doesn\'t allow the requested action.' );
500
501     t::lib::Mocks::mock_preference( 'AllowPatronToSetCheckoutsVisibilityForGuarantor', 1 );
502
503     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->true } )
504       ->status_is( 200 )
505       ->json_is( {} );
506
507     ok( $patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' );
508
509     $t->put_ok( "//$userid:$password@/api/v1/public/patrons/$patron_id/guarantors/can_see_checkouts" => json => { allowed => Mojo::JSON->false } )
510       ->status_is( 200 )
511       ->json_is( {} );
512
513     ok( !$patron->discard_changes->privacy_guarantor_checkouts, 'privacy_guarantor_checkouts has been set correctly' );
514
515     $schema->storage->txn_rollback;
516 };
517
518 # Centralized tests for 401s and 403s assuming the endpoint requires
519 # borrowers flag for access
520 sub unauthorized_access_tests {
521     my ($verb, $patron_id, $json) = @_;
522
523     my $endpoint = '/api/v1/patrons';
524     $endpoint .= ($patron_id) ? "/$patron_id" : '';
525
526     subtest 'unauthorized access tests' => sub {
527         plan tests => 5;
528
529         my $verb_ok = lc($verb) . '_ok';
530
531         $t->$verb_ok($endpoint => json => $json)
532           ->status_is(401);
533
534         my $unauthorized_patron = $builder->build_object(
535             {
536                 class => 'Koha::Patrons',
537                 value => { flags => 0 }
538             }
539         );
540         my $password = "thePassword123!";
541         $unauthorized_patron->set_password(
542             { password => $password, skip_validation => 1 } );
543         my $unauth_userid = $unauthorized_patron->userid;
544
545         $t->$verb_ok( "//$unauth_userid:$password\@$endpoint" => json => $json )
546           ->status_is(403)
547           ->json_has('/required_permissions');
548     };
549 }