Bug 30524: (QA follow-up) Only generate CSRF token if it will be used

This patch avoids generating CSRF tokens unless the csrf-token.inc file
is included in the template.

Passed token doesn't need HTML escaped. The docs for WWW::CSRF state:
  The returned CSRF token is in a text-only form suitable for inserting into a HTML form without further escaping (assuming you did not send in strange things to the Time option).

Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
(cherry picked from commit ddf1eb6cef14da365675890920ff72f010c59527)
Signed-off-by: Fridolin Somers <fridolin.somers@biblibre.com>
(cherry picked from commit 73ca151686b682aaa2b950ccbc89fcec14514112)
Signed-off-by: Matt Blenkinsop <matt.blenkinsop@ptfs-europe.com>
(cherry picked from commit b1bd7ec29a)
This commit is contained in:
Kyle M Hall 2023-07-27 07:45:57 -04:00 committed by Wainui Witika-Park
parent c922f7304b
commit e038ec2709
3 changed files with 30 additions and 2 deletions

View File

@ -303,7 +303,6 @@ sub get_template_and_user {
$template->param( loggedinusernumber => $borrowernumber ); # FIXME Should be replaced with logged_in_user.borrowernumber
$template->param( logged_in_user => $patron );
$template->param( sessionID => $sessionID );
$template->param( csrf_token => Koha::Token->new->generate_csrf({ session_id => scalar $sessionID }));
if ( $in->{'type'} eq 'opac' ) {
require Koha::Virtualshelves;

View File

@ -22,6 +22,7 @@ use Modern::Perl;
use base qw( Template::Plugin );
use C4::Context;
use Koha::Token;
use Koha;
=head1 NAME
@ -48,8 +49,22 @@ is necessary.
=head2 Class Methods
=head3 new
This new method allows us to store the context which gives us
access to the template vars already set. In particular this gives
us access to the template vars set by C4::Auth::get_template_and_user
=cut
sub new {
my ( $class, $context ) = @_;
bless {
_CONTEXT => $context,
}, $class;
}
sub Preference {
my ( $self, $pref ) = @_;
return C4::Context->preference( $pref );
@ -84,4 +99,16 @@ sub Version {
};
}
=head3 GenerateCSRF
Generate a new CSRF token.
=cut
sub GenerateCSRF {
my ($self) = @_;
my $session_id = $self->{_CONTEXT}->stash->{sessionID};
return Koha::Token->new->generate_csrf( { session_id => scalar $session_id } );
}
1;

View File

@ -1 +1,3 @@
<input type="hidden" name="csrf_token" value="[% csrf_token | html %]" />
[%- USE Koha %]
[%- USE raw %]
<input type="hidden" name="csrf_token" value="[% Koha.GenerateCSRF | $raw %]" />