3 # This file is part of Koha.
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
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.
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.
20 use Test::More tests => 1;
27 use t::lib::TestBuilder;
29 my $t = Test::Mojo->new('Koha::REST::V1');
30 my $schema = Koha::Database->new->schema;
31 my $builder = t::lib::TestBuilder->new();
33 subtest '/oauth/token tests' => sub {
36 $schema->storage->txn_begin;
38 my $patron = $builder->build_object({
39 class => 'Koha::Patrons',
41 surname => 'Test OAuth',
46 # Missing parameter grant_type
47 $t->post_ok('/api/v1/oauth/token')
51 $t->post_ok('/api/v1/oauth/token', form => { grant_type => 'password' })
53 ->json_is({error => 'Unimplemented grant type'});
55 # No client_id/client_secret
56 $t->post_ok('/api/v1/oauth/token', form => { grant_type => 'client_credentials' })
58 ->json_is({error => 'unauthorized_client'});
60 my ($client_id, $client_secret) = ('client1', 'secr3t');
61 t::lib::Mocks::mock_config('api_client', {
62 'client_id' => $client_id,
63 'client_secret' => $client_secret,
64 patron_id => $patron->borrowernumber,
68 grant_type => 'client_credentials',
69 client_id => $client_id,
70 client_secret => $client_secret,
72 $t->post_ok('/api/v1/oauth/token', form => $formData)
74 ->json_is('/expires_in' => 3600)
75 ->json_is('/token_type' => 'Bearer')
76 ->json_has('/access_token');
78 my $access_token = $t->tx->res->json->{access_token};
80 # Without access token, it returns 401
81 $t->get_ok('/api/v1/patrons')->status_is(401);
83 # With access token, but without permissions, it returns 403
84 my $tx = $t->ua->build_tx(GET => '/api/v1/patrons');
85 $tx->req->headers->authorization("Bearer $access_token");
86 $t->request_ok($tx)->status_is(403);
88 # With access token and permissions, it returns 200
89 $patron->flags(2**4)->store;
90 $tx = $t->ua->build_tx(GET => '/api/v1/patrons');
91 $tx->req->headers->authorization("Bearer $access_token");
92 $t->request_ok($tx)->status_is(200);
94 $schema->storage->txn_rollback;