Bug 11048: Fix logout redirection for CAS authentication
[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 under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 use warnings;
22
23 use C4::Debug;
24 use C4::Context;
25 use Authen::CAS::Client;
26 use CGI;
27 use FindBin;
28
29
30 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug);
31
32 BEGIN {
33         require Exporter;
34     $VERSION = 3.07.00.049;     # set the version for version checking
35         $debug = $ENV{DEBUG};
36         @ISA    = qw(Exporter);
37         @EXPORT = qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
38 }
39 my $context = C4::Context->new() or die 'C4::Context->new failed';
40 my $defaultcasserver;
41 my $casservers;
42 my $yamlauthfile = "../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(qq($FindBin::Bin/$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($FindBin::Bin/$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) = @_;
68     my ( $cas, $uri ) = _get_cas_and_service($query);
69     print $query->redirect( $cas->logout_url($uri));
70     print $query->redirect( $cas->logout_url(url => $uri));
71 }
72
73 # Login to CAS
74 sub login_cas {
75     my ($query) = @_;
76     my ( $cas, $uri ) = _get_cas_and_service($query);
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 ) = @_;
83     my ( $cas, $uri ) = _get_cas_and_service( $query, $key );
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) = @_;
92     my $retnumber;
93     my ( $cas, $uri ) = _get_cas_and_service($query);
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             # Does it match one of our users ?
109             my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
110             $sth->execute($userid);
111             if ( $sth->rows ) {
112                 $retnumber = $sth->fetchrow;
113                 return ( 1, $retnumber, $userid );
114             }
115             $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
116             $sth->execute($userid);
117             if ( $sth->rows ) {
118                 $retnumber = $sth->fetchrow;
119                 return ( 1, $retnumber, $userid );
120             }
121
122             # If we reach this point, then the user is a valid CAS user, but not a Koha user
123             $debug and warn "User $userid is not a valid Koha user";
124
125         } else {
126             $debug and warn "Problem when validating ticket : $ticket";
127             $debug and warn "Authen::CAS::Client::Response::Error: " . $val->error() if $val->is_error();
128             $debug and warn "Authen::CAS::Client::Response::Failure: " . $val->message() if $val->is_failure();
129             $debug and warn Data::Dumper::Dumper($@) if $val->is_error() or $val->is_failure();
130             return 0;
131         }
132     }
133     return 0;
134 }
135
136 # Proxy CAS auth
137 sub check_api_auth_cas {
138     $debug and warn "check_api_auth_cas";
139     my ($dbh, $PT, $query) = @_;
140     my $retnumber;
141     my ( $cas, $uri ) = _get_cas_and_service($query);
142
143     # If we have a Proxy Ticket
144     if ($PT) {
145         my $r = $cas->proxy_validate( $uri, $PT );
146
147         # If the PT is valid
148         if ( $r->is_success ) {
149
150             # We've got a username !
151             $debug and warn "User authenticated as: ", $r->user, "\n";
152             $debug and warn "Proxied through:\n";
153             $debug and warn "  $_\n" for $r->proxies;
154
155             my $userid = $r->user;
156
157             # Does it match one of our users ?
158             my $sth = $dbh->prepare("select cardnumber from borrowers where userid=?");
159             $sth->execute($userid);
160             if ( $sth->rows ) {
161                 $retnumber = $sth->fetchrow;
162                 return ( 1, $retnumber, $userid );
163             }
164             $sth = $dbh->prepare("select userid from borrowers where cardnumber=?");
165             return $r->user;
166             $sth->execute($userid);
167             if ( $sth->rows ) {
168                 $retnumber = $sth->fetchrow;
169                 return ( 1, $retnumber, $userid );
170             }
171
172             # If we reach this point, then the user is a valid CAS user, but not a Koha user
173             $debug and warn "User $userid is not a valid Koha user";
174
175         } else {
176             $debug and warn "Proxy Ticket authentication failed";
177             return 0;
178         }
179     }
180     return 0;
181 }
182
183 # Get CAS handler and service URI
184 sub _get_cas_and_service {
185     my $query = shift;
186     my $key   = shift;    # optional
187
188     my $uri = _url_with_get_params($query);
189
190     my $casparam = $defaultcasserver;
191     $casparam = $query->param('cas') if defined $query->param('cas');
192     $casparam = $key if defined $key;
193     my $cas = Authen::CAS::Client->new( $casservers->{$casparam} );
194
195     return ( $cas, $uri );
196 }
197
198 # Get the current URL with parameters contained directly into URL (GET params)
199 # This method replaces $query->url() which will give both GET and POST params
200 sub _url_with_get_params {
201     my $query = shift;
202
203     my $uri_base_part = C4::Context->preference('OPACBaseURL') . $query->script_name();
204     my $uri_params_part = '';
205     foreach ( $query->url_param() ) {
206         $uri_params_part .= '&' if $uri_params_part;
207         $uri_params_part .= $_ . '=';
208         $uri_params_part .= URI::Escape::uri_escape( $query->url_param($_) );
209     }
210     $uri_base_part .= '?' if $uri_params_part;
211
212     return $uri_base_part . $uri_params_part;
213 }
214
215 1;
216 __END__
217
218 =head1 NAME
219
220 C4::Auth - Authenticates Koha users
221
222 =head1 SYNOPSIS
223
224   use C4::Auth_with_cas;
225
226 =cut
227
228 =head1 SEE ALSO
229
230 CGI(3)
231
232 Authen::CAS::Client
233
234 =cut