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