1 package Koha
::REST
::V1
::OAuth
;
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 Module
::Load
::Conditional
;
26 use Mojo
::Base
'Mojolicious::Controller';
30 Koha::REST::V1::OAuth - Controller library for handling OAuth2-related token handling
36 Controller method handling token requests
42 my $c = shift->openapi->valid_input or return;
44 if ( Module
::Load
::Conditional
::can_load
(
45 modules
=> {'Net::OAuth2::AuthorizationServer' => undef} )) {
46 require Net
::OAuth2
::AuthorizationServer
;
49 return $c->render( status
=> 400, openapi
=> { error
=> 'Unimplemented grant type' } );
52 my $grant_type = $c->validation->param('grant_type');
53 unless ( $grant_type eq 'client_credentials' and C4
::Context
->preference('RESTOAuth2ClientCredentials') ) {
54 return $c->render(status
=> 400, openapi
=> {error
=> 'Unimplemented grant type'});
60 my $authorization_header = $c->req->headers->authorization;
62 if ( $authorization_header and $authorization_header =~ /^Basic / ) {
63 my ( $type, $credentials ) = split / /, $authorization_header;
65 unless ($credentials) {
66 Koha
::Exceptions
::Authentication
::Required
->throw( error
=> 'Authentication failure.' );
69 my $decoded_credentials = decode_base64
( $credentials );
70 ( $client_id, $client_secret ) = split( /:/, $decoded_credentials, 2 );
73 $client_id = $c->validation->param('client_id');
74 $client_secret = $c->validation->param('client_secret');
77 my $cb = "${grant_type}_grant";
78 my $server = Net
::OAuth2
::AuthorizationServer
->new;
79 my $grant = $server->$cb(Koha
::OAuth
::config
);
81 # verify a client against known clients
82 my ( $is_valid, $error ) = $grant->verify_client(
83 client_id
=> $client_id,
84 client_secret
=> $client_secret,
88 return $c->render(status
=> 403, openapi
=> {error
=> $error});
92 my $token = $grant->token(
93 client_id
=> $client_id,
98 my $expires_in = 3600;
99 $grant->store_access_token(
100 client_id
=> $client_id,
101 access_token
=> $token,
102 expires_in
=> $expires_in,
106 access_token
=> $token,
107 token_type
=> 'Bearer',
108 expires_in
=> $expires_in,
111 return $c->render(status
=> 200, openapi
=> $response);