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