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