Files
Oxicloud/static/js/core/csrf.js
T

31 lines
954 B
JavaScript
Raw Normal View History

2026-04-07 22:48:59 +02:00
/**
* CSRF double-submit cookie utility.
*
* Reads the `oxicloud_csrf` cookie (which is NOT HttpOnly) and provides
* its value as the `X-CSRF-Token` header on mutating requests.
*
* Usage:
* // In any fetch call that changes state:
* fetch(url, { method: 'POST', headers: { ...getCsrfHeaders(), 'Content-Type': 'application/json' } })
*
* The server-side `csrf_middleware` validates that the header value matches
* the cookie for every POST/PUT/DELETE/PATCH request authenticated via
* HttpOnly cookies.
*/
function getCsrfToken() {
const match = document.cookie.split('; ').find((row) => row.startsWith('oxicloud_csrf='));
return match ? match.split('=')[1] : '';
}
2026-05-07 23:40:02 +02:00
/**
* returns headers to add, this includes the X-CSRF-Token
* @returns {Record<String, String>}
*/
2026-04-07 22:48:59 +02:00
function getCsrfHeaders() {
const token = getCsrfToken();
return token ? { 'X-CSRF-Token': token } : {};
}
export { getCsrfHeaders, getCsrfToken };