8b28d7720d191a6d79c8f903935586c21817af33
[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         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 => 3;
98
99     $schema->storage->txn_begin;
100     unauthorized_access_tests('GET', -1, undef);
101     $schema->storage->txn_rollback;
102
103     subtest 'access own object tests' => sub {
104         plan tests => 4;
105
106         $schema->storage->txn_begin;
107
108         my ( $patron_id, $session_id ) = create_user_and_session({ authorized => 0 });
109
110         # Access patron's own data even though they have no borrowers flag
111         my $tx = $t->ua->build_tx(GET => "/api/v1/patrons/" . $patron_id);
112         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
113         $tx->req->env({ REMOTE_ADDR => '127.0.0.1' });
114         $t->request_ok($tx)
115           ->status_is(200);
116
117         my $guarantee = $builder->build_object({
118             class => 'Koha::Patrons',
119             value => {
120                 guarantorid => $patron_id,
121             }
122         });
123
124         # Access guarantee's data even though guarantor has no borrowers flag
125         $tx = $t->ua->build_tx(GET => "/api/v1/patrons/" . $guarantee->id );
126         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
127         $tx->req->env({ REMOTE_ADDR => '127.0.0.1' });
128         $t->request_ok($tx)
129           ->status_is(200);
130
131         $schema->storage->txn_rollback;
132     };
133
134     subtest 'librarian access tests' => sub {
135         plan tests => 6;
136
137         $schema->storage->txn_begin;
138
139         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
140         my ( undef, $session_id ) = create_user_and_session({ authorized => 1 });
141
142         my $tx = $t->ua->build_tx(GET => "/api/v1/patrons/" . $patron->id);
143         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
144         $t->request_ok($tx)
145           ->status_is(200)
146           ->json_is('/patron_id'        => $patron->id)
147           ->json_is('/category_id'      => $patron->categorycode )
148           ->json_is('/surname'          => $patron->surname)
149           ->json_is('/patron_card_lost' => Mojo::JSON->false );
150
151         $schema->storage->txn_rollback;
152     };
153 };
154
155 subtest 'add() tests' => sub {
156     plan tests => 2;
157
158     $schema->storage->txn_begin;
159
160     my $patron = Koha::REST::V1::Patrons::_to_api(
161         $builder->build_object( { class => 'Koha::Patrons' } )->TO_JSON );
162
163     unauthorized_access_tests('POST', undef, $patron);
164
165     $schema->storage->txn_rollback;
166
167     subtest 'librarian access tests' => sub {
168         plan tests => 20;
169
170         $schema->storage->txn_begin;
171
172         my $patron = $builder->build_object({ class => 'Koha::Patrons' });
173         my $newpatron = Koha::REST::V1::Patrons::_to_api( $patron->TO_JSON );
174         # delete RO attributes
175         delete $newpatron->{patron_id};
176         delete $newpatron->{restricted};
177
178         # Create a library just to make sure its ID doesn't exist on the DB
179         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
180         my $deleted_library_id = $library_to_delete->id;
181         # Delete library
182         $library_to_delete->delete;
183
184         my ( undef, $session_id ) = create_user_and_session({ authorized => 1 });
185
186         $newpatron->{library_id} = $deleted_library_id;
187         my $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron );
188         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
189         warning_like {
190             $t->request_ok($tx)
191               ->status_is(409)
192               ->json_is('/error' => "Duplicate ID"); }
193             qr/^DBD::mysql::st execute failed: Duplicate entry/;
194
195         $newpatron->{library_id} = $patron->branchcode;
196
197         # Create a library just to make sure its ID doesn't exist on the DB
198         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
199         my $deleted_category_id = $category_to_delete->id;
200         # Delete library
201         $category_to_delete->delete;
202
203         $newpatron->{category_id} = $deleted_category_id; # Test invalid patron category
204         $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron);
205         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
206         $t->request_ok($tx)
207           ->status_is(400)
208           ->json_is('/error' => "Given category_id does not exist");
209         $newpatron->{category_id} = $patron->categorycode;
210
211         $newpatron->{falseproperty} = "Non existent property";
212         $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron);
213         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
214         $t->request_ok($tx)
215           ->status_is(400);
216         delete $newpatron->{falseproperty};
217
218         my $patron_to_delete = $builder->build_object({ class => 'Koha::Patrons' });
219         $newpatron = Koha::REST::V1::Patrons::_to_api($patron_to_delete->TO_JSON);
220         # delete RO attributes
221         delete $newpatron->{patron_id};
222         delete $newpatron->{restricted};
223         $patron_to_delete->delete;
224
225         $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron);
226         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
227         $t->request_ok($tx)
228           ->status_is(201, 'Patron created successfully')
229           ->json_has('/patron_id', 'got a patron_id')
230           ->json_is( '/cardnumber' => $newpatron->{ cardnumber })
231           ->json_is( '/surname'    => $newpatron->{ surname })
232           ->json_is( '/firstname'  => $newpatron->{ firstname });
233
234         $tx = $t->ua->build_tx(POST => "/api/v1/patrons" => json => $newpatron);
235         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
236         warning_like {
237             $t->request_ok($tx)
238               ->status_is(409)
239               ->json_has( '/error', 'Fails when trying to POST duplicate cardnumber' )
240               ->json_has( '/conflict', 'cardnumber' ); }
241             qr/^DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key 'cardnumber'/;
242
243         $schema->storage->txn_rollback;
244     };
245 };
246
247 subtest 'update() tests' => sub {
248     plan tests => 2;
249
250     $schema->storage->txn_begin;
251     unauthorized_access_tests('PUT', 123, {email => 'nobody@example.com'});
252     $schema->storage->txn_rollback;
253
254     subtest 'librarian access tests' => sub {
255         plan tests => 22;
256
257         $schema->storage->txn_begin;
258
259         t::lib::Mocks::mock_preference('minPasswordLength', 1);
260         my ( $patron_id_1, $session_id ) = create_user_and_session({ authorized => 1 });
261         my ( $patron_id_2, undef )       = create_user_and_session({ authorized => 0 });
262
263         my $patron_1  = Koha::Patrons->find($patron_id_1);
264         my $patron_2  = Koha::Patrons->find($patron_id_2);
265         my $newpatron = Koha::REST::V1::Patrons::_to_api($patron_2->TO_JSON);
266         # delete RO attributes
267         delete $newpatron->{patron_id};
268         delete $newpatron->{restricted};
269
270         my $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/-1" => json => $newpatron );
271         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
272         $t->request_ok($tx)
273           ->status_is(404)
274           ->json_has('/error', 'Fails when trying to PUT nonexistent patron');
275
276         # Create a library just to make sure its ID doesn't exist on the DB
277         my $category_to_delete = $builder->build_object({ class => 'Koha::Patron::Categories' });
278         my $deleted_category_id = $category_to_delete->id;
279         # Delete library
280         $category_to_delete->delete;
281
282         $newpatron->{category_id} = $deleted_category_id;
283         $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/$patron_id_2" => json => $newpatron );
284         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
285         $t->request_ok($tx)
286           ->status_is(400)
287           ->json_is('/error' => "Given category_id does not exist");
288         $newpatron->{category_id} = $patron_2->categorycode;
289
290         # Create a library just to make sure its ID doesn't exist on the DB
291         my $library_to_delete = $builder->build_object({ class => 'Koha::Libraries' });
292         my $deleted_library_id = $library_to_delete->id;
293         # Delete library
294         $library_to_delete->delete;
295
296         $newpatron->{library_id} = $deleted_library_id;
297         $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/" . $patron_2->id => json => $newpatron );
298         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
299         warning_like {
300             $t->request_ok($tx)
301               ->status_is(400)
302               ->json_is('/error' => "Given library_id does not exist"); }
303             qr/^DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails/;
304         $newpatron->{library_id} = $patron_2->branchcode;
305
306         $newpatron->{falseproperty} = "Non existent property";
307         $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/" . $patron_2->id => json => $newpatron );
308         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
309         $t->request_ok($tx)
310           ->status_is(400)
311           ->json_is('/errors/0/message' =>
312                     'Properties not allowed: falseproperty.');
313         delete $newpatron->{falseproperty};
314
315         # Set both cardnumber and userid to already existing values
316         $newpatron->{cardnumber} = $patron_1->cardnumber;
317         $newpatron->{userid}     = $patron_1->userid;
318
319         $tx = $t->ua->build_tx( PUT => "/api/v1/patrons/" . $patron_2->id => json => $newpatron );
320         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
321         warning_like {
322             $t->request_ok($tx)
323               ->status_is(409)
324               ->json_has( '/error' => "Fails when trying to update to an existing cardnumber or userid")
325               ->json_is(  '/conflict', 'cardnumber' ); }
326             qr/^DBD::mysql::st execute failed: Duplicate entry '(.*?)' for key 'cardnumber'/;
327
328         $newpatron->{ cardnumber } = $patron_id_1.$patron_id_2;
329         $newpatron->{ userid }     = "user".$patron_id_1.$patron_id_2;
330         $newpatron->{ surname }    = "user".$patron_id_1.$patron_id_2;
331
332         $tx = $t->ua->build_tx(PUT => "/api/v1/patrons/" . $patron_2->id => json => $newpatron);
333         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
334         $t->request_ok($tx)
335           ->status_is(200, 'Patron updated successfully')
336           ->json_has($newpatron);
337         is(Koha::Patrons->find( $patron_2->id )->cardnumber,
338            $newpatron->{ cardnumber }, 'Patron is really updated!');
339
340         $schema->storage->txn_rollback;
341     };
342 };
343
344 subtest 'delete() tests' => sub {
345     plan tests => 2;
346
347     $schema->storage->txn_begin;
348     unauthorized_access_tests('DELETE', 123, undef);
349     $schema->storage->txn_rollback;
350
351     subtest 'librarian access test' => sub {
352         plan tests => 4;
353
354         $schema->storage->txn_begin;
355
356         my ( undef, $session_id ) = create_user_and_session({ authorized => 1 });
357         my ( $patron_id, undef )  = create_user_and_session({ authorized => 0 });
358
359         my $tx = $t->ua->build_tx(DELETE => "/api/v1/patrons/-1");
360         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
361         $t->request_ok($tx)
362           ->status_is(404, 'Patron not found');
363
364         $tx = $t->ua->build_tx(DELETE => "/api/v1/patrons/$patron_id");
365         $tx->req->cookies({ name => 'CGISESSID', value => $session_id });
366         $t->request_ok($tx)
367           ->status_is(200, 'Patron deleted successfully');
368
369         $schema->storage->txn_rollback;
370     };
371 };
372
373 # Centralized tests for 401s and 403s assuming the endpoint requires
374 # borrowers flag for access
375 sub unauthorized_access_tests {
376     my ($verb, $patron_id, $json) = @_;
377
378     my $endpoint = '/api/v1/patrons';
379     $endpoint .= ($patron_id) ? "/$patron_id" : '';
380
381     subtest 'unauthorized access tests' => sub {
382         plan tests => 5;
383
384         my $tx = $t->ua->build_tx($verb => $endpoint => json => $json);
385         $t->request_ok($tx)
386           ->status_is(401);
387
388         my ($borrowernumber, $session_id) = create_user_and_session({
389             authorized => 0 });
390
391         $tx = $t->ua->build_tx($verb => $endpoint => json => $json);
392         $tx->req->cookies({name => 'CGISESSID', value => $session_id});
393         $t->request_ok($tx)
394           ->status_is(403)
395           ->json_has('/required_permissions');
396     };
397 }
398
399 sub create_user_and_session {
400
401     my $args  = shift;
402     my $flags = ( $args->{authorized} ) ? 16 : 0;
403
404     my $user = $builder->build(
405         {
406             source => 'Borrower',
407             value  => {
408                 flags => $flags,
409                 gonenoaddress => 0,
410                 lost => 0,
411                 email => 'nobody@example.com',
412                 emailpro => 'nobody@example.com',
413                 B_email => 'nobody@example.com'
414             }
415         }
416     );
417
418     # Create a session for the authorized user
419     my $session = C4::Auth::get_session('');
420     $session->param( 'number',   $user->{borrowernumber} );
421     $session->param( 'id',       $user->{userid} );
422     $session->param( 'ip',       '127.0.0.1' );
423     $session->param( 'lasttime', time() );
424     $session->flush;
425
426     return ( $user->{borrowernumber}, $session->id );
427 }