Add CSRF token to event delete fetch() call
All checks were successful
Deploy / deploy (push) Successful in 2m38s
All checks were successful
Deploy / deploy (push) Successful in 2m38s
The delete event functionality uses vanilla fetch() instead of HTMX, so it wasn't getting the x-csrf-token header that the htmx:configRequest listener adds. This caused 403 Forbidden on event deletion. Changes: - Made getCsrfToken() a global window function so it can be used by both HTMX and vanilla fetch() calls - Added x-csrf-token header to the deleteEvent() fetch request 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
@@ -105,15 +105,16 @@ def EventSlideOverScript(): # noqa: N802
|
|||||||
|
|
||||||
|
|
||||||
def CsrfHeaderScript(): # noqa: N802
|
def CsrfHeaderScript(): # noqa: N802
|
||||||
"""JavaScript to inject CSRF token into HTMX requests.
|
"""JavaScript to inject CSRF token into HTMX requests and provide global helper.
|
||||||
|
|
||||||
Reads the csrf_token cookie and adds it as x-csrf-token header
|
Provides a global getCsrfToken() function that reads the csrf_token cookie.
|
||||||
to all HTMX requests. This is required for POST/PUT/DELETE
|
This function is used both by HTMX (via htmx:configRequest) and by any
|
||||||
requests to pass CSRF validation.
|
vanilla fetch() calls that need CSRF protection.
|
||||||
"""
|
"""
|
||||||
return Script("""
|
return Script("""
|
||||||
// Read CSRF token from cookie
|
// Global function to read CSRF token from cookie
|
||||||
function getCsrfToken() {
|
// Used by HTMX config and available for vanilla fetch() calls
|
||||||
|
window.getCsrfToken = function() {
|
||||||
var name = 'csrf_token=';
|
var name = 'csrf_token=';
|
||||||
var cookies = document.cookie.split(';');
|
var cookies = document.cookie.split(';');
|
||||||
for (var i = 0; i < cookies.length; i++) {
|
for (var i = 0; i < cookies.length; i++) {
|
||||||
@@ -123,7 +124,7 @@ def CsrfHeaderScript(): # noqa: N802
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
return '';
|
return '';
|
||||||
}
|
};
|
||||||
|
|
||||||
// Configure HTMX to send CSRF token with all requests
|
// Configure HTMX to send CSRF token with all requests
|
||||||
document.body.addEventListener('htmx:configRequest', function(event) {
|
document.body.addEventListener('htmx:configRequest', function(event) {
|
||||||
|
|||||||
@@ -535,6 +535,7 @@ def delete_script() -> Script:
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/x-www-form-urlencoded',
|
'Content-Type': 'application/x-www-form-urlencoded',
|
||||||
|
'x-csrf-token': getCsrfToken(),
|
||||||
},
|
},
|
||||||
body: 'reason=Deleted via UI'
|
body: 'reason=Deleted via UI'
|
||||||
});
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user