+ elsif ( $lasttime < time() - $timeout ) {
+ # timed logout
+ $info{'timed_out'} = 1;
+ $session->delete();
+ C4::Context->_unset_userenv($sessionID);
+ _session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,localtime);
+ $userid = undef;
+ $sessionID = undef;
+ }
+ elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
+ # Different ip than originally logged in from
+ $info{'oldip'} = $ip;
+ $info{'newip'} = $ENV{'REMOTE_ADDR'};
+ $info{'different_ip'} = 1;
+ $session->delete();
+ C4::Context->_unset_userenv($sessionID);
+ _session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,localtime, $info{'newip'});
+ $sessionID = undef;
+ $userid = undef;
+ }
+ else {
+ $cookie = $query->cookie( CGISESSID => $session->id );
+ $session->param('lasttime',time());
+ unless ( $sessiontype eq 'anon' ) { #if this is an anonymous session, we want to update the session, but not behave as if they are logged in...
+ $flags = haspermission( $dbh, $userid, $flagsrequired );
+ if ($flags) {
+ $loggedin = 1;
+ } else {
+ $info{'nopermission'} = 1;
+ }
+ }
+ }
+ }
+ unless ($userid || $sessionID) {
+ #we initiate a session prior to checking for a username to allow for anonymous sessions...
+ my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
+ my $sessionID = $session->id;
+ C4::Context->_new_userenv($sessionID);
+ $cookie = $query->cookie(CGISESSID => $sessionID);
+ if ( $userid = $query->param('userid') ) {
+ my $password = $query->param('password');
+ my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
+ if ($return) {
+ _session_log(sprintf "%20s from %16s logged in at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},localtime);
+ if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
+ $loggedin = 1;
+ }
+ else {
+ $info{'nopermission'} = 1;
+ C4::Context->_unset_userenv($sessionID);
+ }
+
+ my ($borrowernumber, $firstname, $surname, $userflags,
+ $branchcode, $branchname, $branchprinter, $emailaddress);
+
+ if ( $return == 1 ) {
+ my $select = "
+ SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
+ branches.branchname as branchname,
+ branches.branchprinter as branchprinter,
+ email
+ FROM borrowers
+ LEFT JOIN branches on borrowers.branchcode=branches.branchcode
+ ";
+ my $sth = $dbh->prepare("$select where userid=?");
+ $sth->execute($userid);
+ unless ($sth->rows) {
+ $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
+ $sth = $dbh->prepare("$select where cardnumber=?");
+ $sth->execute($cardnumber);
+ unless ($sth->rows) {
+ $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
+ $sth->execute($userid);
+ unless ($sth->rows) {
+ $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
+ }
+ }
+ }
+ if ($sth->rows) {
+ ($borrowernumber, $firstname, $surname, $userflags,
+ $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
+ $debug and print STDERR "AUTH_3 results: " .
+ "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
+ } else {
+ print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
+ }
+
+# launch a sequence to check if we have a ip for the branch, i
+# if we have one we replace the branchcode of the userenv by the branch bound in the ip.
+
+ my $ip = $ENV{'REMOTE_ADDR'};
+ # if they specify at login, use that
+ if ($query->param('branch')) {
+ $branchcode = $query->param('branch');
+ $branchname = GetBranchName($branchcode);
+ }
+ my $branches = GetBranches();
+ if (C4::Context->boolean_preference('IndependantBranches') && C4::Context->boolean_preference('Autolocation')){
+ # we have to check they are coming from the right ip range
+ my $domain = $branches->{$branchcode}->{'branchip'};
+ if ($ip !~ /^$domain/){
+ $loggedin=0;
+ $info{'wrongip'} = 1;
+ }
+ }
+
+ my @branchesloop;
+ foreach my $br ( keys %$branches ) {
+ # now we work with the treatment of ip
+ my $domain = $branches->{$br}->{'branchip'};
+ if ( $domain && $ip =~ /^$domain/ ) {
+ $branchcode = $branches->{$br}->{'branchcode'};
+
+ # new op dev : add the branchprinter and branchname in the cookie
+ $branchprinter = $branches->{$br}->{'branchprinter'};
+ $branchname = $branches->{$br}->{'branchname'};
+ }
+ }
+ $session->param('number',$borrowernumber);
+ $session->param('id',$userid);
+ $session->param('cardnumber',$cardnumber);
+ $session->param('firstname',$firstname);
+ $session->param('surname',$surname);
+ $session->param('branch',$branchcode);
+ $session->param('branchname',$branchname);
+ $session->param('flags',$userflags);
+ $session->param('emailaddress',$emailaddress);
+ $session->param('ip',$session->remote_addr());
+ $session->param('lasttime',time());
+ $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
+ }
+ elsif ( $return == 2 ) {
+ #We suppose the user is the superlibrarian
+ $borrowernumber = 0;
+ $session->param('number',0);
+ $session->param('id',C4::Context->config('user'));
+ $session->param('cardnumber',C4::Context->config('user'));
+ $session->param('firstname',C4::Context->config('user'));
+ $session->param('surname',C4::Context->config('user'));
+ $session->param('branch','NO_LIBRARY_SET');
+ $session->param('branchname','NO_LIBRARY_SET');
+ $session->param('flags',1);
+ $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
+ $session->param('ip',$session->remote_addr());
+ $session->param('lasttime',time());
+ }
+ C4::Context::set_userenv(
+ $session->param('number'), $session->param('id'),
+ $session->param('cardnumber'), $session->param('firstname'),
+ $session->param('surname'), $session->param('branch'),
+ $session->param('branchname'), $session->param('flags'),
+ $session->param('emailaddress'), $session->param('branchprinter')
+ );
+
+ # Grab borrower's shelves and public shelves and add them to the session
+ # $row_count determines how many records are returned from the db query
+ # and the number of lists to be displayed of each type in the 'Lists' button drop down
+ my $row_count = 10; # FIXME:This probably should be a syspref
+ my ($total, $totshelves, $barshelves, $pubshelves);
+ ($barshelves, $totshelves) = C4::VirtualShelves::GetRecentShelves(1, $row_count, $borrowernumber);
+ $total->{'bartotal'} = $totshelves;
+ ($pubshelves, $totshelves) = C4::VirtualShelves::GetRecentShelves(2, $row_count, undef);
+ $total->{'pubtotal'} = $totshelves;
+ $session->param('barshelves', $barshelves->[0]);
+ $session->param('pubshelves', $pubshelves->[0]);
+ $session->param('totshelves', $total);
+
+ C4::Context::set_shelves_userenv('bar',$barshelves->[0]);
+ C4::Context::set_shelves_userenv('pub',$pubshelves->[0]);
+ C4::Context::set_shelves_userenv('tot',$total);
+ }
+ else {
+ if ($userid) {
+ $info{'invalid_username_or_password'} = 1;
+ C4::Context->_unset_userenv($sessionID);
+ }
+ }
+ } # END if ( $userid = $query->param('userid') )
+ elsif ($type eq "opac") {
+ # if we are here this is an anonymous session; add public lists to it and a few other items...
+ # anonymous sessions are created only for the OPAC
+ $debug and warn "Initiating an anonymous session...";
+
+ # Grab the public shelves and add to the session...
+ my $row_count = 20; # FIXME:This probably should be a syspref
+ my ($total, $totshelves, $pubshelves);
+ ($pubshelves, $totshelves) = C4::VirtualShelves::GetRecentShelves(2, $row_count, undef);
+ $total->{'pubtotal'} = $totshelves;
+ $session->param('pubshelves', $pubshelves->[0]);
+ $session->param('totshelves', $total);
+ C4::Context::set_shelves_userenv('pub',$pubshelves->[0]);
+ C4::Context::set_shelves_userenv('tot',$total);
+
+ # setting a couple of other session vars...
+ $session->param('ip',$session->remote_addr());
+ $session->param('lasttime',time());
+ $session->param('sessiontype','anon');
+ }
+ } # END unless ($userid)
+ my $insecure = C4::Context->boolean_preference('insecure');
+
+ # finished authentification, now respond
+ if ( $loggedin || $authnotrequired || ( defined($insecure) && $insecure ) )
+ {
+ # successful login
+ unless ($cookie) {
+ $cookie = $query->cookie( CGISESSID => '' );
+ }
+ return ( $userid, $cookie, $sessionID, $flags );
+ }
+
+#
+#
+# AUTH rejected, show the login/password template, after checking the DB.
+#
+#
+
+ # get the inputs from the incoming query
+ my @inputs = ();
+ foreach my $name ( param $query) {
+ (next) if ( $name eq 'userid' || $name eq 'password' );
+ my $value = $query->param($name);
+ push @inputs, { name => $name, value => $value };
+ }
+ # get the branchloop, which we need for authentication
+ my $branches = GetBranches();
+ my @branch_loop;
+ for my $branch_hash (sort keys %$branches) {
+ push @branch_loop, {branchcode => "$branch_hash", branchname => $branches->{$branch_hash}->{'branchname'}, };
+ }
+
+ my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
+ my $template = gettemplate( $template_name, $type, $query );
+ $template->param(branchloop => \@branch_loop,);
+ $template->param(
+ login => 1,
+ INPUTS => \@inputs,
+ suggestion => C4::Context->preference("suggestion"),
+ virtualshelves => C4::Context->preference("virtualshelves"),
+ LibraryName => C4::Context->preference("LibraryName"),
+ opacuserlogin => C4::Context->preference("opacuserlogin"),
+ OpacNav => C4::Context->preference("OpacNav"),
+ opaccredits => C4::Context->preference("opaccredits"),
+ opacreadinghistory => C4::Context->preference("opacreadinghistory"),
+ opacsmallimage => C4::Context->preference("opacsmallimage"),
+ opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
+ opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
+ opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
+ opacuserjs => C4::Context->preference("opacuserjs"),
+ opacbookbag => "" . C4::Context->preference("opacbookbag"),
+ OpacCloud => C4::Context->preference("OpacCloud"),
+ OpacTopissue => C4::Context->preference("OpacTopissue"),
+ OpacAuthorities => C4::Context->preference("OpacAuthorities"),
+ OpacBrowser => C4::Context->preference("OpacBrowser"),
+ opacheader => C4::Context->preference("opacheader"),
+ TagsEnabled => C4::Context->preference("TagsEnabled"),
+ OPACUserCSS => C4::Context->preference("OPACUserCSS"),
+ intranetcolorstylesheet =>
+ C4::Context->preference("intranetcolorstylesheet"),
+ intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+ IntranetNav => C4::Context->preference("IntranetNav"),
+ intranetuserjs => C4::Context->preference("intranetuserjs"),
+ TemplateEncoding => C4::Context->preference("TemplateEncoding"),
+ IndependantBranches=> C4::Context->preference("IndependantBranches"),
+ AutoLocation => C4::Context->preference("AutoLocation"),
+ wrongip => $info{'wrongip'}
+ );
+
+ $template->param( loginprompt => 1 ) unless $info{'nopermission'};
+
+ my $self_url = $query->url( -absolute => 1 );
+ $template->param(
+ url => $self_url,
+ LibraryName => C4::Context->preference("LibraryName"),
+ );
+ $template->param( \%info );
+# $cookie = $query->cookie(CGISESSID => $session->id
+# );
+ print $query->header(
+ -type => 'text/html',
+ -charset => 'utf-8',
+ -cookie => $cookie
+ ),
+ $template->output;
+ exit;
+}
+
+=item check_api_auth
+
+ ($status, $cookie, $sessionId) = check_api_auth($query, $userflags);
+
+Given a CGI query containing the parameters 'userid' and 'password' and/or a session
+cookie, determine if the user has the privileges specified by C<$userflags>.
+
+C<check_api_auth> is is meant for authenticating users of web services, and
+consequently will always return and will not attempt to redirect the user
+agent.
+
+If a valid session cookie is already present, check_api_auth will return a status
+of "ok", the cookie, and the Koha session ID.
+
+If no session cookie is present, check_api_auth will check the 'userid' and 'password
+parameters and create a session cookie and Koha session if the supplied credentials
+are OK.
+
+Possible return values in C<$status> are:
+
+=over 4
+
+=item "ok" -- user authenticated; C<$cookie> and C<$sessionid> have valid values.
+
+=item "failed" -- credentials are not correct; C<$cookie> and C<$sessionid> are undef
+
+=item "maintenance" -- DB is in maintenance mode; no login possible at the moment
+
+=item "expired -- session cookie has expired; API user should resubmit userid and password
+
+=back
+
+=cut
+
+sub check_api_auth {
+ my $query = shift;
+ my $flagsrequired = shift;
+
+ my $dbh = C4::Context->dbh;
+ my $timeout = C4::Context->preference('timeout');
+ $timeout = 600 unless $timeout;
+
+ unless (C4::Context->preference('Version')) {
+ # database has not been installed yet
+ return ("maintenance", undef, undef);
+ }
+ my $kohaversion=C4::Context::KOHAVERSION;
+ $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
+ if (C4::Context->preference('Version') < $kohaversion) {
+ # database in need of version update; assume that
+ # no API should be called while databsae is in
+ # this condition.
+ return ("maintenance", undef, undef);
+ }
+
+ # FIXME -- most of what follows is a copy-and-paste
+ # of code from checkauth. There is an obvious need
+ # for refactoring to separate the various parts of
+ # the authentication code, but as of 2007-11-19 this
+ # is deferred so as to not introduce bugs into the
+ # regular authentication code for Koha 3.0.
+
+ # see if we have a valid session cookie already
+ # however, if a userid parameter is present (i.e., from
+ # a form submission, assume that any current cookie
+ # is to be ignored
+ my $sessionID = undef;
+ unless ($query->param('userid')) {
+ $sessionID = $query->cookie("CGISESSID");
+ }
+ if ($sessionID) {
+ my $session = get_session($sessionID);
+ C4::Context->_new_userenv($sessionID);
+ if ($session) {
+ C4::Context::set_userenv(
+ $session->param('number'), $session->param('id'),
+ $session->param('cardnumber'), $session->param('firstname'),
+ $session->param('surname'), $session->param('branch'),
+ $session->param('branchname'), $session->param('flags'),
+ $session->param('emailaddress'), $session->param('branchprinter')
+ );
+
+ my $ip = $session->param('ip');
+ my $lasttime = $session->param('lasttime');
+ my $userid = $session->param('id');