From 1dd923b861b086ee423e91e83b9b5b41a303739d Mon Sep 17 00:00:00 2001
From: Jonathan Druart <jonathan.druart@bugs.koha-community.org>
Date: Fri, 4 Aug 2023 11:32:27 +0200
Subject: [PATCH] Bug 34478: Check CSRF in get_template_and_user

Not sure this is the right place in get_template_and_user
Will have to test login and 2FA
---
 C4/Auth.pm | 26 +++++++++++++++++++++++++-
 1 file changed, 25 insertions(+), 1 deletion(-)

diff --git a/C4/Auth.pm b/C4/Auth.pm
index 9b298eed878..1158da4fa84 100644
--- a/C4/Auth.pm
+++ b/C4/Auth.pm
@@ -947,6 +947,8 @@ sub checkauth {
         }
     }
 
+    my $request_method = $query->request_method // q{};
+
     if ( $auth_state eq 'failed' || $logout ) {
         $sessionID = undef;
         $userid    = undef;
@@ -1089,7 +1091,6 @@ sub checkauth {
                 }
                 else {
                     my $retuserid;
-                    my $request_method = $query->request_method // q{};
 
                     if (
                         $request_method eq 'POST'
@@ -1468,6 +1469,29 @@ sub checkauth {
         }
     }
 
+    if ( $auth_state eq 'completed' && defined $query->param('op') ) {
+        die "Cannot use GET for this request"
+            if $request_method ne 'POST';
+
+        print $query->header(
+            {
+                type              => 'text/html',
+                charset           => 'utf-8',
+                cookie            => $cookie,
+                'X-Frame-Options' => 'SAMEORIGIN',
+                -sameSite         => 'Lax'
+            }
+        );
+
+        output_and_exit( $query, $cookie, $template, 'wrong_csrf_token' )
+            unless Koha::Token->new->check_csrf(
+                {
+                    session_id => scalar $query->cookie('CGISESSID'),
+                    token      => scalar $query->param('csrf_token'),
+                }
+            );
+    }
+
     $template->param(
         LibraryName => C4::Context->preference("LibraryName"),
     );
-- 
2.25.1