Bug 12027: (follow-up) Added missing documentation
[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
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     print $query->redirect( $uri . "/Shibboleth.sso/Logout?return=$uri" );
57 }
58
59 # Returns Shibboleth login URL with callback to the requesting URL
60 sub login_shib_url {
61     my ($query) = @_;
62
63     my $param = _get_uri() . get_script_name();
64     if ( $query->query_string() ) {
65         $param = $param . '%3F' . $query->query_string();
66     }
67     my $uri = _get_uri() . "/Shibboleth.sso/Login?target=$param";
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     $debug and warn $matchAttribute . " value: " . $ENV{$matchAttribute};
86
87     return $ENV{$matchAttribute} || '';
88 }
89
90 # Checks for password correctness
91 # In our case : does the given attribute match one of our users ?
92 sub checkpw_shib {
93     $debug and warn "checkpw_shib";
94
95     my ( $match ) = @_;
96     my $config = _get_shib_config();
97     $debug and warn "User Shibboleth-authenticated as: $match";
98
99     # Does the given shibboleth attribute value ($match) match a valid koha user ?
100     my $borrower =
101       Koha::Database->new()->schema()->resultset('Borrower')
102       ->find( { $config->{matchpoint} => $match } );
103     if ( defined($borrower) ) {
104         return ( 1, $borrower->get_column('cardnumber'), $borrower->get_column('userid') );
105     }
106
107     if ( $config->{'autocreate'} ) {
108         return _autocreate( $config, $match );
109     } else {
110         # If we reach this point, the user is not a valid koha user
111          $debug and warn "User with $config->{matchpoint} of $match is not a valid Koha user";
112         return 0;
113     }
114 }
115
116 sub _autocreate {
117     my ( $config, $match ) = @_;
118
119     my %borrower = ( $config->{matchpoint} => $match );
120
121     while ( my ( $key, $entry ) = each %{$config->{'mapping'}} ) {
122         $borrower{$key} = ( $entry->{'is'} && $ENV{ $entry->{'is'} } ) || $entry->{'content'} || '';
123     }
124
125     my $patron = Koha::Patron->new( \%borrower )->store;
126     C4::Members::Messaging::SetMessagingPreferencesFromDefaults( { borrowernumber => $patron->borrowernumber, categorycode => $patron->categorycode } );
127
128     return ( 1, $patron->cardnumber, $patron->userid );
129 }
130
131 sub _get_uri {
132
133     my $protocol = "https://";
134     my $interface = C4::Context->interface;
135     $debug and warn "shibboleth interface: " . $interface;
136
137     my $return;
138     my $uri;
139     if ( $interface eq 'intranet' ) {
140
141         $uri = C4::Context->preference('staffClientBaseURL') // '';
142         if ($uri eq '') {
143             $debug and warn 'staffClientBaseURL not set!';
144         }
145     } else {
146         $uri = C4::Context->preference('OPACBaseURL') // '';
147         if ($uri eq '') {
148             $debug and warn 'OPACBaseURL not set!';
149         }
150     }
151
152     if ($uri =~ /(.*):\/\/(.*)/) {
153         my $oldprotocol = $1;
154         if ($oldprotocol ne 'https') {
155             $debug
156                 and warn
157                   'Shibboleth requires OPACBaseURL/staffClientBaseURL to use the https protocol!';
158         }
159         $uri = $2;
160     }
161     my $return = $protocol . $uri;
162     return $return;
163 }
164
165 sub _get_shib_config {
166     my $config = C4::Context->config('shibboleth');
167
168     if ( !$config ) {
169         carp 'shibboleth config not defined';
170         return 0;
171     }
172
173     if ( $config->{matchpoint}
174         && defined( $config->{mapping}->{ $config->{matchpoint} }->{is} ) )
175     {
176         if ($debug) {
177             warn "koha borrower field to match: " . $config->{matchpoint};
178             warn "shibboleth attribute to match: "
179               . $config->{mapping}->{ $config->{matchpoint} }->{is};
180         }
181         return $config;
182     }
183     else {
184         if ( !$config->{matchpoint} ) {
185             carp 'shibboleth matchpoint not defined';
186         }
187         else {
188             carp 'shibboleth matchpoint not mapped';
189         }
190         return 0;
191     }
192 }
193
194 1;
195 __END__
196
197 =head1 NAME
198
199 C4::Auth_with_shibboleth
200
201 =head1 SYNOPSIS
202
203 use C4::Auth_with_shibboleth;
204
205 =head1 DESCRIPTION
206
207 This module is specific to Shibboleth authentication in koha and relies heavily upon the native shibboleth service provider package in your operating system.
208
209 =head1 CONFIGURATION
210
211 To use this type of authentication these additional packages are required:
212
213 =over
214
215 =item *
216
217 libapache2-mod-shib2
218
219 =item *
220
221 libshibsp5:amd64
222
223 =item *
224
225 shibboleth-sp2-schemas
226
227 =back
228
229 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.
230
231 But to sum up, to get shibboleth working in koha, as a minimum you will need to:
232
233 =over
234
235 =item 1.
236
237 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)
238
239 =item 2.
240
241 Swap metadata with your Identidy Provider (IdP)
242
243 =item 3.
244
245 Map their attributes to what you want to see in koha
246
247 =item 4.
248
249 Tell apache that we wish to allow koha to authenticate via shibboleth.
250
251 This is as simple as adding the below to your virtualhost config:
252
253  <Location />
254    AuthType shibboleth
255    Require shibboleth
256  </Location>
257
258 =item 5.
259
260 Configure koha to listen for shibboleth environment variables.
261
262 This is as simple as enabling B<useshibboleth> in koha-conf.xml:
263
264  <useshibboleth>1</useshibboleth>
265
266 =item 6.
267
268 Map shibboleth attributes to koha fields, and configure authentication match point in koha-conf.xml.
269
270  <shibboleth>
271    <matchpoint>userid</matchpoint> <!-- koha borrower field to match upon -->
272    <mapping>
273      <userid is="eduPersonID"></userid> <!-- koha borrower field to shibboleth attribute mapping -->
274    </mapping>
275  </shibboleth>
276
277 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.
278
279 =back
280
281 It should be as simple as that; you should now be able to login via shibboleth in the opac.
282
283 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>
284
285 =head1 FUNCTIONS
286
287 =head2 logout_shib
288
289 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.
290
291   logout_shib($query);
292
293 =head2 login_shib_url
294
295 Given a query, this will return a shibboleth login url with return code to page with given given query.
296
297   my $shibLoginURL = login_shib_url($query);
298
299 =head2 get_login_shib
300
301 Returns the shibboleth login attribute should it be found present in the http session
302
303   my $shib_login = get_login_shib();
304
305 =head2 checkpw_shib
306
307 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.
308
309   my ( $retval, $retcard, $retuserid ) = C4::Auth_with_shibboleth::checkpw_shib( $shib_login );
310
311 =head2 _get_uri
312
313   _get_uri();
314
315 A sugar function to that simply returns the current page URI with appropriate protocal attached
316
317 This routine is NOT exported
318
319 =head2 _get_shib_config
320
321   my $config = _get_shib_config();
322
323 A sugar function that checks for a valid sibboleth configuration, and if found returns a hashref of it's contents
324
325 This routine is NOT exported
326
327 =head2 _autocreate
328
329   my ( $retval, $retcard, $retuserid ) = _autocreate( $config, $match );
330
331 Given a shibboleth attribute reference and a userid this internal routine will add the given user to Koha and return their user credentials.
332
333 This routine is NOT exported
334
335 =head1 SEE ALSO
336
337 =cut