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