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