Bug 28572: Remove C4::Debug
[koha.git] / C4 / Auth_with_shibboleth.pm
1 package C4::Auth_with_shibboleth;
2
3 # Copyright 2014 PTFS Europe
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 Modern::Perl;
21
22 use C4::Context;
23 use Koha::AuthUtils qw(get_script_name);
24 use Koha::Database;
25 use Koha::Patrons;
26 use C4::Members::Messaging;
27 use Carp;
28 use CGI;
29 use List::MoreUtils qw(any);
30
31 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug);
32
33 BEGIN {
34     require Exporter;
35     $debug   = $ENV{DEBUG};
36     @ISA     = qw(Exporter);
37     @EXPORT =
38       qw(shib_ok logout_shib login_shib_url checkpw_shib get_login_shib);
39 }
40
41 # Check that shib config is not malformed
42 sub shib_ok {
43     my $config = _get_shib_config();
44
45     if ($config) {
46         return 1;
47     }
48
49     return 0;
50 }
51
52 # Logout from Shibboleth
53 sub logout_shib {
54     my ($query) = @_;
55     my $uri = _get_uri();
56     my $return = _get_return($query);
57     print $query->redirect( $uri . "/Shibboleth.sso/Logout?return=$return" );
58 }
59
60 # Returns Shibboleth login URL with callback to the requesting URL
61 sub login_shib_url {
62     my ($query) = @_;
63
64     my $target = _get_return($query);
65     my $uri = _get_uri() . "/Shibboleth.sso/Login?target=" . $target;
66
67     return $uri;
68 }
69
70 # Returns shibboleth user login
71 sub get_login_shib {
72
73 # In case of a Shibboleth authentication, we expect a shibboleth user attribute
74 # to contain the login match point of the shibboleth-authenticated user. This match
75 # point is configured in koha-conf.xml
76
77 # Shibboleth attributes are mapped into http environmement variables, so we're getting
78 # the match point of the user this way
79
80     # Get shibboleth config
81     my $config = _get_shib_config();
82
83     my $matchAttribute = $config->{mapping}->{ $config->{matchpoint} }->{is};
84
85     if ( any { /(^psgi\.|^plack\.)/i } keys %ENV ) {
86       $debug and warn $matchAttribute . " value: " . $ENV{"HTTP_".uc($matchAttribute)};
87       return $ENV{"HTTP_".uc($matchAttribute)} || '';
88     } else {
89       $debug and warn $matchAttribute . " value: " . $ENV{$matchAttribute};
90       return $ENV{$matchAttribute} || '';
91     }
92 }
93
94 # Checks for password correctness
95 # In our case : does the given attribute match one of our users ?
96 sub checkpw_shib {
97     $debug and warn "checkpw_shib";
98
99     my ( $match ) = @_;
100     my $config = _get_shib_config();
101     $debug and warn "User Shibboleth-authenticated as: $match";
102
103     # Does the given shibboleth attribute value ($match) match a valid koha user ?
104     my $borrowers = Koha::Patrons->search( { $config->{matchpoint} => $match } );
105     if ( $borrowers->count > 1 ){
106         # If we have more than 1 borrower the matchpoint is not unique
107         # we cannot know which patron is the correct one, so we should fail
108          $debug and warn "There are several users with $config->{matchpoint} of $match, matchpoints must be unique";
109         return 0;
110     }
111     my $borrower = $borrowers->next;
112     if ( defined($borrower) ) {
113         if ($config->{'sync'}) {
114             _sync($borrower->borrowernumber, $config, $match);
115         }
116         return ( 1, $borrower->get_column('cardnumber'), $borrower->get_column('userid') );
117     }
118
119     if ( $config->{'autocreate'} ) {
120         return _autocreate( $config, $match );
121     } else {
122         # If we reach this point, the user is not a valid koha user
123          $debug and warn "User with $config->{matchpoint} of $match is not a valid Koha user";
124         return 0;
125     }
126 }
127
128 sub _autocreate {
129     my ( $config, $match ) = @_;
130
131     my %borrower = ( $config->{matchpoint} => $match );
132
133     while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) {
134         if ( any { /(^psgi\.|^plack\.)/i } keys %ENV ) {
135             $borrower{$key} = ( $entry->{'is'} && $ENV{"HTTP_" . uc($entry->{'is'}) } ) || $entry->{'content'} || '';
136         } else {
137             $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || '';
138         }
139     }
140
141     my $patron = Koha::Patron->new( \%borrower )->store;
142     C4::Members::Messaging::SetMessagingPreferencesFromDefaults( { borrowernumber => $patron->borrowernumber, categorycode => $patron->categorycode } );
143
144     return ( 1, $patron->cardnumber, $patron->userid );
145 }
146
147 sub _sync {
148     my ($borrowernumber, $config, $match ) = @_;
149     my %borrower;
150     $borrower{'borrowernumber'} = $borrowernumber;
151     while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) {
152         if ( any { /(^psgi\.|^plack\.)/i } keys %ENV ) {
153             $borrower{$key} = ( $entry->{'is'} && $ENV{"HTTP_" . uc($entry->{'is'}) } ) || $entry->{'content'} || '';
154         } else {
155             $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || '';
156         }
157     }
158     my $patron = Koha::Patrons->find( $borrowernumber );
159     $patron->set(\%borrower)->store;
160 }
161
162 sub _get_uri {
163
164     my $protocol = "https://";
165     my $interface = C4::Context->interface;
166     $debug and warn "shibboleth interface: " . $interface;
167
168     my $uri;
169     if ( $interface eq 'intranet' ) {
170
171         $uri = C4::Context->preference('staffClientBaseURL') // '';
172         if ($uri eq '') {
173             $debug and warn 'staffClientBaseURL not set!';
174         }
175     } else {
176         $uri = C4::Context->preference('OPACBaseURL') // '';
177         if ($uri eq '') {
178             $debug and warn 'OPACBaseURL not set!';
179         }
180     }
181
182     if ($uri =~ /(.*):\/\/(.*)/) {
183         my $oldprotocol = $1;
184         if ($oldprotocol ne 'https') {
185             $debug
186                 and warn
187                   'Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!';
188         }
189         $uri = $2;
190     }
191     my $return = $protocol . $uri;
192     return $return;
193 }
194
195 sub _get_return {
196     my ($query) = @_;
197
198     my $uri_base_part = _get_uri() . get_script_name();
199
200     my $uri_params_part = '';
201     foreach my $param ( sort $query->url_param() ) {
202         # url_param() always returns parameters that were deleted by delete()
203         # This additional check ensure that parameter was not deleted.
204         my $uriPiece = $query->param($param);
205         if ($uriPiece) {
206             $uri_params_part .= '&' if $uri_params_part;
207             $uri_params_part .= $param . '=';
208             $uri_params_part .= $uriPiece;
209         }
210     }
211     $uri_base_part .= '%3F' if $uri_params_part;
212
213     return $uri_base_part . URI::Escape::uri_escape_utf8($uri_params_part);
214 }
215
216 sub _get_shib_config {
217     my $config = C4::Context->config('shibboleth');
218
219     if ( !$config ) {
220         carp 'shibboleth config not defined' if $debug;
221         return 0;
222     }
223
224     if ( $config->{matchpoint}
225         && defined( $config->{mapping}->{ $config->{matchpoint} }->{is} ) )
226     {
227         if ($debug) {
228             warn "koha borrower field to match: " . $config->{matchpoint};
229             warn "shibboleth attribute to match: "
230               . $config->{mapping}->{ $config->{matchpoint} }->{is};
231         }
232         return $config;
233     }
234     else {
235         if ( !$config->{matchpoint} ) {
236             carp 'shibboleth matchpoint not defined';
237         }
238         else {
239             carp 'shibboleth matchpoint not mapped';
240         }
241         return 0;
242     }
243 }
244
245 1;
246 __END__
247
248 =head1 NAME
249
250 C4::Auth_with_shibboleth
251
252 =head1 SYNOPSIS
253
254 use C4::Auth_with_shibboleth;
255
256 =head1 DESCRIPTION
257
258 This module is specific to Shibboleth authentication in koha and relies heavily upon the native shibboleth service provider package in your operating system.
259
260 =head1 CONFIGURATION
261
262 To use this type of authentication these additional packages are required:
263
264 =over
265
266 =item *
267
268 libapache2-mod-shib2
269
270 =item *
271
272 libshibsp5:amd64
273
274 =item *
275
276 shibboleth-sp2-schemas
277
278 =back
279
280 We let the native shibboleth service provider packages handle all the complexities of shibboleth negotiation for us, and configuring this is beyond the scope of this documentation.
281
282 But to sum up, to get shibboleth working in koha, as a minimum you will need to:
283
284 =over
285
286 =item 1.
287
288 Create some metadata for your koha instance (if you're in a single instance setup then the default metadata available at https://youraddress.com/Shibboleth.sso/Metadata should be adequate)
289
290 =item 2.
291
292 Swap metadata with your Identidy Provider (IdP)
293
294 =item 3.
295
296 Map their attributes to what you want to see in koha
297
298 =item 4.
299
300 Tell apache that we wish to allow koha to authenticate via shibboleth.
301
302 This is as simple as adding the below to your virtualhost config (for CGI running):
303
304  <Location />
305    AuthType shibboleth
306    Require shibboleth
307  </Location>
308
309 Or (for Plack running):
310
311  <Location />
312    AuthType shibboleth
313    Require shibboleth
314    ShibUseEnvironment Off
315    ShibUseHeaders On
316  </Location>
317
318 IMPORTANT: Please note, if you are running in the plack configuration you should consult https://wiki.shibboleth.net/confluence/display/SHIB2/NativeSPSpoofChecking for security advice regarding header spoof checking settings. (See also bug 17776 on Bugzilla about enabling ShibUseHeaders.)
319
320 =item 5.
321
322 Configure koha to listen for shibboleth environment variables.
323
324 This is as simple as enabling B<useshibboleth> in koha-conf.xml:
325
326  <useshibboleth>1</useshibboleth>
327
328 =item 6.
329
330 Map shibboleth attributes to koha fields, and configure authentication match point in koha-conf.xml.
331
332  <shibboleth>
333    <matchpoint>userid</matchpoint> <!-- koha borrower field to match upon -->
334    <mapping>
335      <userid is="eduPersonID"></userid> <!-- koha borrower field to shibboleth attribute mapping -->
336    </mapping>
337  </shibboleth>
338
339 Note: The minimum you need here is a <matchpoint> block, containing a valid column name from the koha borrowers table, and a <mapping> block containing a relation between the chosen matchpoint and the shibboleth attribute name.
340
341 =back
342
343 It should be as simple as that; you should now be able to login via shibboleth in the opac.
344
345 If you need more help configuring your B<S>ervice B<P>rovider to authenticate against a chosen B<Id>entity B<P>rovider then it might be worth taking a look at the community wiki L<page|http://wiki.koha-community.org/wiki/Shibboleth_Configuration>
346
347 =head1 FUNCTIONS
348
349 =head2 logout_shib
350
351 Sends a logout signal to the native shibboleth service provider and then logs out of koha.  Depending upon the native service provider configuration and identity provider capabilities this may or may not perform a single sign out action.
352
353   logout_shib($query);
354
355 =head2 login_shib_url
356
357 Given a query, this will return a shibboleth login url with return code to page with given given query.
358
359   my $shibLoginURL = login_shib_url($query);
360
361 =head2 get_login_shib
362
363 Returns the shibboleth login attribute should it be found present in the http session
364
365   my $shib_login = get_login_shib();
366
367 =head2 checkpw_shib
368
369 Given a shib_login attribute, this routine checks for a matching local user and if found returns true, their cardnumber and their userid.  If a match is not found, then this returns false.
370
371   my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib( $shib_login );
372
373 =head2 _get_uri
374
375   _get_uri();
376
377 A sugar function to that simply returns the current page URI with appropriate protocol attached
378
379 This routine is NOT exported
380
381 =head2 _get_shib_config
382
383   my $config = _get_shib_config();
384
385 A sugar function that checks for a valid shibboleth configuration, and if found returns a hashref of it's contents
386
387 This routine is NOT exported
388
389 =head2 _autocreate
390
391   my ( $retval, $retcard, $retuserid ) = _autocreate( $config, $match );
392
393 Given a shibboleth attribute reference and a userid this internal routine will add the given user to Koha and return their user credentials.
394
395 This routine is NOT exported
396
397 =head1 SEE ALSO
398
399 =cut