Bug 20854: Allow correct redirect on logout for Cas servers 3.0 and superior.
[koha.git] / C4 / Auth_with_cas.pm
1 package C4::Auth_with_cas;
2
3 # Copyright 2009 BibLibre SARL
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 use strict;
21 use warnings;
22
23 use C4::Debug;
24 use C4::Context;
25 use Koha::AuthUtils qw(get_script_name);
26 use Authen::CAS::Client;
27 use CGI qw ( -utf8 );
28 use FindBin;
29 use YAML::XS;
30
31
32 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug);
33
34 BEGIN {
35     require Exporter;
36     $debug = $ENV{DEBUG};
37     @ISA   = qw(Exporter);
38     @EXPORT = qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required);
39 }
40 my $defaultcasserver;
41 my $casservers;
42 my $yamlauthfile = C4::Context->config('intranetdir') . "/C4/Auth_cas_servers.yaml";
43
44
45 # If there's a configuration for multiple cas servers, then we get it
46 if (multipleAuth()) {
47     ($defaultcasserver, $casservers) = YAML::XS::LoadFile($yamlauthfile);
48     $defaultcasserver = $defaultcasserver->{'default'};
49 } else {
50 # Else, we fall back to casServerUrl syspref
51     $defaultcasserver = 'default';
52     $casservers = { 'default' => C4::Context->preference('casServerUrl') };
53 }
54
55 =head1 Subroutines
56
57 =cut
58
59 # Is there a configuration file for multiple cas servers?
60 sub multipleAuth {
61     return (-e qq($yamlauthfile));
62 }
63
64 # Returns configured CAS servers' list if multiple authentication is enabled
65 sub getMultipleAuth {
66    return $casservers; 
67 }
68
69 # Logout from CAS
70 sub logout_cas {
71     my ($query, $type) = @_;
72     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
73     $uri =~ s/\?logout\.x=1//; # We don't want to keep triggering a logout, if we got here, the borrower is already logged out of Koha
74     my $logout_url = $cas->logout_url(url => $uri);
75     $logout_url = _fix_logout_url($logout_url);
76     print $query->redirect( $logout_url );
77 }
78
79 # Login to CAS
80 sub login_cas {
81     my ($query, $type) = @_;
82     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
83     print $query->redirect( $cas->login_url($uri));
84 }
85
86 # Returns CAS login URL with callback to the requesting URL
87 sub login_cas_url {
88     my ( $query, $key, $type ) = @_;
89     my ( $cas, $uri ) = _get_cas_and_service( $query, $key, $type );
90     return $cas->login_url($uri);
91 }
92
93 # Checks for password correctness
94 # In our case : is there a ticket, is it valid and does it match one of our users ?
95 sub checkpw_cas {
96     $debug and warn "checkpw_cas";
97     my ($dbh, $ticket, $query, $type) = @_;
98     my $retnumber;
99     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
100
101     # If we got a ticket
102     if ($ticket) {
103         $debug and warn "Got ticket : $ticket";
104
105         # We try to validate it
106         my $val = $cas->service_validate($uri, $ticket );
107
108         # If it's valid
109         if ( $val->is_success() ) {
110
111             my $userid = $val->user();
112             $debug and warn "User CAS authenticated as: $userid";
113
114             # we should store the CAS ticekt too, we need this for single logout https://apereo.github.io/cas/4.2.x/protocol/CAS-Protocol-Specification.html#233-single-logout
115
116             # Does it match one of our users ?
117             my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
118             $sth->execute($userid);
119             if ( $sth->rows ) {
120                 $retnumber = $sth->fetchrow;
121                 return ( 1, $retnumber, $userid, $ticket );
122             }
123             $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
124             $sth->execute($userid);
125             if ( $sth->rows ) {
126                 $retnumber = $sth->fetchrow;
127                 return ( 1, $retnumber, $userid, $ticket );
128             }
129
130             # If we reach this point, then the user is a valid CAS user, but not a Koha user
131             $debug and warn "User $userid is not a valid Koha user";
132
133         } else {
134             $debug and warn "Problem when validating ticket : $ticket";
135             $debug and warn "Authen::CAS::Client::Response::Error: " . $val->error() if $val->is_error();
136             $debug and warn "Authen::CAS::Client::Response::Failure: " . $val->message() if $val->is_failure();
137             $debug and warn Data::Dumper::Dumper($@) if $val->is_error() or $val->is_failure();
138             return 0;
139         }
140     }
141     return 0;
142 }
143
144 # Proxy CAS auth
145 sub check_api_auth_cas {
146     $debug and warn "check_api_auth_cas";
147     my ($dbh, $PT, $query, $type) = @_;
148     my $retnumber;
149     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
150
151     # If we have a Proxy Ticket
152     if ($PT) {
153         my $r = $cas->proxy_validate( $uri, $PT );
154
155         # If the PT is valid
156         if ( $r->is_success ) {
157
158             # We've got a username !
159             $debug and warn "User authenticated as: ", $r->user, "\n";
160             $debug and warn "Proxied through:\n";
161             $debug and warn "  $_\n" for $r->proxies;
162
163             my $userid = $r->user;
164
165             # we should store the CAS ticket too, we need this for single logout https://apereo.github.io/cas/4.2.x/protocol/CAS-Protocol-Specification.html#233-single-logout
166
167             # Does it match one of our users ?
168             my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
169             $sth->execute($userid);
170             if ( $sth->rows ) {
171                 $retnumber = $sth->fetchrow;
172                 return ( 1, $retnumber, $userid, $PT );
173             }
174             $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
175             return $r->user;
176             $sth->execute($userid);
177             if ( $sth->rows ) {
178                 $retnumber = $sth->fetchrow;
179                 return ( 1, $retnumber, $userid, $PT );
180             }
181
182             # If we reach this point, then the user is a valid CAS user, but not a Koha user
183             $debug and warn "User $userid is not a valid Koha user";
184
185         } else {
186             $debug and warn "Proxy Ticket authentication failed";
187             return 0;
188         }
189     }
190     return 0;
191 }
192
193 # Get CAS handler and service URI
194 sub _get_cas_and_service {
195     my $query = shift;
196     my $key   = shift;    # optional
197     my $type  = shift;
198
199     my $uri = _url_with_get_params($query, $type);
200
201     my $casparam = $defaultcasserver;
202     $casparam = $query->param('cas') if defined $query->param('cas');
203     $casparam = $key if defined $key;
204     my $cas = Authen::CAS::Client->new( $casservers->{$casparam} );
205
206     return ( $cas, $uri );
207 }
208
209 # Fix the logout URL when the cas server is 3.0 or superior
210 sub _fix_logout_url {
211     my $url = shift;
212     if (C4::Context->preference('casServerVersion') eq '3') {
213         $url =~ s/url=/service=/;
214     }
215     return $url;
216 }
217
218 # Get the current URL with parameters contained directly into URL (GET params)
219 # This method replaces $query->url() which will give both GET and POST params
220 sub _url_with_get_params {
221     my $query = shift;
222     my $type = shift;
223
224     my $uri_base_part =
225       ( $type eq 'opac' )
226       ? C4::Context->preference('OPACBaseURL')
227       : C4::Context->preference('staffClientBaseURL');
228     $uri_base_part .= get_script_name();
229
230     my $uri_params_part = '';
231     foreach my $param ( $query->url_param() ) {
232         # url_param() always returns parameters that were deleted by delete()
233         # This additional check ensure that parameter was not deleted.
234         my $uriPiece = $query->param($param);
235         if ($uriPiece) {
236             $uri_params_part .= '&' if $uri_params_part;
237             $uri_params_part .= $param . '=';
238             $uri_params_part .= URI::Escape::uri_escape( $uriPiece );
239         }
240     }
241     $uri_base_part .= '?' if $uri_params_part;
242
243     return $uri_base_part . $uri_params_part;
244 }
245
246 =head2 logout_if_required
247
248     If using CAS, this subroutine will trigger single-signout of the CAS server.
249
250 =cut
251
252 sub logout_if_required {
253     my ( $query ) = @_;
254     # Check we havent been hit by a logout call
255     my $xml = $query->param('logoutRequest');
256     return 0 unless $xml;
257
258     my $dom = XML::LibXML->load_xml(string => $xml);
259     my $ticket;
260     foreach my $node ($dom->findnodes('/samlp:LogoutRequest')){
261         # We got a cas single logout request from a cas server;
262         $ticket = $node->findvalue('./samlp:SessionIndex');
263     }
264
265     return 0 unless $ticket;
266
267     # We've been called as part of the single logout destroy the session associated with the cas ticket
268     my $params = C4::Auth::_get_session_params();
269     my $success = CGI::Session->find( $params->{dsn}, sub {delete_cas_session(@_, $ticket)}, $params->{dsn_args} );
270
271     print $query->header;
272     exit;
273 }
274
275 sub delete_cas_session {
276     my $session = shift;
277     my $ticket = shift;
278     if ($session->param('cas_ticket') && $session->param('cas_ticket') eq $ticket ) {
279         $session->delete;
280         $session->flush;
281     }
282 }
283
284 1;
285 __END__
286
287 =head1 NAME
288
289 C4::Auth - Authenticates Koha users
290
291 =head1 SYNOPSIS
292
293   use C4::Auth_with_cas;
294
295 =cut
296
297 =head1 SEE ALSO
298
299 CGI(3)
300
301 Authen::CAS::Client
302
303 =cut