f688e209f512813341adb2ad4ce85de7bfa9f447
[srvgit] / t / db_dependent / api / v1 / auth_authenticate_api_request.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 => 2;
21 use Test::Mojo;
22
23 use Module::Load::Conditional qw(can_load);
24
25 use Koha::ApiKeys;
26 use Koha::Database;
27 use Koha::Patrons;
28
29 use t::lib::Mocks;
30 use t::lib::TestBuilder;
31
32 my $t = Test::Mojo->new('Koha::REST::V1');
33 my $schema  = Koha::Database->new->schema;
34 my $builder = t::lib::TestBuilder->new();
35
36 my $remote_address = '127.0.0.1';
37 my $tx;
38
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' );
43
44 subtest 'token-based tests' => sub {
45
46     if ( can_load( modules => { 'Net::OAuth2::AuthorizationServer' => undef } ) ) {
47         plan tests => 12;
48     }
49     else {
50         plan skip_all => 'Net::OAuth2::AuthorizationServer not available';
51     }
52
53     $schema->storage->txn_begin;
54
55     my $patron = $builder->build_object({
56         class => 'Koha::Patrons',
57         value  => { flags => 1 },
58     });
59
60     t::lib::Mocks::mock_preference('RESTOAuth2ClientCredentials', 1);
61
62     my $api_key = Koha::ApiKey->new({ patron_id => $patron->id, description => 'blah' })->store;
63
64     my $formData = {
65         grant_type    => 'client_credentials',
66         client_id     => $api_key->client_id,
67         client_secret => $api_key->secret
68     };
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');
74
75     my $access_token = $t->tx->res->json->{access_token};
76
77     # With access token and permissions, it returns 200
78     #$patron->flags(2**4)->store;
79
80     my $stash;
81
82     my $tx = $t->ua->build_tx(GET => '/api/v1/acquisitions/orders');
83     $tx->req->headers->authorization("Bearer $access_token");
84     $tx->req->headers->header( 'x-koha-embed' => 'fund' );
85
86     $t->app->hook(after_dispatch => sub { $stash = shift->stash });
87     $t->request_ok($tx)->status_is(200);
88
89     my $user = $stash->{'koha.user'};
90     ok( defined $user, 'The \'koha.user\' object is defined in the stash') and
91     is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and
92     is( $user->borrowernumber, $patron->borrowernumber, 'The stashed user is the right one' );
93
94     my $embed = $stash->{'koha.embed'};
95     ok( defined $embed, 'The embed hashref is generated and stashed' );
96     is_deeply( $embed, { fund => {} }, 'The embed data structure is correct' );
97
98     $schema->storage->txn_rollback;
99 };
100
101 subtest 'cookie-based tests' => sub {
102
103     plan tests => 5;
104
105     $schema->storage->txn_begin;
106
107     my ( $borrowernumber, $session_id ) = create_user_and_session({ authorized => 1 });
108
109     $tx = $t->ua->build_tx( GET => "/api/v1/patrons" );
110     $tx->req->cookies( { name => 'CGISESSID', value => $session_id } );
111     $tx->req->env( { REMOTE_ADDR => $remote_address } );
112
113     my $stash;
114     $t->app->hook(after_dispatch => sub { $stash = shift->stash });
115     $t->request_ok($tx)->status_is(200);
116
117     my $user = $stash->{'koha.user'};
118     ok( defined $user, 'The \'koha.user\' object is defined in the stash') and
119     is( ref($user), 'Koha::Patron', 'Stashed koha.user object type is Koha::Patron') and
120     is( $user->borrowernumber, $borrowernumber, 'The stashed user is the right one' );
121
122     $schema->storage->txn_rollback;
123 };
124
125 sub create_user_and_session {
126
127     my $args  = shift;
128     my $flags = ( $args->{authorized} ) ? 16 : 0;
129
130     my $user = $builder->build(
131         {
132             source => 'Borrower',
133             value  => {
134                 flags => $flags
135             }
136         }
137     );
138
139     # Create a session for the authorized user
140     my $session = C4::Auth::get_session('');
141     $session->param( 'number',   $user->{borrowernumber} );
142     $session->param( 'id',       $user->{userid} );
143     $session->param( 'ip',       '127.0.0.1' );
144     $session->param( 'lasttime', time() );
145     $session->flush;
146
147     return ( $user->{borrowernumber}, $session->id );
148 }