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