package Koha::REST::V1::OAuth;
+# This file is part of Koha.
+#
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
+#
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
+
use Modern::Perl;
-use Mojo::Base 'Mojolicious::Controller';
+use Module::Load::Conditional;
-use Net::OAuth2::AuthorizationServer;
+use C4::Context;
use Koha::OAuth;
+use MIME::Base64;
-use C4::Context;
+use Mojo::Base 'Mojolicious::Controller';
+
+=head1 NAME
+
+Koha::REST::V1::OAuth - Controller library for handling OAuth2-related token handling
+
+=head2 Operations
+
+=head3 token
+
+Controller method handling token requests
+
+=cut
sub token {
+
my $c = shift->openapi->valid_input or return;
+ if ( Module::Load::Conditional::can_load(
+ modules => {'Net::OAuth2::AuthorizationServer' => undef} )) {
+ require Net::OAuth2::AuthorizationServer;
+ }
+ else {
+ return $c->render( status => 400, openapi => { error => 'Unimplemented grant type' } );
+ }
+
my $grant_type = $c->validation->param('grant_type');
- unless ($grant_type eq 'client_credentials') {
+ unless ( $grant_type eq 'client_credentials' and C4::Context->preference('RESTOAuth2ClientCredentials') ) {
return $c->render(status => 400, openapi => {error => 'Unimplemented grant type'});
}
- my $client_id = $c->validation->param('client_id');
- my $client_secret = $c->validation->param('client_secret');
+ my $client_id;
+ my $client_secret;
+
+ my $authorization_header = $c->req->headers->authorization;
+
+ if ( $authorization_header and $authorization_header =~ /^Basic / ) {
+ my ( $type, $credentials ) = split / /, $authorization_header;
+
+ unless ($credentials) {
+ Koha::Exceptions::Authentication::Required->throw( error => 'Authentication failure.' );
+ }
+
+ my $decoded_credentials = decode_base64( $credentials );
+ ( $client_id, $client_secret ) = split( /:/, $decoded_credentials, 2 );
+ }
+ else {
+ $client_id = $c->validation->param('client_id');
+ $client_secret = $c->validation->param('client_secret');
+ }
my $cb = "${grant_type}_grant";
my $server = Net::OAuth2::AuthorizationServer->new;
expires_in => $expires_in,
);
- my $at = Koha::OAuthAccessTokens->search({ access_token => $token })->next;
-
my $response = {
access_token => $token,
token_type => 'Bearer',