Bug 29648: Move NumSavedReports to the table settings
[koha-ffzg.git] / C4 / Auth.pm
index d5eec4b..c1c27e0 100644 (file)
@@ -23,6 +23,7 @@ use Carp qw( croak );
 
 use Digest::MD5 qw( md5_base64 );
 use CGI::Session;
+use CGI::Session::ErrorHandler;
 use URI;
 use URI::QueryParam;
 
@@ -34,6 +35,7 @@ use Koha;
 use Koha::Logger;
 use Koha::Caches;
 use Koha::AuthUtils qw( get_script_name hash_password );
+use Koha::Auth::TwoFactorAuth;
 use Koha::Checkouts;
 use Koha::DateUtils qw( dt_from_string );
 use Koha::Library::Groups;
@@ -47,6 +49,7 @@ use Encode;
 use C4::Auth_with_shibboleth qw( shib_ok get_login_shib login_shib_url logout_shib checkpw_shib );
 use Net::CIDR;
 use C4::Log qw( logaction );
+use Koha::CookieManager;
 
 # use utf8;
 
@@ -153,6 +156,9 @@ sub get_template_and_user {
 
     my $in = shift;
     my ( $user, $cookie, $sessionID, $flags );
+    $cookie = [];
+
+    my $cookie_mgr = Koha::CookieManager->new;
 
     # Get shibboleth login attribute
     my $shib = C4::Context->config('useshibboleth') && shib_ok();
@@ -242,13 +248,13 @@ sub get_template_and_user {
         if ($kick_out) {
             $template = C4::Templates::gettemplate( 'opac-auth.tt', 'opac',
                 $in->{query} );
-            $cookie = $in->{query}->cookie(
+            $cookie = $cookie_mgr->replace_in_list( $cookie, $in->{query}->cookie(
                 -name     => 'CGISESSID',
                 -value    => '',
-                -expires  => '',
                 -HttpOnly => 1,
                 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-            );
+                -sameSite => 'Lax',
+            ));
 
             $template->param(
                 loginprompt => 1,
@@ -347,6 +353,7 @@ sub get_template_and_user {
             $template->param( CAN_user_stockrotation    => 1 );
             $template->param( CAN_user_cash_management  => 1 );
             $template->param( CAN_user_problem_reports  => 1 );
+            $template->param( CAN_user_recalls          => 1 );
 
             foreach my $module ( keys %$all_perms ) {
                 foreach my $subperm ( keys %{ $all_perms->{$module} } ) {
@@ -451,10 +458,10 @@ sub get_template_and_user {
             $template->param(
                 some_public_shelves  => $some_public_shelves,
             );
-        }
 
-        # Set default branch if one has been passed by the environment.
-        $template->param( branchcode => $ENV{OPAC_BRANCH_DEFAULT} ) if $ENV{OPAC_BRANCH_DEFAULT};
+            # Set default branch if one has been passed by the environment.
+            $template->param( default_branch => $ENV{OPAC_BRANCH_DEFAULT} ) if $ENV{OPAC_BRANCH_DEFAULT};
+        }
     }
 
     # Sysprefs disabled via URL param
@@ -496,7 +503,6 @@ sub get_template_and_user {
     my $minPasswordLength = C4::Context->preference('minPasswordLength');
     $minPasswordLength = 3 if not $minPasswordLength or $minPasswordLength < 3;
     $template->param(
-        "BiblioDefaultView" . C4::Context->preference("BiblioDefaultView") => 1,
         EnhancedMessagingPreferences                                       => C4::Context->preference('EnhancedMessagingPreferences'),
         GoogleJackets                                                      => C4::Context->preference("GoogleJackets"),
         OpenLibraryCovers                                                  => C4::Context->preference("OpenLibraryCovers"),
@@ -518,7 +524,6 @@ sub get_template_and_user {
         $template->param(
             AmazonCoverImages                                                          => C4::Context->preference("AmazonCoverImages"),
             AutoLocation                                                               => C4::Context->preference("AutoLocation"),
-            "BiblioDefaultView" . C4::Context->preference("IntranetBiblioDefaultView") => 1,
             PatronAutoComplete                                                       => C4::Context->preference("PatronAutoComplete"),
             FRBRizeEditions                                                            => C4::Context->preference("FRBRizeEditions"),
             IndependentBranches                                                        => C4::Context->preference("IndependentBranches"),
@@ -563,9 +568,10 @@ sub get_template_and_user {
             unless ( $pagename =~ /^(?:MARC|ISBD)?detail$/
                 or $pagename =~ /^showmarc$/
                 or $pagename =~ /^addbybiblionumber$/
-                or $pagename =~ /^review$/ ) {
-                my $sessionSearch = get_session( $sessionID || $in->{'query'}->cookie("CGISESSID") );
-                $sessionSearch->clear( ["busc"] ) if ( $sessionSearch->param("busc") );
+                or $pagename =~ /^review$/ )
+            {
+                my $sessionSearch = get_session( $sessionID );
+                $sessionSearch->clear( ["busc"] ) if $sessionSearch;
             }
         }
 
@@ -653,11 +659,7 @@ sub get_template_and_user {
         # what to do
         my $language = C4::Languages::getlanguage( $in->{'query'} );
         my $languagecookie = C4::Templates::getlanguagecookie( $in->{'query'}, $language );
-        if ( ref $cookie eq 'ARRAY' ) {
-            push @{$cookie}, $languagecookie;
-        } else {
-            $cookie = [ $cookie, $languagecookie ];
-        }
+        $cookie = $cookie_mgr->replace_in_list( $cookie, $languagecookie );
     }
 
     return ( $template, $borrowernumber, $cookie, $flags );
@@ -837,12 +839,16 @@ sub checkauth {
     my $dbh     = C4::Context->dbh;
     my $timeout = _timeout_syspref();
 
+    my $cookie_mgr = Koha::CookieManager->new;
+
     _version_check( $type, $query );
 
     # state variables
     my $loggedin = 0;
+    my $auth_state = 'failed';
     my %info;
     my ( $userid, $cookie, $sessionID, $flags );
+    $cookie = [];
     my $logout = $query->param('logout.x');
 
     my $anon_search_history;
@@ -853,6 +859,8 @@ sub checkauth {
     my $q_userid = $query->param('userid') // '';
 
     my $session;
+    my $invalid_otp_token;
+    my $require_2FA = ( C4::Context->preference('TwoFactorAuthentication') && $type ne "OPAC" ) ? 1 : 0;
 
     # Basic authentication is incompatible with the use of Shibboleth,
     # as Shibboleth may return REMOTE_USER as a Shibboleth attribute,
@@ -866,13 +874,13 @@ sub checkauth {
     if ( !$shib and defined( $ENV{'REMOTE_USER'} ) and $ENV{'REMOTE_USER'} ne '' and $userid = $ENV{'REMOTE_USER'} ) {
 
         # Using Basic Authentication, no cookies required
-        $cookie = $query->cookie(
+        $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie(
             -name     => 'CGISESSID',
             -value    => '',
-            -expires  => '',
             -HttpOnly => 1,
             -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-        );
+            -sameSite => 'Lax',
+        ));
         $loggedin = 1;
     }
     elsif ( $emailaddress) {
@@ -880,17 +888,49 @@ sub checkauth {
     }
     elsif ( $sessionID = $query->cookie("CGISESSID") ) {    # assignment, not comparison
         my ( $return, $more_info );
+        # NOTE: $flags in the following call is still undefined !
         ( $return, $session, $more_info ) = check_cookie_auth( $sessionID, $flags,
             { remote_addr => $ENV{REMOTE_ADDR}, skip_version_check => 1 }
         );
 
-        if ( $return eq 'ok' ) {
-            Koha::Logger->get->debug(sprintf "AUTH_SESSION: (%s)\t%s %s - %s", map { $session->param($_) || q{} } qw(cardnumber firstname surname branch));
+        if ( $return eq 'ok' || $return eq 'additional-auth-needed' ) {
+            $userid = $session->param('id');
+        }
 
-            my $s_userid = $session->param('id');
-            $userid      = $s_userid;
+        $auth_state =
+            $return eq 'ok'                     ? 'completed'
+          : $return eq 'additional-auth-needed' ? 'additional-auth-needed'
+          :                                       'failed';
 
-            if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
+        # We are at the second screen if the waiting-for-2FA is set in session
+        # and otp_token param has been passed
+        if (   $require_2FA
+            && $auth_state eq 'additional-auth-needed'
+            && ( my $otp_token = $query->param('otp_token') ) )
+        {
+            my $patron    = Koha::Patrons->find( { userid => $userid } );
+            my $auth      = Koha::Auth::TwoFactorAuth->new( { patron => $patron } );
+            my $verified = $auth->verify($otp_token);
+            $auth->clear;
+            if ( $verified ) {
+                # The token is correct, the user is fully logged in!
+                $auth_state = 'completed';
+                $session->param( 'waiting-for-2FA', 0 );
+
+               # This is an ugly trick to pass the test
+               # $query->param('koha_login_context') && ( $q_userid ne $userid )
+               # few lines later
+                $q_userid = $userid;
+            }
+            else {
+                $invalid_otp_token = 1;
+            }
+        }
+
+        if ( $auth_state eq 'completed' ) {
+            Koha::Logger->get->debug(sprintf "AUTH_SESSION: (%s)\t%s %s - %s", map { $session->param($_) || q{} } qw(cardnumber firstname surname branch));
+
+            if ( ( $query->param('koha_login_context') && ( $q_userid ne $userid ) )
                 || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} )
                 || ( $shib && $shib_login && !$logout && !C4::Context->userenv->{'id'} )
             ) {
@@ -900,42 +940,23 @@ sub checkauth {
                 $anon_search_history = $session->param('search_history');
                 $session->delete();
                 $session->flush;
-                C4::Context->_unset_userenv($sessionID);
-            }
-            elsif ($logout) {
+                $cookie = $cookie_mgr->clear_unless( $query->cookie, @$cookie );
+                C4::Context::_unset_userenv($sessionID);
+                $sessionID = undef;
+            } elsif (!$logout) {
 
-                # voluntary logout the user
-                # check wether the user was using their shibboleth session or a local one
-                my $shibSuccess = C4::Context->userenv->{'shibboleth'};
-                $session->delete();
-                $session->flush;
-                C4::Context->_unset_userenv($sessionID);
-
-                if ($cas and $caslogout) {
-                    logout_cas($query, $type);
-                }
-
-                # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
-                if ( $shib and $shib_login and $shibSuccess) {
-                    logout_shib($query);
-                }
-            } else {
-
-                $cookie = $query->cookie(
+                $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie(
                     -name     => 'CGISESSID',
                     -value    => $session->id,
                     -HttpOnly => 1,
                     -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-                );
+                    -sameSite => 'Lax',
+                ));
 
-                my $sessiontype = $session->param('sessiontype') || '';
-                unless ( $sessiontype && $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( $userid, $flagsrequired );
-                    if ($flags) {
-                        $loggedin = 1;
-                    } else {
-                        $info{'nopermission'} = 1;
-                    }
+                $flags = haspermission( $userid, $flagsrequired );
+                unless ( $flags ) {
+                    $auth_state = 'failed';
+                    $info{'nopermission'} = 1;
                 }
             }
         } elsif ( !$logout ) {
@@ -949,14 +970,41 @@ sub checkauth {
         }
     }
 
-    unless ( $loggedin ) {
+    if ( $auth_state eq 'failed' || $logout ) {
         $sessionID = undef;
         $userid    = undef;
     }
 
+    if ($logout) {
+
+        # voluntary logout the user
+        # check wether the user was using their shibboleth session or a local one
+        my $shibSuccess = C4::Context->userenv->{'shibboleth'};
+        if ( $session ) {
+            $session->delete();
+            $session->flush;
+        }
+        C4::Context::_unset_userenv($sessionID);
+        $cookie = $cookie_mgr->clear_unless( $query->cookie, @$cookie );
+
+        if ($cas and $caslogout) {
+            logout_cas($query, $type);
+        }
+
+        # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
+        if ( $shib and $shib_login and $shibSuccess) {
+            logout_shib($query);
+        }
+
+        $session   = undef;
+        $auth_state = 'logout';
+    }
+
     unless ( $userid ) {
         #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()";
+        if( !$session or !$sessionID ) { # if we cleared sessionID, we need a new session
+            $session = get_session() or die "Auth ERROR: Cannot get_session()";
+        }
 
         # Save anonymous search history in new session so it can be retrieved
         # by get_template_and_user to store it in user's search history after
@@ -967,12 +1015,13 @@ sub checkauth {
 
         $sessionID = $session->id;
         C4::Context->_new_userenv($sessionID);
-        $cookie = $query->cookie(
+        $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie(
             -name     => 'CGISESSID',
             -value    => $sessionID,
             -HttpOnly => 1,
             -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-        );
+            -sameSite => 'Lax',
+        ));
         my $pki_field = C4::Context->preference('AllowPKIAuth');
         if ( !defined($pki_field) ) {
             print STDERR "ERROR: Missing system preference AllowPKIAuth.\n";
@@ -1101,11 +1150,11 @@ sub checkauth {
             if ($return) {
 
                 if ( $flags = haspermission( $userid, $flagsrequired ) ) {
-                    $loggedin = 1;
+                    $auth_state = "logged_in";
                 }
                 else {
                     $info{'nopermission'} = 1;
-                    C4::Context->_unset_userenv($sessionID);
+                    C4::Context::_unset_userenv($sessionID);
                 }
                 my ( $borrowernumber, $firstname, $surname, $userflags,
                     $branchcode, $branchname, $emailaddress, $desk_id,
@@ -1167,12 +1216,13 @@ sub checkauth {
                         $domain =~ s|\.\*||g;
                         if ( $ip !~ /^$domain/ ) {
                             $loggedin = 0;
-                            $cookie = $query->cookie(
+                            $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie(
                                 -name     => 'CGISESSID',
                                 -value    => '',
                                 -HttpOnly => 1,
                                 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-                            );
+                                -sameSite => 'Lax',
+                            ));
                             $info{'wrongip'} = 1;
                         }
                     }
@@ -1230,7 +1280,7 @@ sub checkauth {
             else {
                 if ($userid) {
                     $info{'invalid_username_or_password'} = 1;
-                    C4::Context->_unset_userenv($sessionID);
+                    C4::Context::_unset_userenv($sessionID);
                 }
                 $session->param( 'lasttime', time() );
                 $session->param( 'ip',       $session->remote_addr() );
@@ -1248,19 +1298,36 @@ sub checkauth {
             $session->param( 'sessiontype', 'anon' );
             $session->param( 'interface', $type);
         }
+        $session->flush;
     }    # END unless ($userid)
 
+
+    if ( $auth_state eq 'logged_in' ) {
+        $auth_state = 'completed';
+
+        # Auth is completed unless an additional auth is needed
+        if ( $require_2FA ) {
+            my $patron = Koha::Patrons->find({userid => $userid});
+            if ( $patron->auth_method eq 'two-factor' ) {
+                # Ask for the OTP token
+                $auth_state = 'additional-auth-needed';
+                $session->param('waiting-for-2FA', 1);
+                %info = ();# We remove the warnings/errors we may have set incorrectly before
+            }
+        }
+    }
+
     # finished authentification, now respond
-    if ( $loggedin || $authnotrequired )
-    {
+    if ( $auth_state eq 'completed' || $authnotrequired ) {
         # successful login
-        unless ($cookie) {
-            $cookie = $query->cookie(
+        unless (@$cookie) {
+            $cookie = $cookie_mgr->replace_in_list( $cookie, $query->cookie(
                 -name     => 'CGISESSID',
                 -value    => '',
                 -HttpOnly => 1,
                 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
-            );
+                -sameSite => 'Lax',
+            ));
         }
 
         track_login_daily( $userid );
@@ -1286,16 +1353,17 @@ sub checkauth {
     #
     #
 
+    my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
+
     # get the inputs from the incoming query
     my @inputs = ();
+    my @inputs_to_clean = qw( userid password ticket logout.x otp_token );
     foreach my $name ( param $query) {
-        (next) if ( $name eq 'userid' || $name eq 'password' || $name eq 'ticket' );
+        next if grep { $name eq $_ } @inputs_to_clean;
         my @value = $query->multi_param($name);
         push @inputs, { name => $name, value => $_ } for @value;
     }
 
-    my $patron = Koha::Patrons->find({ userid => $q_userid }); # Not necessary logged in!
-
     my $LibraryNameTitle = C4::Context->preference("LibraryName");
     $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
     $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
@@ -1343,6 +1411,12 @@ sub checkauth {
     $template->param( SCI_login => 1 ) if ( $query->param('sci_user_login') );
     $template->param( OpacPublic => C4::Context->preference("OpacPublic") );
     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
+    if ( $auth_state eq 'additional-auth-needed' ) {
+        $template->param(
+            TwoFA_prompt => 1,
+            invalid_otp_token => $invalid_otp_token,
+        );
+    }
 
     if ( $type eq 'opac' ) {
         require Koha::Virtualshelves;
@@ -1412,7 +1486,8 @@ sub checkauth {
         {   type              => 'text/html',
             charset           => 'utf-8',
             cookie            => $cookie,
-            'X-Frame-Options' => 'SAMEORIGIN'
+            'X-Frame-Options' => 'SAMEORIGIN',
+            -sameSite => 'Lax'
         }
       ),
       $template->output;
@@ -1451,6 +1526,8 @@ Possible return values in C<$status> are:
 
 =item "restricted" -- The IP has changed (if SessionRestrictionByIP)
 
+=item "additional-auth-needed -- User is in an authentication process that is not finished
+
 =back
 
 =cut
@@ -1495,8 +1572,9 @@ sub check_api_auth {
             -value    => $session->id,
             -HttpOnly => 1,
             -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
+            -sameSite => 'Lax'
         );
-        return ( $return, undef, $session );
+        return ( $return, $cookie, $session ); # return == 'ok' here
 
     } else {
 
@@ -1535,6 +1613,7 @@ sub check_api_auth {
                 -value    => $sessionID,
                 -HttpOnly => 1,
                 -secure => ( C4::Context->https_enabled() ? 1 : 0 ),
+                -sameSite => 'Lax'
             );
             if ( $return == 1 ) {
                 my (
@@ -1625,7 +1704,7 @@ sub check_api_auth {
 
 =head2 check_cookie_auth
 
-  ($status, $sessionId) = check_api_auth($cookie, $userflags);
+  ($status, $sessionId) = check_cookie_auth($cookie, $userflags);
 
 Given a CGISESSID cookie set during a previous login to Koha, determine
 if the user has the privileges specified by C<$userflags>. C<$userflags>
@@ -1688,57 +1767,60 @@ sub check_cookie_auth {
     # however, if a userid parameter is present (i.e., from
     # a form submission, assume that any current cookie
     # is to be ignored
-    unless ( defined $sessionID and $sessionID ) {
+    unless ( $sessionID ) {
         return ( "failed", undef );
     }
+    C4::Context::_unset_userenv($sessionID); # remove old userenv first
     my $session   = get_session($sessionID);
-    C4::Context->_new_userenv($sessionID);
     if ($session) {
-        C4::Context->interface($session->param('interface'));
-        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('shibboleth'),
-            $session->param('desk_id'),      $session->param('desk_name'),
-            $session->param('register_id'),  $session->param('register_name')
-        );
-
         my $userid   = $session->param('id');
         my $ip       = $session->param('ip');
         my $lasttime = $session->param('lasttime');
         my $timeout = _timeout_syspref();
 
         if ( !$lasttime || ( $lasttime < time() - $timeout ) ) {
-
             # time out
             $session->delete();
             $session->flush;
-            C4::Context->_unset_userenv($sessionID);
             return ("expired", undef);
-        } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) {
 
+        } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $remote_addr ) {
             # IP address changed
             $session->delete();
             $session->flush;
-            C4::Context->_unset_userenv($sessionID);
             return ( "restricted", undef, { old_ip => $ip, new_ip => $remote_addr});
+
         } elsif ( $userid ) {
             $session->param( 'lasttime', time() );
             my $flags = defined($flagsrequired) ? haspermission( $userid, $flagsrequired ) : 1;
             if ($flags) {
+                C4::Context->_new_userenv($sessionID);
+                C4::Context->interface($session->param('interface'));
+                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('shibboleth'),
+                    $session->param('desk_id'),      $session->param('desk_name'),
+                    $session->param('register_id'),  $session->param('register_name')
+                );
+                return ( "additional-auth-needed", $session )
+                    if $session->param('waiting-for-2FA');
+
                 return ( "ok", $session );
+            } else {
+                $session->delete();
+                $session->flush;
+                return ( "failed", undef );
             }
+
         } else {
+            C4::Context->_new_userenv($sessionID);
+            C4::Context->interface($session->param('interface'));
+            C4::Context->set_userenv( undef, q{} );
             return ( "anon", $session );
         }
-        # If here user was logged in, but doesn't have correct permissions
-        # could be an 'else' at `if($flags) return "ok"` , but left here to catch any errors
-        $session->delete();
-        $session->flush;
-        C4::Context->_unset_userenv($sessionID);
-        return ( "failed", undef );
     } else {
         return ( "expired", undef );
     }
@@ -1784,9 +1866,13 @@ sub _get_session_params {
 sub get_session {
     my $sessionID      = shift;
     my $params = _get_session_params();
-    my $session = CGI::Session->new( $params->{dsn}, $sessionID, $params->{dsn_args} );
-    if ( ! $session ){
-        die CGI::Session->errstr();
+    my $session;
+    if( $sessionID ) { # find existing
+        CGI::Session::ErrorHandler->set_error( q{} ); # clear error, cpan issue #111463
+        $session = CGI::Session->load( $params->{dsn}, $sessionID, $params->{dsn_args} );
+    } else {
+        $session = CGI::Session->new( $params->{dsn}, $sessionID, $params->{dsn_args} );
+        # no need to flush here
     }
     return $session;
 }