2 # NOTE: This file uses 8-character tabs; do not change the tab size!
6 # Copyright 2000-2002 Katipo Communications
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License along with
20 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
21 # Suite 330, Boston, MA 02111-1307 USA
24 use Digest::MD5 qw(md5_base64);
28 use C4::Output; # to get the template
29 use C4::Interface::CGI::Output;
30 use C4::Circulation::Circ2; # getpatroninformation
32 # use Net::LDAP qw(:all);
34 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
36 # set the version for version checking
41 C4::Auth - Authenticates Koha users
50 my ($template, $borrowernumber, $cookie)
51 = get_template_and_user({template_name => "opac-main.tmpl",
55 flagsrequired => {borrow => 1},
59 -type => guesstype($template->output),
66 The main function of this module is to provide
67 authentification. However the get_template_and_user function has
68 been provided so that a users login information is passed along
69 automatically. This gets loaded into the template.
82 &get_template_and_user
85 =item get_template_and_user
87 my ($template, $borrowernumber, $cookie)
88 = get_template_and_user({template_name => "opac-main.tmpl",
92 flagsrequired => {borrow => 1},
95 This call passes the C<query>, C<flagsrequired> and C<authnotrequired>
96 to C<&checkauth> (in this module) to perform authentification.
97 See C<&checkauth> for an explanation of these parameters.
99 The C<template_name> is then used to find the correct template for
100 the page. The authenticated users details are loaded onto the
101 template in the HTML::Template LOOP variable C<USER_INFO>. Also the
102 C<sessionID> is passed to the template. This can be used in templates
103 if cookies are disabled. It needs to be put as and input to every
106 More information on the C<gettemplate> sub can be found in the
112 sub get_template_and_user {
114 my $template = gettemplate($in->{'template_name'}, $in->{'type'},$in->{'query'});
115 my ($user, $cookie, $sessionID, $flags)
116 = checkauth($in->{'query'}, $in->{'authnotrequired'}, $in->{'flagsrequired'}, $in->{'type'});
120 $template->param(loggedinusername => $user);
121 $template->param(sessionID => $sessionID);
123 $borrowernumber = getborrowernumber($user);
124 my ($borr, $flags) = getpatroninformation(undef, $borrowernumber);
127 $template->param(USER_INFO => \@bordat,
131 LibraryName => C4::Context->preference("LibraryName"),
133 return ($template, $borrowernumber, $cookie);
139 ($userid, $cookie, $sessionID) = &checkauth($query, $noauth, $flagsrequired, $type);
141 Verifies that the user is authorized to run this script. If
142 the user is authorized, a (userid, cookie, session-id, flags)
143 quadruple is returned. If the user is not authorized but does
144 not have the required privilege (see $flagsrequired below), it
145 displays an error page and exits. Otherwise, it displays the
146 login page and exits.
148 Note that C<&checkauth> will return if and only if the user
149 is authorized, so it should be called early on, before any
150 unfinished operations (e.g., if you've opened a file, then
151 C<&checkauth> won't close it for you).
153 C<$query> is the CGI object for the script calling C<&checkauth>.
155 The C<$noauth> argument is optional. If it is set, then no
156 authorization is required for the script.
158 C<&checkauth> fetches user and session information from C<$query> and
159 ensures that the user is authorized to run scripts that require
162 The C<$flagsrequired> argument specifies the required privileges
163 the user must have if the username and password are correct.
164 It should be specified as a reference-to-hash; keys in the hash
165 should be the "flags" for the user, as specified in the Members
166 intranet module. Any key specified must correspond to a "flag"
167 in the userflags table. E.g., { circulate => 1 } would specify
168 that the user must have the "circulate" privilege in order to
169 proceed. To make sure that access control is correct, the
170 C<$flagsrequired> parameter must be specified correctly.
172 The C<$type> argument specifies whether the template should be
173 retrieved from the opac or intranet directory tree. "opac" is
174 assumed if it is not specified; however, if C<$type> is specified,
175 "intranet" is assumed if it is not "opac".
177 If C<$query> does not have a valid session ID associated with it
178 (i.e., the user has not logged in) or if the session has expired,
179 C<&checkauth> presents the user with a login page (from the point of
180 view of the original script, C<&checkauth> does not return). Once the
181 user has authenticated, C<&checkauth> restarts the original script
182 (this time, C<&checkauth> returns).
184 The login page is provided using a HTML::Template, which is set in the
185 systempreferences table or at the top of this file. The variable C<$type>
186 selects which template to use, either the opac or the intranet
187 authentification template.
189 C<&checkauth> returns a user ID, a cookie, and a session ID. The
190 cookie should be sent back to the browser; it verifies that the user
199 # $authnotrequired will be set for scripts which will run without authentication
200 my $authnotrequired = shift;
201 my $flagsrequired = shift;
203 $type = 'opac' unless $type;
205 my $dbh = C4::Context->dbh;
206 my $timeout = C4::Context->preference('timeout');
207 $timeout = 600 unless $timeout;
210 if ($type eq 'opac') {
211 $template_name = "opac-auth.tmpl";
213 $template_name = "auth.tmpl";
219 my ($userid, $cookie, $sessionID, $flags);
220 my $logout = $query->param('logout.x');
221 if ($userid = $ENV{'REMOTE_USER'}) {
222 # Using Basic Authentication, no cookies required
223 $cookie=$query->cookie(-name => 'sessionID',
227 } elsif ($sessionID=$query->cookie('sessionID')) {
228 my ($ip , $lasttime);
229 ($userid, $ip, $lasttime) = $dbh->selectrow_array(
230 "SELECT userid,ip,lasttime FROM sessions WHERE sessionid=?",
233 # voluntary logout the user
234 $dbh->do("DELETE FROM sessions WHERE sessionID=?", undef, $sessionID);
237 open L, ">>/tmp/sessionlog";
238 my $time=localtime(time());
239 printf L "%20s from %16s logged out at %30s (manually).\n", $userid, $ip, $time;
243 if ($lasttime<time()-$timeout) {
245 $info{'timed_out'} = 1;
246 $dbh->do("DELETE FROM sessions WHERE sessionID=?", undef, $sessionID);
249 open L, ">>/tmp/sessionlog";
250 my $time=localtime(time());
251 printf L "%20s from %16s logged out at %30s (inactivity).\n", $userid, $ip, $time;
253 } elsif ($ip ne $ENV{'REMOTE_ADDR'}) {
254 # Different ip than originally logged in from
255 $info{'oldip'} = $ip;
256 $info{'newip'} = $ENV{'REMOTE_ADDR'};
257 $info{'different_ip'} = 1;
258 $dbh->do("DELETE FROM sessions WHERE sessionID=?", undef, $sessionID);
261 open L, ">>/tmp/sessionlog";
262 my $time=localtime(time());
263 printf L "%20s from logged out at %30s (ip changed from %16s to %16s).\n", $userid, $time, $ip, $info{'newip'};
266 $cookie=$query->cookie(-name => 'sessionID',
267 -value => $sessionID,
269 $dbh->do("UPDATE sessions SET lasttime=? WHERE sessionID=?",
270 undef, (time(), $sessionID));
271 $flags = haspermission($dbh, $userid, $flagsrequired);
275 $info{'nopermission'} = 1;
281 $sessionID=int(rand()*100000).'-'.time();
282 $userid=$query->param('userid');
283 my $password=$query->param('password');
284 my ($return, $cardnumber) = checkpw($dbh,$userid,$password);
286 $dbh->do("DELETE FROM sessions WHERE sessionID=? AND userid=?",
287 undef, ($sessionID, $userid));
288 $dbh->do("INSERT INTO sessions (sessionID, userid, ip,lasttime) VALUES (?, ?, ?, ?)",
289 undef, ($sessionID, $userid, $ENV{'REMOTE_ADDR'}, time()));
290 open L, ">>/tmp/sessionlog";
291 my $time=localtime(time());
292 printf L "%20s from %16s logged in at %30s.\n", $userid, $ENV{'REMOTE_ADDR'}, $time;
294 $cookie=$query->cookie(-name => 'sessionID',
295 -value => $sessionID,
297 if ($flags = haspermission($dbh, $userid, $flagsrequired)) {
300 $info{'nopermission'} = 1;
304 $info{'invalid_username_or_password'} = 1;
308 my $insecure = C4::Context->boolean_preference('insecure');
309 # finished authentification, now respond
310 if ($loggedin || $authnotrequired || (defined($insecure) && $insecure)) {
313 $cookie=$query->cookie(-name => 'sessionID',
317 return ($userid, $cookie, $sessionID, $flags);
319 # else we have a problem...
320 # get the inputs from the incoming query
322 foreach my $name (param $query) {
323 (next) if ($name eq 'userid' || $name eq 'password');
324 my $value = $query->param($name);
325 push @inputs, {name => $name , value => $value};
328 my $template = gettemplate($template_name, $type,$query);
329 $template->param(INPUTS => \@inputs);
330 $template->param(loginprompt => 1) unless $info{'nopermission'};
332 my $self_url = $query->url(-absolute => 1);
333 $template->param(url => $self_url);
334 $template->param(\%info);
335 $cookie=$query->cookie(-name => 'sessionID',
336 -value => $sessionID,
338 print $query->header(
339 -type => guesstype($template->output),
341 ), $template->output;
350 my ($dbh, $userid, $password) = @_;
352 my $sth=$dbh->prepare("select password,cardnumber from borrowers where userid=?");
353 $sth->execute($userid);
355 my ($md5password,$cardnumber) = $sth->fetchrow;
356 if (md5_base64($password) eq $md5password) {
357 return 1,$cardnumber;
360 my $sth=$dbh->prepare("select password from borrowers where cardnumber=?");
361 $sth->execute($userid);
363 my ($md5password) = $sth->fetchrow;
364 if (md5_base64($password) eq $md5password) {
368 if ($userid eq C4::Context->config('user') && $password eq C4::Context->config('pass')) {
369 # Koha superuser account
372 if ($userid eq 'demo' && $password eq 'demo' && C4::Context->config('demo')) {
373 # DEMO => the demo user is allowed to do everything (if demo set to 1 in koha.conf
374 # some features won't be effective : modify systempref, modify MARC structure,
381 my $cardnumber=shift;
384 my $sth=$dbh->prepare("SELECT flags FROM borrowers WHERE cardnumber=?");
385 $sth->execute($cardnumber);
386 my ($flags) = $sth->fetchrow;
387 $sth=$dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
389 while (my ($bit, $flag, $defaulton) = $sth->fetchrow) {
390 if (($flags & (2**$bit)) || $defaulton) {
391 $userflags->{$flag}=1;
398 my ($dbh, $userid, $flagsrequired) = @_;
399 my $sth=$dbh->prepare("SELECT cardnumber FROM borrowers WHERE userid=?");
400 $sth->execute($userid);
401 my ($cardnumber) = $sth->fetchrow;
402 ($cardnumber) || ($cardnumber=$userid);
403 my $flags=getuserflags($cardnumber,$dbh);
405 if ($userid eq C4::Context->config('user')) {
406 # Super User Account from /etc/koha.conf
407 $flags->{'superlibrarian'}=1;
409 if ($userid eq 'demo' && C4::Context->config('demo')) {
410 # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
411 $flags->{'superlibrarian'}=1;
413 return $flags if $flags->{superlibrarian};
414 foreach (keys %$flagsrequired) {
415 return $flags if $flags->{$_};
420 sub getborrowernumber {
422 my $dbh = C4::Context->dbh;
423 for my $field ('userid', 'cardnumber') {
424 my $sth=$dbh->prepare
425 ("select borrowernumber from borrowers where $field=?");
426 $sth->execute($userid);
428 my ($bnumber) = $sth->fetchrow;
435 END { } # module clean-up code here (global destructor)