Skip to content

Commit

Permalink
Changed app context logic to get CSRF value and reuse it if available
Browse files Browse the repository at this point in the history
  • Loading branch information
mkimberlin committed Nov 5, 2024
1 parent acb6ee4 commit 9b9b43a
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion web-ui/src/context/AppContext.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,17 @@ import {getCertifications} from "../api/certification.js";

const AppContext = React.createContext();

function getSessionCookieValue(name) {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
if (cookie.startsWith(name + '=')) {
return decodeURIComponent(cookie.substring(name.length + 1));
}
}
return null;
}

const AppContextProvider = props => {
const [state, dispatch] = useReducer(
reducer,
Expand Down Expand Up @@ -63,14 +74,17 @@ const AppContextProvider = props => {
const url = `${BASE_API_URL}/csrf/cookie`;
useEffect(() => {
const getCsrf = async () => {
if (!csrf) {
const cookieVal = getSessionCookieValue('_csrf');
if (!csrf && !cookieVal) {
const res = await fetch(url, {
responseType: 'text',
credentials: 'include'
});
if (res && res.ok) {
dispatch({ type: SET_CSRF, payload: await res.text() });
}
} else if (cookieVal) {
dispatch({ type: SET_CSRF, payload: cookieVal });
}
};
getCsrf();
Expand Down

0 comments on commit 9b9b43a

Please sign in to comment.