Bug 20624: (QA follow-up) Handle missing deps gracefuly
[koha.git] / Koha / REST / V1 / OAuth.pm
1 package Koha::REST::V1::OAuth;
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 Module::Load::Conditional;
21
22 use C4::Context;
23 use Koha::OAuth;
24
25 use Mojo::Base 'Mojolicious::Controller';
26
27 sub token {
28
29     my $c = shift->openapi->valid_input or return;
30
31     if ( Module::Load::Conditional::can_load('Net::OAuth2::AuthorizationServer') ) {
32         require Net::OAuth2::AuthorizationServer;
33     }
34     else {
35         return $c->render( status => 400, openapi => { error => 'Unimplemented grant type' } );
36     }
37
38     my $grant_type = $c->validation->param('grant_type');
39     unless ( $grant_type eq 'client_credentials' and C4::Context->preference('RESTOAuth2ClientCredentials') ) {
40         return $c->render(status => 400, openapi => {error => 'Unimplemented grant type'});
41     }
42
43     my $client_id = $c->validation->param('client_id');
44     my $client_secret = $c->validation->param('client_secret');
45
46     my $cb = "${grant_type}_grant";
47     my $server = Net::OAuth2::AuthorizationServer->new;
48     my $grant = $server->$cb(Koha::OAuth::config);
49
50     # verify a client against known clients
51     my ( $is_valid, $error ) = $grant->verify_client(
52         client_id     => $client_id,
53         client_secret => $client_secret,
54     );
55
56     unless ($is_valid) {
57         return $c->render(status => 403, openapi => {error => $error});
58     }
59
60     # generate a token
61     my $token = $grant->token(
62         client_id => $client_id,
63         type      => 'access',
64     );
65
66     # store access token
67     my $expires_in = 3600;
68     $grant->store_access_token(
69         client_id    => $client_id,
70         access_token => $token,
71         expires_in   => $expires_in,
72     );
73
74     my $response = {
75         access_token => $token,
76         token_type => 'Bearer',
77         expires_in => $expires_in,
78     };
79
80     return $c->render(status => 200, openapi => $response);
81 }
82
83 1;