Skip to content

Commit

Permalink
Fix CSRF when CSRF_USE_SESSIONS is enabled (#619)
Browse files Browse the repository at this point in the history
The front-end currently checks for the
`input[name="csrfmiddlewaretoken"]` element if `CSRF_COOKIE_HTTPONLY` is
set, but according to the [Django docs], it should do the same thing if
`CSRF_USE_SESSIONS` is set, as it will also mean the token is not
available in a cookie.

[Django docs]: https://docs.djangoproject.com/en/5.0/howto/csrf/#acquiring-the-token-if-csrf-use-sessions-or-csrf-cookie-httponly-is-true
  • Loading branch information
cpmsmith authored May 22, 2024
1 parent a5d678b commit 1d30c93
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 4 deletions.
4 changes: 2 additions & 2 deletions explorer/src/js/csrf.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import cookie from "cookiejs";

const csrfCookieName = document.getElementById('csrfCookieName').value;
const csrfCookieHttpOnly = document.getElementById('csrfCookieHttpOnly').value === "True";
const csrfTokenInDOM = document.getElementById('csrfTokenInDOM').value === "True";

export function getCsrfToken() {
if (csrfCookieHttpOnly) {
if (csrfTokenInDOM) {
let csrfInput = document.querySelector('input[name="csrfmiddlewaretoken"]');
return csrfInput ? csrfInput.value : null;
}
Expand Down
2 changes: 1 addition & 1 deletion explorer/templates/explorer/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

<body>
<input type="hidden" id="csrfCookieName" value="{% firstof csrf_cookie_name 'csrftoken' %}">
<input type="hidden" id="csrfCookieHttpOnly" value="{% firstof csrf_cookie_httponly False %}">
<input type="hidden" id="csrfTokenInDOM" value="{% firstof csrf_token_in_dom False %}">
<input type="hidden" id="clientRoute" value="{{ request.resolver_match.url_name }}">
{% if vite_dev_mode %}
<div class="vite-not-running-canary" style="text-align:center;">
Expand Down
2 changes: 1 addition & 1 deletion explorer/views/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def gen_ctx(self):
),
"assistant_enabled": app_settings.EXPLORER_AI_API_KEY is not None,
"csrf_cookie_name": settings.CSRF_COOKIE_NAME,
"csrf_cookie_httponly": settings.CSRF_COOKIE_HTTPONLY,
"csrf_token_in_dom": settings.CSRF_COOKIE_HTTPONLY or settings.CSRF_USE_SESSIONS,
"view_name": self.request.resolver_match.view_name,
}

Expand Down

0 comments on commit 1d30c93

Please sign in to comment.