|
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 |
|
| 43 |
my $discoveryDocURL = C4::Context->preference('OpenIDConfigURL'); |
| 44 |
my $issuer = ''; |
| 45 |
my $authendpoint = ''; |
| 46 |
my $tokenendpoint = ''; |
| 47 |
my $scope = 'openid email profile'; |
| 48 |
my $host = C4::Context->preference('OPACBaseURL') // q{}; |
| 49 |
my $restricttodomain = C4::Context->preference('OpenIDConnectDomain') |
| 50 |
// q{}; |
| 51 |
|
| 52 |
# protocol is assumed in OPACBaseURL see bug 5010. |
| 53 |
my $redirecturl = $host . '/cgi-bin/koha/svc/auth/openidconnect'; |
| 54 |
my $clientid = C4::Context->preference('OpenIDOAuth2ClientID'); |
| 55 |
my $clientsecret = C4::Context->preference('OpenIDOAuth2ClientSecret'); |
| 56 |
|
| 57 |
my $ua = LWP::UserAgent->new(); |
| 58 |
my $response = $ua->get($discoveryDocURL); |
| 59 |
if ( $response->is_success ) { |
| 60 |
my $json = decode_json( $response->decoded_content ); |
| 61 |
if ( exists( $json->{'issuer'} ) ) { |
| 62 |
$issuer = $json->{'issuer'}; |
| 63 |
} |
| 64 |
if ( exists( $json->{'authorization_endpoint'} ) ) { |
| 65 |
$authendpoint = $json->{'authorization_endpoint'}; |
| 66 |
} |
| 67 |
if ( exists( $json->{'token_endpoint'} ) ) { |
| 68 |
$tokenendpoint = $json->{'token_endpoint'}; |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
my $query = CGI->new; |
| 73 |
|
| 74 |
sub loginfailed { |
| 75 |
my $cgi_query = shift; |
| 76 |
my $reason = shift; |
| 77 |
$cgi_query->delete('code'); |
| 78 |
$cgi_query->param( 'OpenIDConnectFailed' => $reason ); |
| 79 |
my ( $template, $borrowernumber, $cookie ) = get_template_and_user( |
| 80 |
{ |
| 81 |
template_name => 'opac-user.tt', |
| 82 |
query => $cgi_query, |
| 83 |
type => 'opac', |
| 84 |
} |
| 85 |
); |
| 86 |
$template->param( 'invalidOpenIDConnectLogin' => $reason ); |
| 87 |
$template->param( 'loginprompt' => 1 ); |
| 88 |
output_html_with_http_headers $cgi_query, $cookie, $template->output, undef, { force_no_caching => 1 }; |
| 89 |
return; |
| 90 |
} |
| 91 |
|
| 92 |
if ( defined $query->param('error') ) { |
| 93 |
loginfailed( $query, |
| 94 |
'An authentication error occurred. (Error:' |
| 95 |
. $query->param('error') |
| 96 |
. ')' ); |
| 97 |
} |
| 98 |
elsif ( defined $query->param('code') ) { |
| 99 |
my $stateclaim = $query->param('state'); |
| 100 |
my $session = get_session( $query->cookie('CGISESSID') ); |
| 101 |
if ( $session->param('openid-state') ne $stateclaim ) { |
| 102 |
$session->clear( ["openid-state"] ); |
| 103 |
$session->flush(); |
| 104 |
loginfailed( $query, |
| 105 |
'Authentication failed. Your session has an unexpected state.' ); |
| 106 |
} |
| 107 |
$session->clear( ["openid-state"] ); |
| 108 |
$session->flush(); |
| 109 |
|
| 110 |
my $code = $query->param('code'); |
| 111 |
my $ua = LWP::UserAgent->new(); |
| 112 |
if ( $tokenendpoint eq q{} ) { |
| 113 |
loginfailed( $query, 'Unable to discover token endpoint.' ); |
| 114 |
} |
| 115 |
my $request = POST( |
| 116 |
$tokenendpoint, |
| 117 |
[ |
| 118 |
code => $code, |
| 119 |
client_id => $clientid, |
| 120 |
client_secret => $clientsecret, |
| 121 |
redirect_uri => $redirecturl, |
| 122 |
grant_type => 'authorization_code', |
| 123 |
$scope => $scope |
| 124 |
] |
| 125 |
); |
| 126 |
my $response = $ua->request($request)->decoded_content; |
| 127 |
my $json = decode_json($response); |
| 128 |
if ( exists( $json->{'id_token'} ) ) { |
| 129 |
if ( lc( $json->{'token_type'} ) ne 'bearer' ) { |
| 130 |
loginfailed( $query, |
| 131 |
'Authentication failed. Incorrect token type.' ); |
| 132 |
} |
| 133 |
my $idtoken = $json->{'id_token'}; |
| 134 |
|
| 135 |
# need to validate the token here |
| 136 |
|
| 137 |
my @segments = split( '\.', $idtoken ); |
| 138 |
unless ( scalar(@segments) == 3 ) { |
| 139 |
loginfailed( $query, |
| 140 |
'Login token broken: either too many or too few segments.' ); |
| 141 |
} |
| 142 |
my ( $header, $claims, $validation ) = @segments; |
| 143 |
$claims = decode_base64url($claims); |
| 144 |
my $claims_json = decode_json($claims); |
| 145 |
if ( $issuer eq q{} ) { |
| 146 |
loginfailed( $query, 'Unable to discover issuer.' ); |
| 147 |
} |
| 148 |
if ( ( $claims_json->{'iss'} ne ( 'https://' . $issuer ) ) |
| 149 |
&& ( $claims_json->{'iss'} ne $issuer ) ) |
| 150 |
{ |
| 151 |
loginfailed( $query, |
| 152 |
"Authentication failed. Issuer of authentication is different from what we expected." |
| 153 |
); |
| 154 |
} |
| 155 |
if ( ref( $claims_json->{'aud'} ) eq 'ARRAY' ) { |
| 156 |
warn "Audience is an array of size: " |
| 157 |
. scalar( @$claims_json->{'aud'} ); |
| 158 |
if ( scalar( @$claims_json->{'aud'} ) > 1 ) |
| 159 |
{ # We don't want any other audiences |
| 160 |
loginfailed( $query, |
| 161 |
"Authentication failed. Unexpected audience provided." ); |
| 162 |
} |
| 163 |
} |
| 164 |
if ( ( $claims_json->{'aud'} ne $clientid ) ) |
| 165 |
{ |
| 166 |
loginfailed( $query, |
| 167 |
"Authentication failed. Unexpected audience." ); |
| 168 |
} |
| 169 |
if ( $claims_json->{'exp'} < time() ) { |
| 170 |
loginfailed( $query, 'Sorry, your authentication has timed out.' ); |
| 171 |
} |
| 172 |
|
| 173 |
if ( exists( $claims_json->{'email'} ) ) { |
| 174 |
my $email = $claims_json->{'email'}; |
| 175 |
if ( ( $restricttodomain ne q{} ) |
| 176 |
&& ( index( $email, $restricttodomain ) < 0 ) ) |
| 177 |
{ |
| 178 |
loginfailed( $query, |
| 179 |
'The email you have used is not valid for this library. Email addresses should conclude with ' |
| 180 |
. $restricttodomain |
| 181 |
. ' .' ); |
| 182 |
} |
| 183 |
else { |
| 184 |
my $error_feedback = |
| 185 |
'The email address you are trying to use is not associated with a borrower at this library.'; |
| 186 |
my $auto_registration = C4::Context->preference('OpenIDConnectAutoRegister') // q{0}; |
| 187 |
my $borrower = Koha::Patrons->find( { email => $email } ); |
| 188 |
if (! $borrower && $auto_registration==1) { |
| 189 |
my $firstname = $claims_json->{'given_name'} // q{}; |
| 190 |
my $surname = $claims_json->{'family_name'} // q{}; |
| 191 |
my $delimiter = $firstname ? q{.} : q{}; |
| 192 |
my $userid = $firstname . $delimiter . $surname; |
| 193 |
my $categorycode = C4::Context->preference('OpenIDConnectDefaultCategory') // q{}; |
| 194 |
my $patron_category = Koha::Patron::Categories->find( $categorycode ); |
| 195 |
my $branchcode = C4::Context->preference('OpenIDConnectDefaultBranch') // q{}; |
| 196 |
my $library = Koha::Libraries->find( $branchcode ); |
| 197 |
if (defined $patron_category && defined $library) { |
| 198 |
my $password = undef; |
| 199 |
# TODO errors handling! |
| 200 |
my $borrower = Koha::Patron->new({ |
| 201 |
firstname => $firstname, |
| 202 |
surname => $surname, |
| 203 |
email => $email, |
| 204 |
categorycode => $categorycode, |
| 205 |
branchcode => $branchcode, |
| 206 |
userid => $userid, |
| 207 |
password => $password |
| 208 |
})->store; |
| 209 |
} else { |
| 210 |
$error_feedback = 'The OpenIDConnectDefaultBranch or OpenIDConnectDefaultCategory system preferences are not configured properly. Please contact the library with this error message.'; |
| 211 |
} |
| 212 |
} |
| 213 |
my ( $userid, $cookie, $session_id ) = |
| 214 |
checkauth( $query, 1, {}, 'opac', $email ); |
| 215 |
if ($userid) { # A user with this email is registered in koha |
| 216 |
|
| 217 |
#handle redirect to main.pl, for private opac |
| 218 |
my $uri; |
| 219 |
if (C4::Context->preference('OpacPublic') ) { |
| 220 |
$uri = '/cgi-bin/koha/opac-user.pl'; |
| 221 |
} else { |
| 222 |
$uri = '/cgi-bin/koha/opac-main.pl'; |
| 223 |
} |
| 224 |
print $query->redirect( |
| 225 |
-uri => $uri, |
| 226 |
-cookie => $cookie |
| 227 |
); |
| 228 |
} |
| 229 |
else { |
| 230 |
loginfailed( $query, $error_feedback ); |
| 231 |
} |
| 232 |
} |
| 233 |
} |
| 234 |
else { |
| 235 |
loginfailed( $query, |
| 236 |
'Unexpectedly, no email seems to be associated with that acccount.' |
| 237 |
); |
| 238 |
} |
| 239 |
} |
| 240 |
else { |
| 241 |
loginfailed( $query, 'Failed to get proper credentials.' ); |
| 242 |
} |
| 243 |
} |
| 244 |
else { |
| 245 |
my $session = get_session( $query->cookie('CGISESSID') ); |
| 246 |
my $openidstate = 'auth_'; |
| 247 |
$openidstate .= sprintf( "%x", rand 16 ) for 1 .. 32; |
| 248 |
$session->param( 'openid-state', $openidstate ); |
| 249 |
$session->flush(); |
| 250 |
|
| 251 |
my $prompt = $query->param('reauthenticate') // q{}; |
| 252 |
if ( $authendpoint eq q{} ) { |
| 253 |
loginfailed( $query, 'Unable to discover authorisation endpoint.' ); |
| 254 |
} |
| 255 |
my $authorisationurl = |
| 256 |
$authendpoint . '?' |
| 257 |
. 'response_type=code&' |
| 258 |
. 'redirect_uri=' |
| 259 |
. escape($redirecturl) . q{&} |
| 260 |
. 'client_id=' |
| 261 |
. escape($clientid) . q{&} |
| 262 |
. 'scope=' |
| 263 |
. escape($scope) . q{&} |
| 264 |
. 'state=' |
| 265 |
. escape($openidstate); |
| 266 |
if ( $prompt || ( defined $prompt && length $prompt > 0 ) ) { |
| 267 |
$authorisationurl .= '&prompt=' . escape($prompt); |
| 268 |
} |
| 269 |
print $query->redirect($authorisationurl); |
| 270 |
} |