Bug 26922: Regression tests
[koha.git] / t / db_dependent / api / v1 / auth_authenticate_api_request.t
blob5bb68d257003d9c485fd5133e2d137d3a8a626a1
1 #!/usr/bin/env perl
3 # This file is part of Koha.
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.
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.
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>.
18 use Modern::Perl;
20 use Test::More tests => 3;
21 use Test::Mojo;
23 use Module::Load::Conditional qw(can_load);
25 use Koha::ApiKeys;
26 use Koha::Database;
27 use Koha::Patrons;
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
32 my $t = Test::Mojo->new('Koha::REST::V1');
33 my $schema = Koha::Database->new->schema;
34 my $builder = t::lib::TestBuilder->new();
36 my $remote_address = '127.0.0.1';
37 my $tx;
39 # FIXME: CGI::Session::Driver::DBI explicitly sets AutoCommit=1 [1] which breaks the rollback in out tests.
40 # Until we change into some other library, set SessionStorage to 'tmp'
41 # [1] https://metacpan.org/source/CGI::Session::Driver::DBI#L28
42 t::lib::Mocks::mock_preference( 'SessionStorage', 'tmp' );
44 subtest 'token-based tests' => sub {
46 if ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) {
47 plan tests => 14;
49 else {
50 plan skip_all => 'Net::OAuth2::AuthorizationServer not available';
53 $schema->storage->txn_begin;
55 my $patron = $builder->build_object({
56 class => 'Koha::Patrons',
57 value => { flags => 1 },
58 });
60 t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 1);
62 my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store;
64 my $formData = {
65 grant_type => 'client_credentials',
66 client_id => $api_key->client_id,
67 client_secret => $api_key->secret
69 $t->post_ok('/api/v1/oauth/token', form => $formData)
70 ->status_is(200)
71 ->json_is('/expires_in' => 3600)
72 ->json_is('/token_type' => 'Bearer')
73 ->json_has('/access_token');
75 my $access_token = $t->tx->res->json->{access_token};
77 my $stash;
78 my $interface;
79 my $userenv;
81 my $tx = $t->ua->build_tx(GET => '/api/v1/acquisitions/orders');
82 $tx->req->headers->authorization("Bearer $access_token");
83 $tx->req->headers->header( 'x-koha-embed' => 'fund' );
85 $t->app->hook(after_dispatch => sub {
86 $stash = shift->stash;
87 $interface = C4::Context->interface;
88 $userenv = C4::Context->userenv;
89 });
91 # With access token and permissions, it returns 200
92 #$patron->flags(2**4)->store;
93 $t->request_ok($tx)->status_is(200);
95 my $user = $stash->{'koha.user'};
96 ok( defined $user, 'The \'koha.user\' object is defined in the stash') and
97 is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and
98 is( $user->borrowernumber, $patron->borrowernumber, 'The stashed user is the right one' );
99 is( $userenv->{number}, $patron->borrowernumber, 'userenv set correctly' );
100 is( $interface, 'api', "Interface correctly set to \'api\'" );
102 my $embed = $stash->{'koha.embed'};
103 ok( defined $embed, 'The embed hashref is generated and stashed' );
104 is_deeply( $embed, { fund => {} }, 'The embed data structure is correct' );
106 $schema->storage->txn_rollback;
109 subtest 'cookie-based tests' => sub {
111 plan tests => 8;
113 $schema->storage->txn_begin;
115 my ( $borrowernumber, $session_id ) = create_user_and_session({ authorized => 1 });
117 $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
118 $tx->req->cookies( { name => 'CGISESSID', value => $session_id } );
119 $tx->req->env( { REMOTE_ADDR => $remote_address } );
121 my $stash;
122 my $interface;
123 my $userenv;
125 $t->app->hook(after_dispatch => sub {
126 $stash = shift->stash;
127 $interface = C4::Context->interface;
128 $userenv = C4::Context->userenv;
131 $t->request_ok($tx)->status_is(200);
133 my $user = $stash->{'koha.user'};
134 ok( defined $user, 'The \'koha.user\' object is defined in the stash') and
135 is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and
136 is( $user->borrowernumber, $borrowernumber, 'The stashed user is the right one' );
137 is( $userenv->{number}, $borrowernumber, 'userenv set correctly' );
138 is( $interface, 'api', "Interface correctly set to \'api\'" );
140 subtest 'logged-out tests' => sub {
141 plan tests => 3;
143 # Generate an anonymous session
144 my $session = C4::Auth::get_session('');
145 $session->param( 'ip', $remote_address );
146 $session->param( 'lasttime', time() );
147 $session->param( 'sessiontype', 'anon' );
148 $session->flush;
150 my $tx = $t->ua->build_tx( GET => '/api/v1/libraries' );
151 $tx->req->cookies({ name => 'CGISESSID', value => $session->id });
152 $tx->req->env({ REMOTE_ADDR => $remote_address });
154 $t->request_ok($tx)
155 ->status_is( 401, 'Anonymous session on permission protected resource returns 401' )
156 ->json_is( { error => 'Authentication failure.' } );
159 $schema->storage->txn_rollback;
162 subtest 'anonymous requests to public API' => sub {
164 plan tests => 4;
166 $schema->storage->txn_begin;
168 t::lib::Mocks::mock_preference( 'RESTBasicAuth', 1 );
170 my $password = 'AbcdEFG123';
171 my $userid = 'tomasito';
172 # Add a patron
173 my $patron = $builder->build_object({ class => 'Koha::Patrons' });
174 $patron->set_password({ password => $password });
175 # Add a biblio
176 my $biblio_id = $builder->build_sample_biblio()->biblionumber;
178 # Enable the public API
179 t::lib::Mocks::mock_preference( 'RESTPublicAPI', 1 );
180 # Disable anonymous requests on the public namespace
181 t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 0 );
183 $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' })
184 ->status_is( 401, 'Unauthorized anonymous attempt to access a resource' );
186 # Disable anonymous requests on the public namespace
187 t::lib::Mocks::mock_preference( 'RESTPublicAnonymousRequests', 1 );
189 $t->get_ok("/api/v1/public/biblios/" . $biblio_id => { Accept => 'application/marc' })
190 ->status_is( 200, 'Successfull anonymous access to a resource' );
192 $schema->storage->txn_rollback;
195 sub create_user_and_session {
197 my $args = shift;
198 my $flags = ( $args->{authorized} ) ? 16 : 0;
200 my $user = $builder->build(
202 source => 'Borrower',
203 value => {
204 flags => $flags
209 # Create a session for the authorized user
210 my $session = C4::Auth::get_session('');
211 $session->param( 'number', $user->{borrowernumber} );
212 $session->param( 'id', $user->{userid} );
213 $session->param( 'ip', '127.0.0.1' );
214 $session->param( 'lasttime', time() );
215 $session->flush;
217 return ( $user->{borrowernumber}, $session->id );