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