Line 0
Link Here
|
0 |
- |
1 |
#!/usr/bin/perl |
|
|
2 |
# |
3 |
# This file is part of Koha. |
4 |
# |
5 |
# Koha is free software; you can redistribute it and/or modify it |
6 |
# under the terms of the GNU General Public License as published by |
7 |
# the Free Software Foundation; either version 3 of the License, or |
8 |
# (at your option) any later version. |
9 |
# |
10 |
# Koha is distributed in the hope that it will be useful, but |
11 |
# WITHOUT ANY WARRANTY; without even the implied warranty of |
12 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
13 |
# GNU General Public License for more details. |
14 |
# |
15 |
# You should have received a copy of the GNU General Public License |
16 |
# along with Koha; if not, see <http://www.gnu.org/licenses>. |
17 |
# |
18 |
# |
19 |
# Basic OAuth2/OpenID Connect authentication goes like this |
20 |
# |
21 |
# The first thing that happens when this script is called is |
22 |
# that one gets redirected to an authentication url |
23 |
# |
24 |
# If successful, that then redirects back to this script, setting |
25 |
# a CODE parameter which we use to look up a json authentication |
26 |
# token. This token includes an encrypted json id_token, which we |
27 |
# round-trip back to decrypt. Finally, we can extract |
28 |
# the email address from this. |
29 |
# |
30 |
|
31 |
use Modern::Perl; |
32 |
use CGI qw ( -utf8 escape ); |
33 |
use C4::Auth qw{ checkauth get_session get_template_and_user }; |
34 |
use C4::Context; |
35 |
use C4::Output; |
36 |
use Koha::Patrons; |
37 |
|
38 |
use LWP::UserAgent; |
39 |
use HTTP::Request::Common qw{ POST }; |
40 |
use JSON; |
41 |
use MIME::Base64 qw{ decode_base64url }; |
42 |
use URI; |
43 |
use URI::QueryParam; |
44 |
|
45 |
my $discoveryDocURL = C4::Context->preference('OIDCConfigURL'); |
46 |
my $issuer = ''; |
47 |
my $authendpoint = ''; |
48 |
my $tokenendpoint = ''; |
49 |
my $scope = 'openid email profile'; |
50 |
my $host = C4::Context->preference('OPACBaseURL') // q{}; |
51 |
my $restricttodomain = C4::Context->preference('OIDCDomain') |
52 |
// q{}; |
53 |
|
54 |
# protocol is assumed in OPACBaseURL see bug 5010. |
55 |
my $redirecturl = $host . '/cgi-bin/koha/svc/auth/openidconnect'; |
56 |
my $clientid = C4::Context->preference('OIDCOAuth2ClientID'); |
57 |
my $clientsecret = C4::Context->preference('OIDCOAuth2ClientSecret'); |
58 |
|
59 |
my $ua = LWP::UserAgent->new(); |
60 |
my $response = $ua->get($discoveryDocURL); |
61 |
if ( $response->is_success ) { |
62 |
my $json = decode_json( $response->decoded_content ); |
63 |
if ( exists( $json->{'issuer'} ) ) { |
64 |
$issuer = $json->{'issuer'}; |
65 |
} |
66 |
if ( exists( $json->{'authorization_endpoint'} ) ) { |
67 |
$authendpoint = $json->{'authorization_endpoint'}; |
68 |
} |
69 |
if ( exists( $json->{'token_endpoint'} ) ) { |
70 |
$tokenendpoint = $json->{'token_endpoint'}; |
71 |
} |
72 |
} |
73 |
|
74 |
my $query = CGI->new; |
75 |
|
76 |
sub loginfailed { |
77 |
my $cgi_query = shift; |
78 |
my $reason = shift; |
79 |
$cgi_query->delete('code'); |
80 |
$cgi_query->param( 'OIDCFailed' => $reason ); |
81 |
my ( $template, $borrowernumber, $cookie ) = get_template_and_user( |
82 |
{ |
83 |
template_name => 'opac-user.tt', |
84 |
query => $cgi_query, |
85 |
type => 'opac', |
86 |
} |
87 |
); |
88 |
$template->param( 'invalidOIDCLogin' => $reason ); |
89 |
$template->param( 'loginprompt' => 1 ); |
90 |
output_html_with_http_headers $cgi_query, $cookie, $template->output, undef, { force_no_caching => 1 }; |
91 |
return; |
92 |
} |
93 |
|
94 |
if ( defined $query->param('error') ) { |
95 |
loginfailed( $query, |
96 |
'An authentication error occurred. (Error:' |
97 |
. $query->param('error') |
98 |
. ')' ); |
99 |
} |
100 |
elsif ( defined $query->param('code') ) { |
101 |
my $stateclaim = $query->param('state'); |
102 |
my $session = get_session( $query->cookie('CGISESSID') ); |
103 |
if ( $session->param('openid-state') ne $stateclaim ) { |
104 |
$session->clear( ["openid-state"] ); |
105 |
$session->flush(); |
106 |
loginfailed( $query, |
107 |
'Authentication failed. Your session has an unexpected state.' ); |
108 |
} |
109 |
$session->clear( ["openid-state"] ); |
110 |
$session->flush(); |
111 |
|
112 |
my $code = $query->param('code'); |
113 |
my $ua = LWP::UserAgent->new(); |
114 |
if ( $tokenendpoint eq q{} ) { |
115 |
loginfailed( $query, 'Unable to discover token endpoint.' ); |
116 |
} |
117 |
my $request = POST( |
118 |
$tokenendpoint, |
119 |
[ |
120 |
code => $code, |
121 |
client_id => $clientid, |
122 |
client_secret => $clientsecret, |
123 |
redirect_uri => $redirecturl, |
124 |
grant_type => 'authorization_code', |
125 |
$scope => $scope |
126 |
] |
127 |
); |
128 |
my $response = $ua->request($request)->decoded_content; |
129 |
my $json = decode_json($response); |
130 |
if ( exists( $json->{'id_token'} ) ) { |
131 |
if ( lc( $json->{'token_type'} ) ne 'bearer' ) { |
132 |
loginfailed( $query, |
133 |
'Authentication failed. Incorrect token type.' ); |
134 |
} |
135 |
my $idtoken = $json->{'id_token'}; |
136 |
|
137 |
# need to validate the token here |
138 |
|
139 |
my @segments = split( '\.', $idtoken ); |
140 |
unless ( scalar(@segments) == 3 ) { |
141 |
loginfailed( $query, |
142 |
'Login token broken: either too many or too few segments.' ); |
143 |
} |
144 |
my ( $header, $claims, $validation ) = @segments; |
145 |
$claims = decode_base64url($claims); |
146 |
my $claims_json = decode_json($claims); |
147 |
if ( $issuer eq q{} ) { |
148 |
loginfailed( $query, 'Unable to discover issuer.' ); |
149 |
} |
150 |
if ( ( $claims_json->{'iss'} ne ( 'https://' . $issuer ) ) |
151 |
&& ( $claims_json->{'iss'} ne $issuer ) ) |
152 |
{ |
153 |
loginfailed( $query, |
154 |
"Authentication failed. Issuer of authentication is different from what we expected." |
155 |
); |
156 |
} |
157 |
if ( ref( $claims_json->{'aud'} ) eq 'ARRAY' ) { |
158 |
warn "Audience is an array of size: " |
159 |
. scalar( @$claims_json->{'aud'} ); |
160 |
if ( scalar( @$claims_json->{'aud'} ) > 1 ) |
161 |
{ # We don't want any other audiences |
162 |
loginfailed( $query, |
163 |
"Authentication failed. Unexpected audience provided." ); |
164 |
} |
165 |
} |
166 |
if ( ( $claims_json->{'aud'} ne $clientid ) ) |
167 |
{ |
168 |
loginfailed( $query, |
169 |
"Authentication failed. Unexpected audience." ); |
170 |
} |
171 |
if ( $claims_json->{'exp'} < time() ) { |
172 |
loginfailed( $query, 'Sorry, your authentication has timed out.' ); |
173 |
} |
174 |
|
175 |
if ( exists( $claims_json->{'email'} ) ) { |
176 |
my $email = $claims_json->{'email'}; |
177 |
if ( ( $restricttodomain ne q{} ) |
178 |
&& ( index( $email, $restricttodomain ) < 0 ) ) |
179 |
{ |
180 |
loginfailed( $query, |
181 |
'The email you have used is not valid for this library. Email addresses should conclude with ' |
182 |
. $restricttodomain |
183 |
. ' .' ); |
184 |
} |
185 |
else { |
186 |
my $error_feedback = |
187 |
'The email address you are trying to use is not associated with a borrower at this library.'; |
188 |
my $auto_registration = C4::Context->preference('OIDCAutoRegister') // q{0}; |
189 |
my $borrower = Koha::Patrons->find( { email => $email }, { emailpro => $email } ); |
190 |
if (! $borrower && $auto_registration==1) { |
191 |
my $firstname = $claims_json->{'given_name'} // q{}; |
192 |
my $surname = $claims_json->{'family_name'} // q{}; |
193 |
if ($firstname && $surname) { |
194 |
my $delimiter = $firstname ? q{.} : q{}; |
195 |
my $userid = $firstname . $delimiter . $surname; |
196 |
my $categorycode = C4::Context->preference('OIDCDefaultCategory') // q{}; |
197 |
my $patron_category = Koha::Patron::Categories->find( $categorycode ); |
198 |
my $branchcode = C4::Context->preference('OIDCDefaultBranch') // q{}; |
199 |
my $library = Koha::Libraries->find( $branchcode ); |
200 |
if (defined $patron_category && defined $library) { |
201 |
my $password = undef; |
202 |
# TODO errors handling! |
203 |
my $borrower = Koha::Patron->new({ |
204 |
firstname => $firstname, |
205 |
surname => $surname, |
206 |
email => $email, |
207 |
categorycode => $categorycode, |
208 |
branchcode => $branchcode, |
209 |
userid => $userid, |
210 |
password => $password |
211 |
})->store; |
212 |
} else { |
213 |
$error_feedback = 'The OIDCDefaultBranch or OIDCDefaultCategory system preferences are not configured properly. Please contact the library with this error message.'; |
214 |
} |
215 |
} else { |
216 |
$error_feedback = 'We could not find given name and/or family name.' |
217 |
} |
218 |
} |
219 |
my ( $userid, $cookie, $session_id ) = |
220 |
checkauth( $query, 1, {}, 'opac', $email ); |
221 |
if ($userid) { # A user with this email is registered in koha |
222 |
|
223 |
#handle redirect to main.pl, for private opac |
224 |
my $uri; |
225 |
if (C4::Context->preference('OpacPublic') ) { |
226 |
$uri = '/cgi-bin/koha/opac-user.pl'; |
227 |
} else { |
228 |
$uri = '/cgi-bin/koha/opac-main.pl'; |
229 |
} |
230 |
print $query->redirect( |
231 |
-uri => $uri, |
232 |
-cookie => $cookie |
233 |
); |
234 |
} |
235 |
else { |
236 |
loginfailed( $query, $error_feedback ); |
237 |
} |
238 |
} |
239 |
} |
240 |
else { |
241 |
loginfailed( $query, |
242 |
'Unexpectedly, no email seems to be associated with that acccount.' |
243 |
); |
244 |
} |
245 |
} |
246 |
else { |
247 |
loginfailed( $query, 'Failed to get proper credentials.' ); |
248 |
} |
249 |
} |
250 |
else { |
251 |
my $session = get_session( $query->cookie('CGISESSID') ); |
252 |
my $openidstate = 'auth_'; |
253 |
$openidstate .= sprintf( "%x", rand 16 ) for 1 .. 32; |
254 |
$session->param( 'openid-state', $openidstate ); |
255 |
$session->flush(); |
256 |
|
257 |
my $prompt = $query->param('reauthenticate') // q{}; |
258 |
if ( $authendpoint eq q{} ) { |
259 |
loginfailed( $query, 'Unable to discover authorisation endpoint.' ); |
260 |
} |
261 |
my $authorisationurl = URI->new($authendpoint); |
262 |
$authorisationurl->query_form( |
263 |
response_type => "code", |
264 |
redirect_uri => $redirecturl, |
265 |
client_id => $clientid, |
266 |
scope => $scope, |
267 |
state => $openidstate |
268 |
); |
269 |
if ( $prompt || ( defined $prompt && length $prompt > 0 ) ) { |
270 |
$authorisationurl->query_param_append( prompt => $prompt ); |
271 |
} |
272 |
print $query->redirect($authorisationurl->as_string); |
273 |
} |