Bug 19160: CAS Single logout
[koha-equinox.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);
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 # Is there a configuration file for multiple cas servers?
56 sub multipleAuth {
57     return (-e qq($yamlauthfile));
58 }
59
60 # Returns configured CAS servers' list if multiple authentication is enabled
61 sub getMultipleAuth {
62    return $casservers; 
63 }
64
65 # Logout from CAS
66 sub logout_cas {
67     my ($query, $type) = @_;
68     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
69     $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
70     print $query->redirect( $cas->logout_url(url => $uri));
71 }
72
73 # Login to CAS
74 sub login_cas {
75     my ($query, $type) = @_;
76     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
77     print $query->redirect( $cas->login_url($uri));
78 }
79
80 # Returns CAS login URL with callback to the requesting URL
81 sub login_cas_url {
82     my ( $query, $key, $type ) = @_;
83     my ( $cas, $uri ) = _get_cas_and_service( $query, $key, $type );
84     return $cas->login_url($uri);
85 }
86
87 # Checks for password correctness
88 # In our case : is there a ticket, is it valid and does it match one of our users ?
89 sub checkpw_cas {
90     $debug and warn "checkpw_cas";
91     my ($dbh, $ticket, $query, $type) = @_;
92     my $retnumber;
93     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
94
95     # If we got a ticket
96     if ($ticket) {
97         $debug and warn "Got ticket : $ticket";
98
99         # We try to validate it
100         my $val = $cas->service_validate($uri, $ticket );
101
102         # If it's valid
103         if ( $val->is_success() ) {
104
105             my $userid = $val->user();
106             $debug and warn "User CAS authenticated as: $userid";
107
108             # 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
109
110             # Does it match one of our users ?
111             my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
112             $sth->execute($userid);
113             if ( $sth->rows ) {
114                 $retnumber = $sth->fetchrow;
115                 return ( 1, $retnumber, $userid, $ticket );
116             }
117             $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
118             $sth->execute($userid);
119             if ( $sth->rows ) {
120                 $retnumber = $sth->fetchrow;
121                 return ( 1, $retnumber, $userid, $ticket );
122             }
123
124             # If we reach this point, then the user is a valid CAS user, but not a Koha user
125             $debug and warn "User $userid is not a valid Koha user";
126
127         } else {
128             $debug and warn "Problem when validating ticket : $ticket";
129             $debug and warn "Authen::CAS::Client::Response::Error: " . $val->error() if $val->is_error();
130             $debug and warn "Authen::CAS::Client::Response::Failure: " . $val->message() if $val->is_failure();
131             $debug and warn Data::Dumper::Dumper($@) if $val->is_error() or $val->is_failure();
132             return 0;
133         }
134     }
135     return 0;
136 }
137
138 # Proxy CAS auth
139 sub check_api_auth_cas {
140     $debug and warn "check_api_auth_cas";
141     my ($dbh, $PT, $query, $type) = @_;
142     my $retnumber;
143     my ( $cas, $uri ) = _get_cas_and_service($query, undef, $type);
144
145     # If we have a Proxy Ticket
146     if ($PT) {
147         my $r = $cas->proxy_validate( $uri, $PT );
148
149         # If the PT is valid
150         if ( $r->is_success ) {
151
152             # We've got a username !
153             $debug and warn "User authenticated as: ", $r->user, "\n";
154             $debug and warn "Proxied through:\n";
155             $debug and warn "  $_\n" for $r->proxies;
156
157             my $userid = $r->user;
158
159             # 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
160
161             # Does it match one of our users ?
162             my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
163             $sth->execute($userid);
164             if ( $sth->rows ) {
165                 $retnumber = $sth->fetchrow;
166                 return ( 1, $retnumber, $userid, $PT );
167             }
168             $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
169             return $r->user;
170             $sth->execute($userid);
171             if ( $sth->rows ) {
172                 $retnumber = $sth->fetchrow;
173                 return ( 1, $retnumber, $userid, $PT );
174             }
175
176             # If we reach this point, then the user is a valid CAS user, but not a Koha user
177             $debug and warn "User $userid is not a valid Koha user";
178
179         } else {
180             $debug and warn "Proxy Ticket authentication failed";
181             return 0;
182         }
183     }
184     return 0;
185 }
186
187 # Get CAS handler and service URI
188 sub _get_cas_and_service {
189     my $query = shift;
190     my $key   = shift;    # optional
191     my $type  = shift;
192
193     my $uri = _url_with_get_params($query, $type);
194
195     my $casparam = $defaultcasserver;
196     $casparam = $query->param('cas') if defined $query->param('cas');
197     $casparam = $key if defined $key;
198     my $cas = Authen::CAS::Client->new( $casservers->{$casparam} );
199
200     return ( $cas, $uri );
201 }
202
203 # Get the current URL with parameters contained directly into URL (GET params)
204 # This method replaces $query->url() which will give both GET and POST params
205 sub _url_with_get_params {
206     my $query = shift;
207     my $type = shift;
208
209     my $uri_base_part =
210       ( $type eq 'opac' )
211       ? C4::Context->preference('OPACBaseURL')
212       : C4::Context->preference('staffClientBaseURL');
213     $uri_base_part .= get_script_name();
214
215     my $uri_params_part = '';
216     foreach my $param ( $query->url_param() ) {
217         # url_param() always returns parameters that were deleted by delete()
218         # This additional check ensure that parameter was not deleted.
219         my $uriPiece = $query->param($param);
220         if ($uriPiece) {
221             $uri_params_part .= '&' if $uri_params_part;
222             $uri_params_part .= $param . '=';
223             $uri_params_part .= URI::Escape::uri_escape( $uriPiece );
224         }
225     }
226     $uri_base_part .= '?' if $uri_params_part;
227
228     return $uri_base_part . $uri_params_part;
229 }
230
231 1;
232 __END__
233
234 =head1 NAME
235
236 C4::Auth - Authenticates Koha users
237
238 =head1 SYNOPSIS
239
240   use C4::Auth_with_cas;
241
242 =cut
243
244 =head1 SEE ALSO
245
246 CGI(3)
247
248 Authen::CAS::Client
249
250 =cut