Bug 33040: Add "Date published (text)" to serials tab on record view (detail.pl)
[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 qw( carp );
28 use List::MoreUtils qw( any );
29
30 use Koha::Logger;
31
32 our (@ISA, @EXPORT_OK);
33 BEGIN {
34     require Exporter;
35     @ISA     = qw(Exporter);
36     @EXPORT_OK =
37       qw(shib_ok logout_shib login_shib_url checkpw_shib get_login_shib);
38 }
39
40 # Check that shib config is not malformed
41 sub shib_ok {
42     my $config = _get_shib_config();
43
44     if ($config) {
45         return 1;
46     }
47
48     return 0;
49 }
50
51 # Logout from Shibboleth
52 sub logout_shib {
53     my ($query) = @_;
54     my $uri = _get_uri();
55     my $return = _get_return($query);
56     print $query->redirect( $uri . "/Shibboleth.sso/Logout?return=$return" );
57     exit;
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       return $ENV{"HTTP_".uc($matchAttribute)} || '';
87     } else {
88       return $ENV{$matchAttribute} || '';
89     }
90 }
91
92 # Checks for password correctness
93 # In our case : does the given attribute match one of our users ?
94 sub checkpw_shib {
95
96     my ( $match ) = @_;
97     my $config = _get_shib_config();
98
99     # Does the given shibboleth attribute value ($match) match a valid koha user ?
100     my $borrowers = Koha::Patrons->search( { $config->{matchpoint} => $match } );
101     if ( $borrowers->count > 1 ){
102         # If we have more than 1 borrower the matchpoint is not unique
103         # we cannot know which patron is the correct one, so we should fail
104         Koha::Logger->get->warn("There are several users with $config->{matchpoint} of $match, matchpoints must be unique");
105         return 0;
106     }
107     my $borrower = $borrowers->next;
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         Koha::Logger->get->info("There are several users with $config->{matchpoint} of $match, matchpoints must be unique");
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
163     my $uri =
164       $interface eq 'intranet'
165       ? C4::Context->preference('staffClientBaseURL')
166       : C4::Context->preference('OPACBaseURL');
167
168     $uri or Koha::Logger->get->warn("Syspref staffClientBaseURL or OPACBaseURL not set!"); # FIXME We should die here
169
170     $uri ||= "";
171
172     if ($uri =~ /(.*):\/\/(.*)/) {
173         my $oldprotocol = $1;
174         if ($oldprotocol ne 'https') {
175             Koha::Logger->get->warn('Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!');
176         }
177         $uri = $2;
178     }
179     my $return = $protocol . $uri;
180     return $return;
181 }
182
183 sub _get_return {
184     my ($query) = @_;
185
186     my $uri_base_part = _get_uri() . get_script_name();
187
188     my $uri_params_part = '';
189     foreach my $param ( sort $query->url_param() ) {
190         # url_param() always returns parameters that were deleted by delete()
191         # This additional check ensure that parameter was not deleted.
192         my $uriPiece = $query->param($param);
193         if ($uriPiece) {
194             $uri_params_part .= '&' if $uri_params_part;
195             $uri_params_part .= $param . '=';
196             $uri_params_part .= $uriPiece;
197         }
198     }
199     $uri_base_part .= '%3F' if $uri_params_part;
200
201     return $uri_base_part . URI::Escape::uri_escape_utf8($uri_params_part);
202 }
203
204 sub _get_shib_config {
205     my $config = C4::Context->config('shibboleth');
206
207     if ( !$config ) {
208         Koha::Logger->get->warn('shibboleth config not defined');
209         return 0;
210     }
211
212     if ( $config->{matchpoint}
213         && defined( $config->{mapping}->{ $config->{matchpoint} }->{is} ) )
214     {
215         my $logger = Koha::Logger->get;
216         $logger->debug("koha borrower field to match: " . $config->{matchpoint});
217         $logger->debug("shibboleth attribute to match: " . $config->{mapping}->{ $config->{matchpoint} }->{is});
218         return $config;
219     }
220     else {
221         if ( !$config->{matchpoint} ) {
222             carp 'shibboleth matchpoint not defined';
223         }
224         else {
225             carp 'shibboleth matchpoint not mapped';
226         }
227         return 0;
228     }
229 }
230
231 1;
232 __END__
233
234 =head1 NAME
235
236 C4::Auth_with_shibboleth
237
238 =head1 SYNOPSIS
239
240 use C4::Auth_with_shibboleth;
241
242 =head1 DESCRIPTION
243
244 This module is specific to Shibboleth authentication in koha and relies heavily upon the native shibboleth service provider package in your operating system.
245
246 =head1 CONFIGURATION
247
248 To use this type of authentication these additional packages are required:
249
250 =over
251
252 =item *
253
254 libapache2-mod-shib2
255
256 =item *
257
258 libshibsp5:amd64
259
260 =item *
261
262 shibboleth-sp2-schemas
263
264 =back
265
266 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.
267
268 But to sum up, to get shibboleth working in koha, as a minimum you will need to:
269
270 =over
271
272 =item 1.
273
274 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)
275
276 =item 2.
277
278 Swap metadata with your Identidy Provider (IdP)
279
280 =item 3.
281
282 Map their attributes to what you want to see in koha
283
284 =item 4.
285
286 Tell apache that we wish to allow koha to authenticate via shibboleth.
287
288 This is as simple as adding the below to your virtualhost config (for CGI running):
289
290  <Location />
291    AuthType shibboleth
292    Require shibboleth
293  </Location>
294
295 Or (for Plack running):
296
297  <Location />
298    AuthType shibboleth
299    Require shibboleth
300    ShibUseEnvironment Off
301    ShibUseHeaders On
302  </Location>
303
304 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.)
305
306 =item 5.
307
308 Configure koha to listen for shibboleth environment variables.
309
310 This is as simple as enabling B<useshibboleth> in koha-conf.xml:
311
312  <useshibboleth>1</useshibboleth>
313
314 =item 6.
315
316 Map shibboleth attributes to koha fields, and configure authentication match point in koha-conf.xml.
317
318  <shibboleth>
319    <matchpoint>userid</matchpoint> <!-- koha borrower field to match upon -->
320    <mapping>
321      <userid is="eduPersonID"></userid> <!-- koha borrower field to shibboleth attribute mapping -->
322    </mapping>
323  </shibboleth>
324
325 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.
326
327 =back
328
329 It should be as simple as that; you should now be able to login via shibboleth in the opac.
330
331 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>
332
333 =head1 FUNCTIONS
334
335 =head2 logout_shib
336
337 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.
338
339   logout_shib($query);
340
341 =head2 login_shib_url
342
343 Given a query, this will return a shibboleth login url with return code to page with given given query.
344
345   my $shibLoginURL = login_shib_url($query);
346
347 =head2 get_login_shib
348
349 Returns the shibboleth login attribute should it be found present in the http session
350
351   my $shib_login = get_login_shib();
352
353 =head2 checkpw_shib
354
355 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.
356
357   my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib( $shib_login );
358
359 =head2 _get_uri
360
361   _get_uri();
362
363 A sugar function to that simply returns the current page URI with appropriate protocol attached
364
365 This routine is NOT exported
366
367 =head2 _get_shib_config
368
369   my $config = _get_shib_config();
370
371 A sugar function that checks for a valid shibboleth configuration, and if found returns a hashref of it's contents
372
373 This routine is NOT exported
374
375 =head2 _autocreate
376
377   my ( $retval, $retcard, $retuserid ) = _autocreate( $config, $match );
378
379 Given a shibboleth attribute reference and a userid this internal routine will add the given user to Koha and return their user credentials.
380
381 This routine is NOT exported
382
383 =head1 SEE ALSO
384
385 =cut