Follow-up fix for Bug 4473 - Recent comments view for the OPAC
[koha.git] / C4 / Auth.pm
index bc96f19..2aac678 100644 (file)
@@ -26,35 +26,51 @@ use CGI::Session;
 
 require Exporter;
 use C4::Context;
-use C4::Output;    # to get the template
+use C4::Templates;    # to get the template
 use C4::Members;
 use C4::Koha;
 use C4::Branch; # GetBranches
 use C4::VirtualShelves;
 use POSIX qw/strftime/;
+use List::MoreUtils qw/ any /;
 
 # use utf8;
-use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
+use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $servers $memcached);
 
 BEGIN {
-    $VERSION = 3.02;        # set version for version checking
-    $debug = $ENV{DEBUG};
-    @ISA   = qw(Exporter);
-    @EXPORT    = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
-    @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &get_all_subpermissions &get_user_subpermissions);
-    %EXPORT_TAGS = (EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)]);
-    $ldap = C4::Context->config('useldapserver') || 0;
-    $cas = C4::Context->preference('casAuthentication');
-    $caslogout = C4::Context->preference('casLogout');
+    sub psgi_env { any { /^psgi\./ } keys %ENV }
+    sub safe_exit {
+       if ( psgi_env ) { die 'psgi:exit' }
+       else { exit }
+    }
+
+    $VERSION     = 3.02;                                                                                                            # set version for version checking
+    $debug       = $ENV{DEBUG};
+    @ISA         = qw(Exporter);
+    @EXPORT      = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
+    @EXPORT_OK   = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &get_all_subpermissions &get_user_subpermissions);
+    %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
+    $ldap        = C4::Context->config('useldapserver') || 0;
+    $cas         = C4::Context->preference('casAuthentication');
+    $caslogout   = C4::Context->preference('casLogout');
+    require C4::Auth_with_cas;             # no import
     if ($ldap) {
-        require C4::Auth_with_ldap;             # no import
-        import  C4::Auth_with_ldap qw(checkpw_ldap);
+       require C4::Auth_with_ldap;
+       import C4::Auth_with_ldap qw(checkpw_ldap);
     }
     if ($cas) {
-        require C4::Auth_with_cas;             # no import
-        import  C4::Auth_with_cas qw(checkpw_cas login_cas logout_cas login_cas_url);
+        import  C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
+    }
+    $servers = C4::Context->config('memcached_servers');
+    if ($servers) {
+       require Cache::Memcached;
+        $memcached = Cache::Memcached->new({
+                                              servers => [ $servers ],
+                                              debug   => 0,
+                                              compress_threshold => 10_000,
+                                              namespace => C4::Context->config('memcached_namespace') || 'koha',
+                                          });
     }
-
 }
 
 =head1 NAME
@@ -122,18 +138,21 @@ Output.pm module.
 
 my $SEARCH_HISTORY_INSERT_SQL =<<EOQ;
 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, total, time            )
-VALUES                    (     ?,         ?,          ?,         ?,     ?, FROM_UNIXTIME(?))
+VALUES                    (     ?,         ?,          ?,         ?,          ?, FROM_UNIXTIME(?))
 EOQ
 sub get_template_and_user {
     my $in       = shift;
     my $template =
-      gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
-    my ( $user, $cookie, $sessionID, $flags ) = checkauth(
-        $in->{'query'},
-        $in->{'authnotrequired'},
-        $in->{'flagsrequired'},
-        $in->{'type'}
-    ) unless ($in->{'template_name'}=~/maintenance/);
+      C4::Templates::gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
+    my ( $user, $cookie, $sessionID, $flags );
+    if ( $in->{'template_name'} !~m/maintenance/ ) {
+        ( $user, $cookie, $sessionID, $flags ) = checkauth(
+            $in->{'query'},
+            $in->{'authnotrequired'},
+            $in->{'flagsrequired'},
+            $in->{'type'}
+        );
+    }
 
     my $borrowernumber;
     my $insecure = C4::Context->preference('insecure');
@@ -154,19 +173,19 @@ sub get_template_and_user {
         $template->param( loggedinusername => $user );
         $template->param( sessionID        => $sessionID );
 
-               my ($total, $pubshelves, $barshelves) = C4::Context->get_shelves_userenv();
-               if (defined($pubshelves)) {
-               $template->param(       pubshelves      => scalar (@$pubshelves),
-                                                       pubshelvesloop  => $pubshelves,
-                                                       );
-                       $template->param(       pubtotal                => $total->{'pubtotal'}, ) if ($total->{'pubtotal'} > scalar (@$pubshelves));
-               }
-               if (defined($barshelves)) {
-               $template->param(       barshelves      => scalar (@$barshelves),
-                                                       barshelvesloop  => $barshelves,
-                                                       );
-                       $template->param(       bartotal                => $total->{'bartotal'}, ) if ($total->{'bartotal'} > scalar (@$barshelves));
-               }
+        my ($total, $pubshelves, $barshelves) = C4::Context->get_shelves_userenv();
+        if (defined($pubshelves)) {
+            $template->param( pubshelves     => scalar @{$pubshelves},
+                              pubshelvesloop => $pubshelves,
+            );
+            $template->param( pubtotal   => $total->{'pubtotal'}, ) if ($total->{'pubtotal'} > scalar @{$pubshelves});
+        }
+        if (defined($barshelves)) {
+            $template->param( barshelves      => scalar @{$barshelves},
+                              barshelvesloop  => $barshelves,
+            );
+            $template->param( bartotal  => $total->{'bartotal'}, ) if ($total->{'bartotal'} > scalar @{$barshelves});
+        }
 
         $borrowernumber = getborrowernumber($user) if defined($user);
 
@@ -258,7 +277,7 @@ sub get_template_and_user {
                                                       $_->{'query_cgi'},
                                                       $_->{'total'},
                                                       $_->{'time'},
-                                        ) foreach @recentSearches;
+                            ) foreach @recentSearches;
 
                                        # And then, delete the cookie's content
                                        my $newsearchcookie = $in->{'query'}->cookie(
@@ -287,11 +306,11 @@ sub get_template_and_user {
         $template->param( sessionID        => $sessionID );
         
         my ($total, $pubshelves) = C4::Context->get_shelves_userenv();  # an anonymous user has no 'barshelves'...
-        if (defined(($pubshelves))) {
-            $template->param(   pubshelves      => scalar (@$pubshelves),
+        if (defined $pubshelves) {
+            $template->param(   pubshelves      => scalar @{$pubshelves},
                                 pubshelvesloop  => $pubshelves,
                             );
-            $template->param(   pubtotal        => $total->{'pubtotal'}, ) if ($total->{'pubtotal'} > scalar (@$pubshelves));
+            $template->param(   pubtotal        => $total->{'pubtotal'}, ) if ($total->{'pubtotal'} > scalar @{$pubshelves});
         }
 
     }
@@ -326,6 +345,7 @@ sub get_template_and_user {
             "BiblioDefaultView".C4::Context->preference("BiblioDefaultView")         => 1,
             EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
             GoogleJackets                => C4::Context->preference("GoogleJackets"),
+           OpenLibraryCovers            => C4::Context->preference("OpenLibraryCovers"),
             KohaAdminEmailAddress        => "" . C4::Context->preference("KohaAdminEmailAddress"),
             LoginBranchcode              => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
             LoginFirstname               => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
@@ -359,6 +379,7 @@ sub get_template_and_user {
             advancedMARCEditor          => C4::Context->preference("advancedMARCEditor"),
             canreservefromotherbranches => C4::Context->preference('canreservefromotherbranches'),
             intranetcolorstylesheet     => C4::Context->preference("intranetcolorstylesheet"),
+            IntranetFavicon             => C4::Context->preference("IntranetFavicon"),
             intranetreadinghistory      => C4::Context->preference("intranetreadinghistory"),
             intranetstylesheet          => C4::Context->preference("intranetstylesheet"),
             IntranetUserCSS             => C4::Context->preference("IntranetUserCSS"),
@@ -368,6 +389,7 @@ sub get_template_and_user {
             virtualshelves              => C4::Context->preference("virtualshelves"),
             StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
             NoZebra                     => C4::Context->preference('NoZebra'),
+               EasyAnalyticalRecords => C4::Context->preference('EasyAnalyticalRecords'),
         );
     }
     else {
@@ -410,6 +432,7 @@ sub get_template_and_user {
             OpacHighlightedWords       => C4::Context->preference("OpacHighlightedWords"),
             OPACItemHolds             => C4::Context->preference("OPACItemHolds"),
             OPACShelfBrowser          => "". C4::Context->preference("OPACShelfBrowser"),
+            OpacShowRecentComments    => C4::Context->preference("OpacShowRecentComments"),
             OPACURLOpenInNewWindow    => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
             OPACUserCSS               => "". C4::Context->preference("OPACUserCSS"),
             OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
@@ -421,8 +444,10 @@ sub get_template_and_user {
             opac_limit_override       => $opac_limit_override,
             OpacBrowser               => C4::Context->preference("OpacBrowser"),
             OpacCloud                 => C4::Context->preference("OpacCloud"),
+            OpacKohaUrl               => C4::Context->preference("OpacKohaUrl"),
             OpacMainUserBlock         => "" . C4::Context->preference("OpacMainUserBlock"),
             OpacNav                   => "" . C4::Context->preference("OpacNav"),
+            OpacNavBottom             => "" . C4::Context->preference("OpacNavBottom"),
             OpacPasswordChange        => C4::Context->preference("OpacPasswordChange"),
             OPACPatronDetails        => C4::Context->preference("OPACPatronDetails"),
             OPACPrivacy               => C4::Context->preference("OPACPrivacy"),
@@ -436,6 +461,7 @@ sub get_template_and_user {
             opacstylesheet            => "" . C4::Context->preference("opacstylesheet"),
             opacbookbag               => "" . C4::Context->preference("opacbookbag"),
             opaccredits               => "" . C4::Context->preference("opaccredits"),
+            OpacFavicon               => C4::Context->preference("OpacFavicon"),
             opacheader                => "" . C4::Context->preference("opacheader"),
             opaclanguagesdisplay      => "" . C4::Context->preference("opaclanguagesdisplay"),
             opacreadinghistory        => C4::Context->preference("opacreadinghistory"),
@@ -443,6 +469,8 @@ sub get_template_and_user {
             opacuserjs                => C4::Context->preference("opacuserjs"),
             opacuserlogin             => "" . C4::Context->preference("opacuserlogin"),
             reviewson                 => C4::Context->preference("reviewson"),
+            ShowReviewer              => C4::Context->preference("ShowReviewer"),
+            ShowReviewerPhoto         => C4::Context->preference("ShowReviewerPhoto"),
             suggestion                => "" . C4::Context->preference("suggestion"),
             virtualshelves            => "" . C4::Context->preference("virtualshelves"),
             OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
@@ -463,7 +491,7 @@ sub get_template_and_user {
             SyndeticsCoverImageSize      => C4::Context->preference("SyndeticsCoverImageSize"),
         );
 
-        $template->param(OpacPublic => '1') if ($template->param( 'loggedinusername') || C4::Context->preference("OpacPublic"));
+        $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
     }
        $template->param(listloop=>[{shelfname=>"Freelist", shelfnumber=>110}]);
     return ( $template, $borrowernumber, $cookie, $flags);
@@ -555,19 +583,18 @@ sub _version_check ($$) {
     # and so we must redirect to OPAC maintenance page or to the WebInstaller
        # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
        if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
-               warn "OPAC Install required, redirecting to maintenance";
-               print $query->redirect("/cgi-bin/koha/maintenance.pl");
-       }
-    unless ($version = C4::Context->preference('Version')) {    # assignment, not comparison
-      if ($type ne 'opac') {
-        warn "Install required, redirecting to Installer";
-        print $query->redirect("/cgi-bin/koha/installer/install.pl");
-      }
-      else {
         warn "OPAC Install required, redirecting to maintenance";
         print $query->redirect("/cgi-bin/koha/maintenance.pl");
-      }
-      exit;
+    }
+    unless ( $version = C4::Context->preference('Version') ) {    # assignment, not comparison
+        if ( $type ne 'opac' ) {
+            warn "Install required, redirecting to Installer";
+            print $query->redirect("/cgi-bin/koha/installer/install.pl");
+        } else {
+            warn "OPAC Install required, redirecting to maintenance";
+            print $query->redirect("/cgi-bin/koha/maintenance.pl");
+        }
+        safe_exit;
     }
 
     # check that database and koha version are the same
@@ -587,7 +614,7 @@ sub _version_check ($$) {
             warn sprintf("OPAC: " . $warning, 'maintenance');
             print $query->redirect("/cgi-bin/koha/maintenance.pl");
         }
-        exit;
+        safe_exit;
     }
 }
 
@@ -622,6 +649,10 @@ sub checkauth {
     my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
     my $logout = $query->param('logout.x');
 
+    # This parameter is the name of the CAS server we want to authenticate against,
+    # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
+    my $casparam = $query->param('cas');
+
     if ( $userid = $ENV{'REMOTE_USER'} ) {
         # Using Basic Authentication, no cookies required
         $cookie = $query->cookie(
@@ -724,7 +755,9 @@ sub checkauth {
                    $userid = $retuserid;
                    $info{'invalidCasLogin'} = 1 unless ($return);
                } else {
-                   ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
+                   my $retuserid;
+                   ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, $password, $query );
+                   $userid = $retuserid if ($retuserid ne '');
                }
                if ($return) {
                _session_log(sprintf "%20s from %16s logged in  at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
@@ -750,20 +783,21 @@ sub checkauth {
                        ";
                        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";
-                                                       }
-                                               }
-                                       }
+                       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,
+                           ($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";
@@ -847,12 +881,12 @@ sub checkauth {
                                $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('barshelves', $barshelves);
+                               $session->param('pubshelves', $pubshelves);
                                $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('bar',$barshelves);
+                               C4::Context::set_shelves_userenv('pub',$pubshelves);
                                C4::Context::set_shelves_userenv('tot',$total);
                        }
                else {
@@ -872,9 +906,9 @@ sub checkauth {
                        my ($total, $totshelves, $pubshelves);
                        ($pubshelves, $totshelves) = C4::VirtualShelves::GetRecentShelves(2, $row_count, undef);
                        $total->{'pubtotal'} = $totshelves;
-                       $session->param('pubshelves', $pubshelves->[0]);
+                       $session->param('pubshelves', $pubshelves);
                        $session->param('totshelves', $total);
-                       C4::Context::set_shelves_userenv('pub',$pubshelves->[0]);
+                       C4::Context::set_shelves_userenv('pub',$pubshelves);
                        C4::Context::set_shelves_userenv('tot',$total);
 
                        # setting a couple of other session vars...
@@ -916,7 +950,7 @@ sub checkauth {
     }
 
     my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
-    my $template = gettemplate( $template_name, $type, $query );
+    my $template = C4::Templates::gettemplate( $template_name, $type, $query );
     $template->param(branchloop => \@branch_loop,);
     my $checkstyle = C4::Context->preference("opaccolorstylesheet");
     if ($checkstyle =~ /\//)
@@ -936,7 +970,9 @@ sub checkauth {
         LibraryName          => C4::Context->preference("LibraryName"),
         opacuserlogin        => C4::Context->preference("opacuserlogin"),
         OpacNav              => C4::Context->preference("OpacNav"),
+        OpacNavBottom        => C4::Context->preference("OpacNavBottom"),
         opaccredits          => C4::Context->preference("opaccredits"),
+        OpacFavicon          => C4::Context->preference("OpacFavicon"),
         opacreadinghistory   => C4::Context->preference("opacreadinghistory"),
         opacsmallimage       => C4::Context->preference("opacsmallimage"),
         opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
@@ -950,6 +986,7 @@ sub checkauth {
         opacheader           => C4::Context->preference("opacheader"),
         TagsEnabled                  => C4::Context->preference("TagsEnabled"),
         OPACUserCSS           => C4::Context->preference("OPACUserCSS"),
+        opacstylesheet       => C4::Context->preference("opacstylesheet"),
         intranetcolorstylesheet =>
                                                                C4::Context->preference("intranetcolorstylesheet"),
         intranetstylesheet => C4::Context->preference("intranetstylesheet"),
@@ -964,11 +1001,28 @@ sub checkauth {
     $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
 
-    if ($cas) { 
+    if ($cas) {
+
+       # Is authentication against multiple CAS servers enabled?
+        if (C4::Auth_with_cas::multipleAuth && !$casparam) {
+           my $casservers = C4::Auth_with_cas::getMultipleAuth();                  
+           my @tmplservers;
+           foreach my $key (keys %$casservers) {
+               push @tmplservers, {name => $key, value => login_cas_url($query, $key) . "?cas=$key" };
+           }
+           #warn Data::Dumper::Dumper(\@tmplservers);
+           $template->param(
+               casServersLoop => \@tmplservers
+           );
+       } else {
+        $template->param(
+            casServerUrl    => login_cas_url($query),
+           );
+       }
+
        $template->param(
-           casServerUrl    => login_cas_url(),
-           invalidCasLogin => $info{'invalidCasLogin'}
-       );
+            invalidCasLogin => $info{'invalidCasLogin'}
+        );
     }
 
     my $self_url = $query->url( -absolute => 1 );
@@ -976,7 +1030,7 @@ sub checkauth {
         url         => $self_url,
         LibraryName => C4::Context->preference("LibraryName"),
     );
-    $template->param( \%info );
+    $template->param( %info );
 #    $cookie = $query->cookie(CGISESSID => $session->id
 #   );
     print $query->header(
@@ -985,7 +1039,7 @@ sub checkauth {
         -cookie => $cookie
       ),
       $template->output;
-    exit;
+    safe_exit;
 }
 
 =head2 check_api_auth
@@ -1058,7 +1112,7 @@ sub check_api_auth {
     unless ($query->param('userid')) {
         $sessionID = $query->cookie("CGISESSID");
     }
-    if ($sessionID) {
+    if ($sessionID && not $cas) {
         my $session = get_session($sessionID);
         C4::Context->_new_userenv($sessionID);
         if ($session) {
@@ -1108,18 +1162,24 @@ sub check_api_auth {
         # new login
         my $userid = $query->param('userid');
         my $password = $query->param('password');
-        unless ($userid and $password) {
-            # caller did something wrong, fail the authenticateion
-            return ("failed", undef, undef);
-        }
-       my ($return, $cardnumber);
-       if ($cas && $query->param('ticket')) {
+               my ($return, $cardnumber);
+
+       # Proxy CAS auth
+       if ($cas && $query->param('PT')) {
            my $retuserid;
-           ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, $password, $query );
-           $userid = $retuserid;
+           $debug and print STDERR "## check_api_auth - checking CAS\n";
+           # In case of a CAS authentication, we use the ticket instead of the password
+           my $PT = $query->param('PT');
+           ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query);    # EXTERNAL AUTH
        } else {
+           # User / password auth
+           unless ($userid and $password) {
+               # caller did something wrong, fail the authenticateion
+               return ("failed", undef, undef);
+           }
            ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
        }
+
         if ($return and haspermission(  $userid, $flagsrequired)) {
             my $session = get_session("");
             return ("failed", undef, undef) unless $session;
@@ -1357,6 +1417,9 @@ sub get_session {
     elsif ($storage_method eq 'Pg') {
         $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
     }
+    elsif ($storage_method eq 'memcached' && $servers){
+       $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => $memcached } );
+    }
     else {
         # catch all defaults to tmp should work on all systems
         $session = new CGI::Session("driver:File;serializer:yaml;id:md5", $sessionID, {Directory=>'/tmp'});
@@ -1369,11 +1432,11 @@ sub checkpw {
     my ( $dbh, $userid, $password, $query ) = @_;
     if ($ldap) {
         $debug and print "## checkpw - checking LDAP\n";
-        my ($retval,$retcard) = checkpw_ldap(@_);    # EXTERNAL AUTH
-        ($retval) and return ($retval,$retcard);
+        my ($retval,$retcard,$retuserid) = checkpw_ldap(@_);    # EXTERNAL AUTH
+        ($retval) and return ($retval,$retcard,$retuserid);
     }
 
-    if ($cas && $query->param('ticket')) {
+    if ($cas && $query && $query->param('ticket')) {
         $debug and print STDERR "## checkpw - checking CAS\n";
        # In case of a CAS authentication, we use the ticket instead of the password
        my $ticket = $query->param('ticket');
@@ -1396,7 +1459,7 @@ sub checkpw {
 
             C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
                 $firstname, $surname, $branchcode, $flags );
-            return 1, $cardnumber;
+            return 1, $cardnumber, $userid;
         }
     }
     $sth =
@@ -1412,7 +1475,7 @@ sub checkpw {
 
             C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
                 $firstname, $surname, $branchcode, $flags );
-            return 1, $userid;
+            return 1, $cardnumber, $userid;
         }
     }
     if (   $userid && $userid eq C4::Context->config('user')
@@ -1560,7 +1623,7 @@ sub haspermission {
     my ($userid, $flagsrequired) = @_;
     my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
     $sth->execute($userid);
-    my $flags = getuserflags( $sth->fetchrow(), $userid );
+    my $flags = getuserflags($sth->fetchrow(), $userid);
     if ( $userid eq C4::Context->config('user') ) {
         # Super User Account from /etc/koha.conf
         $flags->{'superlibrarian'} = 1;
@@ -1569,7 +1632,9 @@ sub haspermission {
         # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
         $flags->{'superlibrarian'} = 1;
     }
+
     return $flags if $flags->{superlibrarian};
+
     foreach my $module ( keys %$flagsrequired ) {
         my $subperm = $flagsrequired->{$module};
         if ($subperm eq '*') {