Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

csrf fixes #2647

Merged
merged 2 commits into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions src/main/resources/static/js/csrf.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
document.addEventListener('DOMContentLoaded', function() {
// Get CSRF token from cookie
const getCsrfToken = () => {
return document.cookie
.split('; ')
.find(row => row.startsWith('XSRF-TOKEN='))
?.split('=')[1];
};

// Function to decode the URI-encoded cookie value
const decodeCsrfToken = (token) => {
if (token) {
return decodeURIComponent(token);
}
return null;
};

// Find all forms and add CSRF token
const forms = document.querySelectorAll('form');
const csrfToken = decodeCsrfToken(getCsrfToken());

// Only proceed if we have a cookie-based token
if (csrfToken) {
forms.forEach(form => {
// Only now remove existing CSRF input fields since we have a new token
const existingCsrfInputs = form.querySelectorAll('input[name="_csrf"]');
existingCsrfInputs.forEach(input => input.remove());

// Create and add new CSRF input field
const csrfInput = document.createElement('input');
csrfInput.type = 'hidden';
csrfInput.name = '_csrf';
csrfInput.value = csrfToken;
form.appendChild(csrfInput);
});
}
});
1 change: 1 addition & 0 deletions src/main/resources/templates/fragments/common.html
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
<script th:src="@{'/js/cacheFormInputs.js'}" th:if="${currentPage != 'home'}"></script>
<script th:src="@{'/js/tab-container.js'}"></script>
<script th:src="@{'/js/darkmode.js'}"></script>
<script th:src="@{'/js/csrf.js'}"></script>
<script th:inline="javascript">
const stirlingPDFLabel = /*[[${@StirlingPDFLabel}]]*/ '';
const analyticsEnabled = /*[[${@analyticsEnabled}]]*/ false;
Expand Down
Loading