1 package C4::Auth_with_cas;
3 # Copyright 2009 BibLibre SARL
5 # This file is part of Koha.
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.
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.
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>.
24 use Koha::AuthUtils qw( get_script_name );
25 use Authen::CAS::Client;
31 our (@ISA, @EXPORT_OK);
36 @EXPORT_OK = qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url logout_if_required);
40 my $yamlauthfile = C4::Context->config('intranetdir') . "/C4/Auth_cas_servers.yaml";
43 # If there's a configuration for multiple cas servers, then we get it
45 ($defaultcasserver, $casservers) = YAML::XS::LoadFile($yamlauthfile);
46 $defaultcasserver = $defaultcasserver->{'default'};
48 # Else, we fall back to casServerUrl syspref
49 $defaultcasserver = 'default';
50 $casservers = { 'default' => C4::Context->preference('casServerUrl') };
57 # Is there a configuration file for multiple cas servers?
59 return (-e qq($yamlauthfile));
62 # Returns configured CAS servers' list if multiple authentication is enabled
69 my ( $query, $type ) = @_;
70 my ( $cas, $uri ) = _get_cas_and_service( $query, undef, $type );
72 # We don't want to keep triggering a logout, if we got here,
73 # the borrower is already logged out of Koha
74 $uri =~ s/\?logout\.x=1//;
76 my $logout_url = $cas->logout_url( url => $uri );
77 $logout_url =~ s/url=/service=/
78 if C4::Context->preference('casServerVersion') eq '3';
80 print $query->redirect($logout_url);
86 my ($query, $type) = @_;
87 my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
88 print $query->redirect( $cas->login_url($uri));
91 # Returns CAS login URL with callback to the requesting URL
93 my ( $query, $key, $type ) = @_;
94 my ( $cas, $uri ) = _get_cas_and_service( $query, $key, $type );
95 return $cas->login_url($uri);
98 # Checks for password correctness
99 # In our case : is there a ticket, is it valid and does it match one of our users ?
101 my ($dbh, $ticket, $query, $type) = @_;
103 my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
108 # We try to validate it
109 my $val = $cas->service_validate($uri, $ticket );
112 if ( $val->is_success() ) {
114 my $userid = $val->user();
116 # 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 # Does it match one of our users ?
119 my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
120 $sth->execute($userid);
122 $retnumber = $sth->fetchrow;
123 return ( 1, $retnumber, $userid, $ticket );
125 $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
126 $sth->execute($userid);
128 $retnumber = $sth->fetchrow;
129 return ( 1, $retnumber, $userid, $ticket );
132 # If we reach this point, then the user is a valid CAS user, but not a Koha user
133 Koha::Logger->get->info("User $userid is not a valid Koha user");
136 my $logger = Koha::Logger->get;
137 $logger->debug("Problem when validating ticket : $ticket");
138 $logger->debug("Authen::CAS::Client::Response::Error: " . $val->error()) if $val->is_error();
139 $logger->debug("Authen::CAS::Client::Response::Failure: " . $val->message()) if $val->is_failure();
140 $logger->debug(Data::Dumper::Dumper($@)) if $val->is_error() or $val->is_failure();
148 sub check_api_auth_cas {
149 my ($dbh, $PT, $query, $type) = @_;
151 my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
153 # If we have a Proxy Ticket
155 my $r = $cas->proxy_validate( $uri, $PT );
158 if ( $r->is_success ) {
160 # We've got a username !
161 my $userid = $r->user;
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
165 # Does it match one of our users ?
166 my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
167 $sth->execute($userid);
169 $retnumber = $sth->fetchrow;
170 return ( 1, $retnumber, $userid, $PT );
172 $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
174 $sth->execute($userid);
176 $retnumber = $sth->fetchrow;
177 return ( 1, $retnumber, $userid, $PT );
180 # If we reach this point, then the user is a valid CAS user, but not a Koha user
181 Koha::Logger->get->info("User $userid is not a valid Koha user");
184 Koha::Logger->get->debug("Proxy Ticket authentication failed");
191 # Get CAS handler and service URI
192 sub _get_cas_and_service {
194 my $key = shift; # optional
197 my $uri = _url_with_get_params($query, $type);
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} );
204 return ( $cas, $uri );
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 {
215 ? C4::Context->preference('OPACBaseURL')
216 : C4::Context->preference('staffClientBaseURL');
217 $uri_base_part .= get_script_name();
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);
225 $uri_params_part .= '&' if $uri_params_part;
226 $uri_params_part .= $param . '=';
227 $uri_params_part .= URI::Escape::uri_escape( $uriPiece );
230 $uri_base_part .= '?' if $uri_params_part;
232 return $uri_base_part . $uri_params_part;
235 =head2 logout_if_required
237 If using CAS, this subroutine will trigger single-signout of the CAS server.
241 sub logout_if_required {
243 # Check we havent been hit by a logout call
244 my $xml = $query->param('logoutRequest');
245 return 0 unless $xml;
247 my $dom = XML::LibXML->load_xml(string => $xml);
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');
254 return 0 unless $ticket;
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} );
260 print $query->header;
264 sub delete_cas_session {
267 if ($session->param('cas_ticket') && $session->param('cas_ticket') eq $ticket ) {
278 C4::Auth - Authenticates Koha users
282 use C4::Auth_with_cas;