Bug 11969: Show patrons star rating on their reading history
[koha.git] / opac / svc / overdrive_proxy
1 #!/usr/bin/perl
2
3 # Copyright 2013 ByWater
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 =head1 NAME
21
22 svc/overdrive_proxy: Proxy OAuth'd requests to OverDrive
23
24 =head1 SYNOPSIS
25
26 svc/overdrive_proxy/libraries/9001 -> https://api.overdrive.com/v1/libraries/9001
27
28 =head1 DESCRIPTION
29
30 This service proxies incoming requests to the OverDrive OAuth API, to keep the
31 JS side from having to deal with cross-origin/authentication issues.
32
33 =cut
34
35 use Modern::Perl;
36
37 use CGI qw(-oldstyle_urls -utf8);
38 use JSON;
39
40 use C4::Context;
41 use C4::External::OverDrive;
42 use C4::Output;
43
44 use Koha;
45
46 my $query = new CGI;
47
48 my $token;
49
50 if ( !IsOverDriveEnabled() || !( $token = GetOverDriveToken() ) ) {
51     print $query->header(
52         -status => '400 Bad Request',
53     );
54
55     print to_json({
56         error => 'invalid_client',
57         error_description => 'OverDrive login failed'
58     });
59
60     exit;
61 }
62 my $fixed_query = $query->query_string;
63 $fixed_query =~ tr/;/&/;
64
65 my $request = HTTP::Request::Common::GET( "https://api.overdrive.com/v1" . $query->path_info . '?' . $fixed_query );
66 $request->header( Authorization => $token );
67
68 my $ua = LWP::UserAgent->new( "Koha " . Koha::version() );
69
70 my $response = $ua->request( $request ) ;
71 if ( $response->code eq '500' ) {
72     print $query->header(
73         -status => '500 Internal Server Error'
74     );
75
76     warn "OverDrive request failed: " . $response->message;
77     print to_json({
78         error => 'invalid_client',
79         error_description => 'OverDrive request failed'
80     });
81
82     exit;
83 }
84
85 output_with_http_headers $query, undef, $response->content, 'json', $response->status_line;