Bug 21772: (QA follow-up) Fix setting variables to PROCESS in holds
[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;
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::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     print $query->redirect( $cas->logout_url(url => $uri));
75 }
76
77 # Login to CAS
78 sub login_cas {
79     my ($query, $type) = @_;
80     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
81     print $query->redirect( $cas->login_url($uri));
82 }
83
84 # Returns CAS login URL with callback to the requesting URL
85 sub login_cas_url {
86     my ( $query, $key, $type ) = @_;
87     my ( $cas, $uri ) = _get_cas_and_service( $query, $key, $type );
88     return $cas->login_url($uri);
89 }
90
91 # Checks for password correctness
92 # In our case : is there a ticket, is it valid and does it match one of our users ?
93 sub checkpw_cas {
94     $debug and warn "checkpw_cas";
95     my ($dbh, $ticket, $query, $type) = @_;
96     my $retnumber;
97     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
98
99     # If we got a ticket
100     if ($ticket) {
101         $debug and warn "Got ticket : $ticket";
102
103         # We try to validate it
104         my $val = $cas->service_validate($uri, $ticket );
105
106         # If it's valid
107         if ( $val->is_success() ) {
108
109             my $userid = $val->user();
110             $debug and warn "User CAS authenticated as: $userid";
111
112             # 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
113
114             # Does it match one of our users ?
115             my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
116             $sth->execute($userid);
117             if ( $sth->rows ) {
118                 $retnumber = $sth->fetchrow;
119                 return ( 1, $retnumber, $userid, $ticket );
120             }
121             $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
122             $sth->execute($userid);
123             if ( $sth->rows ) {
124                 $retnumber = $sth->fetchrow;
125                 return ( 1, $retnumber, $userid, $ticket );
126             }
127
128             # If we reach this point, then the user is a valid CAS user, but not a Koha user
129             $debug and warn "User $userid is not a valid Koha user";
130
131         } else {
132             $debug and warn "Problem when validating ticket : $ticket";
133             $debug and warn "Authen::CAS::Client::Response::Error: " . $val->error() if $val->is_error();
134             $debug and warn "Authen::CAS::Client::Response::Failure: " . $val->message() if $val->is_failure();
135             $debug and warn Data::Dumper::Dumper($@) if $val->is_error() or $val->is_failure();
136             return 0;
137         }
138     }
139     return 0;
140 }
141
142 # Proxy CAS auth
143 sub check_api_auth_cas {
144     $debug and warn "check_api_auth_cas";
145     my ($dbh, $PT, $query, $type) = @_;
146     my $retnumber;
147     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
148
149     # If we have a Proxy Ticket
150     if ($PT) {
151         my $r = $cas->proxy_validate( $uri, $PT );
152
153         # If the PT is valid
154         if ( $r->is_success ) {
155
156             # We've got a username !
157             $debug and warn "User authenticated as: ", $r->user, "\n";
158             $debug and warn "Proxied through:\n";
159             $debug and warn "  $_\n" for $r->proxies;
160
161             my $userid = $r->user;
162
163             # 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
164
165             # Does it match one of our users ?
166             my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
167             $sth->execute($userid);
168             if ( $sth->rows ) {
169                 $retnumber = $sth->fetchrow;
170                 return ( 1, $retnumber, $userid, $PT );
171             }
172             $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
173             return $r->user;
174             $sth->execute($userid);
175             if ( $sth->rows ) {
176                 $retnumber = $sth->fetchrow;
177                 return ( 1, $retnumber, $userid, $PT );
178             }
179
180             # If we reach this point, then the user is a valid CAS user, but not a Koha user
181             $debug and warn "User $userid is not a valid Koha user";
182
183         } else {
184             $debug and warn "Proxy Ticket authentication failed";
185             return 0;
186         }
187     }
188     return 0;
189 }
190
191 # Get CAS handler and service URI
192 sub _get_cas_and_service {
193     my $query = shift;
194     my $key   = shift;    # optional
195     my $type  = shift;
196
197     my $uri = _url_with_get_params($query, $type);
198
199     my $casparam = $defaultcasserver;
200     $casparam = $query->param('cas') if defined $query->param('cas');
201     $casparam = $key if defined $key;
202     my $cas = Authen::CAS::Client->new( $casservers->{$casparam} );
203
204     return ( $cas, $uri );
205 }
206
207 # Get the current URL with parameters contained directly into URL (GET params)
208 # This method replaces $query->url() which will give both GET and POST params
209 sub _url_with_get_params {
210     my $query = shift;
211     my $type = shift;
212
213     my $uri_base_part =
214       ( $type eq 'opac' )
215       ? C4::Context->preference('OPACBaseURL')
216       : C4::Context->preference('staffClientBaseURL');
217     $uri_base_part .= get_script_name();
218
219     my $uri_params_part = '';
220     foreach my $param ( $query->url_param() ) {
221         # url_param() always returns parameters that were deleted by delete()
222         # This additional check ensure that parameter was not deleted.
223         my $uriPiece = $query->param($param);
224         if ($uriPiece) {
225             $uri_params_part .= '&' if $uri_params_part;
226             $uri_params_part .= $param . '=';
227             $uri_params_part .= URI::Escape::uri_escape( $uriPiece );
228         }
229     }
230     $uri_base_part .= '?' if $uri_params_part;
231
232     return $uri_base_part . $uri_params_part;
233 }
234
235 =head2 logout_if_required
236
237     If using CAS, this subroutine will trigger single-signout of the CAS server.
238
239 =cut
240
241 sub logout_if_required {
242     my ( $query ) = @_;
243     # Check we havent been hit by a logout call
244     my $xml = $query->param('logoutRequest');
245     return 0 unless $xml;
246
247     my $dom = XML::LibXML->load_xml(string => $xml);
248     my $ticket;
249     foreach my $node ($dom->findnodes('/samlp:LogoutRequest')){
250         # We got a cas single logout request from a cas server;
251         $ticket = $node->findvalue('./samlp:SessionIndex');
252     }
253
254     return 0 unless $ticket;
255
256     # We've been called as part of the single logout destroy the session associated with the cas ticket
257     my $params = C4::Auth::_get_session_params();
258     my $success = CGI::Session->find( $params->{dsn}, sub {delete_cas_session(@_, $ticket)}, $params->{dsn_args} );
259
260     sub delete_cas_session {
261         my $session = shift;
262         my $ticket = shift;
263         if ($session->param('cas_ticket') && $session->param('cas_ticket') eq $ticket ) {
264             $session->delete;
265             $session->flush;
266         }
267     }
268
269     print $query->header;
270     exit;
271 }
272
273 1;
274 __END__
275
276 =head1 NAME
277
278 C4::Auth - Authenticates Koha users
279
280 =head1 SYNOPSIS
281
282   use C4::Auth_with_cas;
283
284 =cut
285
286 =head1 SEE ALSO
287
288 CGI(3)
289
290 Authen::CAS::Client
291
292 =cut