Skip to content

Commit

Permalink
Add CSRF token to requests when available in cookies (#598)
Browse files Browse the repository at this point in the history
Co-authored-by: Paulus Schoutsen <[email protected]>
  • Loading branch information
jesserockz and balloob authored Mar 19, 2024
1 parent 114612f commit 80c583a
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 0 deletions.
1 change: 1 addition & 0 deletions raw_package/login.template.html
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,7 @@
<h3 id="login-head" class="center">Login</h3>
<p class="center">Enter your {% if ha_addon %}Home Assistant{% else %}ESPHome{% end %} credentials.</p>
<form action="./login" method="post" id="login-form">
{% module xsrf_form_html() %}
{% if has_username or ha_addon %}
<div class="row">
<i class="material-icons prefix">person</i>
Expand Down
9 changes: 9 additions & 0 deletions src/api/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { getCookie } from "../util/cookie";

export class APIError extends Error {
constructor(
message: string,
Expand All @@ -16,6 +18,13 @@ const fetchApiBase = async (
options = {};
}
options.credentials = "same-origin";
const csrfCookie = getCookie("_xsrf");
if (csrfCookie) {
if (!options.headers) {
options.headers = {};
}
options.headers["X-CSRFToken"] = csrfCookie;
}
const resp = await fetch(path, options);
if (!resp.ok) {
throw new APIError(`Request not successful (${resp.status})`, resp.status);
Expand Down
4 changes: 4 additions & 0 deletions src/util/cookie.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export const getCookie = (name: string): string | undefined => {
var r = document.cookie.match("\\b" + name + "=([^;]*)\\b");
return r ? r[1] : undefined;
};

0 comments on commit 80c583a

Please sign in to comment.