Bug 10988 - Fix some wording Fix some outdated wording in googleopenidconnect
[koha.git] / opac / svc / auth / googleopenidconnect
1 #!/usr/bin/perl
2 # Copyright vanoudt@gmail.com 2014
3 # Based on persona code from chris@bigballofwax.co.nz 2013
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 #
21 # Basic OAuth2/OpenID Connect authentication for google goes like this
22 #
23 # The first thing that happens when this script is called is
24 # that one gets redirected to an authentication url from google
25 #
26 # If successful, that then redirects back to this script, setting
27 # a CODE parameter which we use to look up a json authentication
28 # token. This token includes an encrypted json id_token, which we
29 # round-trip back to google to decrypt. Finally, we can extract
30 # the email address from this.
31 #
32
33 use Modern::Perl;
34 use CGI qw ( -utf8 escape );
35 use C4::Auth qw{ checkauth get_session get_template_and_user };
36 use C4::Context;
37 use C4::Output;
38
39 use LWP::UserAgent;
40 use HTTP::Request::Common qw{ POST };
41 use JSON;
42 use MIME::Base64 qw{ decode_base64url };
43
44 my $discoveryDocURL =
45   'https://accounts.google.com/.well-known/openid-configuration';
46 my $authendpoint     = '';
47 my $tokenendpoint    = '';
48 my $scope            = 'openid email profile';
49 my $host             = C4::Context->preference('OPACBaseURL') // q{};
50 my $restricttodomain = C4::Context->preference('GoogleOpenIDConnectDomain')
51   // q{};
52
53 # protocol is assumed in OPACBaseURL see bug 5010.
54 my $redirecturl  = $host . '/cgi-bin/koha/svc/auth/googleopenidconnect';
55 my $issuer       = 'accounts.google.com';
56 my $clientid     = C4::Context->preference('GoogleOAuth2ClientID');
57 my $clientsecret = C4::Context->preference('GoogleOAuth2ClientSecret');
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->{'authorization_endpoint'} ) ) {
64         $authendpoint = $json->{'authorization_endpoint'};
65     }
66     if ( exists( $json->{'token_endpoint'} ) ) {
67         $tokenendpoint = $json->{'token_endpoint'};
68     }
69 }
70
71 my $query = CGI->new;
72
73 sub loginfailed {
74     my $cgi_query = shift;
75     my $reason    = shift;
76     $cgi_query->delete('code');
77     $cgi_query->param( 'OpenIDConnectFailed' => $reason );
78     my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
79         {
80             template_name   => 'opac-user.tt',
81             query           => $cgi_query,
82             type            => 'opac',
83             authnotrequired => 0,
84         }
85     );
86     $template->param( 'invalidGoogleOpenIDConnectLogin' => $reason );
87     $template->param( 'loginprompt'                     => 1 );
88     output_html_with_http_headers $cgi_query, $cookie, $template->output;
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('google-openid-state') ne $stateclaim ) {
102         $session->clear( ["google-openid-state"] );
103         $session->flush();
104         loginfailed( $query,
105             'Authentication failed. Your session has an unexpected state.' );
106     }
107     $session->clear( ["google-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 # Normally we'd have to validate the token - but google says not to worry here (Avoids another library!)
136 # See https://developers.google.com/identity/protocols/OpenIDConnect#obtainuserinfo for rationale
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 (   ( $claims_json->{'iss'} ne ( 'https://' . $issuer ) )
146             && ( $claims_json->{'iss'} ne $issuer ) )
147         {
148             loginfailed( $query,
149                 "Authentication failed. Issuer of authentication isn't Google."
150             );
151         }
152         if ( ref( $claims_json->{'aud'} ) eq 'ARRAY' ) {
153             warn "Audience is an array of size: "
154               . scalar( @$claims_json->{'aud'} );
155             if ( scalar( @$claims_json->{'aud'} ) > 1 )
156             {    # We don't want any other audiences
157                 loginfailed( $query,
158                     "Authentication failed. Unexpected audience provided." );
159             }
160         }
161         if (   ( $claims_json->{'aud'} ne $clientid )
162             || ( $claims_json->{'azp'} ne $clientid ) )
163         {
164             loginfailed( $query,
165                 "Authentication failed. Unexpected audience." );
166         }
167         if ( $claims_json->{'exp'} < time() ) {
168             loginfailed( $query, 'Sorry, your authentication has timed out.' );
169         }
170
171         if ( exists( $claims_json->{'email'} ) ) {
172             my $email = $claims_json->{'email'};
173             if (   ( $restricttodomain ne q{} )
174                 && ( index( $email, $restricttodomain ) < 0 ) )
175             {
176                 loginfailed( $query,
177 'The email you have used is not valid for this library. Email addresses should conclude with '
178                       . $restricttodomain
179                       . ' .' );
180             }
181             else {
182                 my ( $userid, $cookie, $session_id ) =
183                   checkauth( $query, 1, {}, 'opac', $email );
184                 if ($userid) {    # A user with this email is registered in koha
185                     print $query->redirect(
186                         -uri    => '/cgi-bin/koha/opac-user.pl',
187                         -cookie => $cookie
188                     );
189                 }
190                 else {
191                     loginfailed( $query,
192 'The email address you are trying to use is not associated with a borrower at this library.'
193                     );
194                 }
195             }
196         }
197         else {
198             loginfailed( $query,
199 'Unexpectedly, no email seems to be associated with that acccount.'
200             );
201         }
202     }
203     else {
204         loginfailed( $query, 'Failed to get proper credentials from Google.' );
205     }
206 }
207 else {
208     my $session     = get_session( $query->cookie('CGISESSID') );
209     my $openidstate = 'auth_';
210     $openidstate .= sprintf( "%x", rand 16 ) for 1 .. 32;
211     $session->param( 'google-openid-state', $openidstate );
212     $session->flush();
213
214     my $prompt = $query->param('reauthenticate') // q{};
215     if ( $authendpoint eq q{} ) {
216         loginfailed( $query, 'Unable to discover authorisation endpoint.' );
217     }
218     my $authorisationurl =
219         $authendpoint . '?'
220       . 'response_type=code&'
221       . 'redirect_uri='
222       . escape($redirecturl) . q{&}
223       . 'client_id='
224       . escape($clientid) . q{&}
225       . 'scope='
226       . escape($scope) . q{&}
227       . 'state='
228       . escape($openidstate);
229     if ( $prompt || ( defined $prompt && length $prompt > 0 ) ) {
230         $authorisationurl .= '&prompt=' . escape($prompt);
231     }
232     print $query->redirect($authorisationurl);
233 }