Bug 20624: Make /api/v1/oauth/token respect RESTOAuth2ClientCredentials
[koha.git] / Koha / REST / V1 / OAuth.pm
1 package Koha::REST::V1::OAuth;
2
3 use Modern::Perl;
4
5 use Mojo::Base 'Mojolicious::Controller';
6
7 use Net::OAuth2::AuthorizationServer;
8 use Koha::OAuth;
9
10 use C4::Context;
11
12 sub token {
13     my $c = shift->openapi->valid_input or return;
14
15     my $grant_type = $c->validation->param('grant_type');
16     unless ( $grant_type eq 'client_credentials' and C4::Context->preference('RESTOAuth2ClientCredentials') ) {
17         return $c->render(status => 400, openapi => {error => 'Unimplemented grant type'});
18     }
19
20     my $client_id = $c->validation->param('client_id');
21     my $client_secret = $c->validation->param('client_secret');
22
23     my $cb = "${grant_type}_grant";
24     my $server = Net::OAuth2::AuthorizationServer->new;
25     my $grant = $server->$cb(Koha::OAuth::config);
26
27     # verify a client against known clients
28     my ( $is_valid, $error ) = $grant->verify_client(
29         client_id     => $client_id,
30         client_secret => $client_secret,
31     );
32
33     unless ($is_valid) {
34         return $c->render(status => 403, openapi => {error => $error});
35     }
36
37     # generate a token
38     my $token = $grant->token(
39         client_id => $client_id,
40         type      => 'access',
41     );
42
43     # store access token
44     my $expires_in = 3600;
45     $grant->store_access_token(
46         client_id    => $client_id,
47         access_token => $token,
48         expires_in   => $expires_in,
49     );
50
51     my $response = {
52         access_token => $token,
53         token_type => 'Bearer',
54         expires_in => $expires_in,
55     };
56
57     return $c->render(status => 200, openapi => $response);
58 }
59
60 1;