Skip to content

Commit

Permalink
fix: set CSRF header instantly when getting token (#2261)
Browse files Browse the repository at this point in the history
Set axios instance CSRF header instantly when getting token from /me
endpoint as the axios instance might be initialized before there was
CSRF token available.
  • Loading branch information
mjturt committed Sep 13, 2023
1 parent 43caf3e commit 9d8009d
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
6 changes: 4 additions & 2 deletions frontend/benefit/applicant/src/hooks/useUserQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,10 @@ const useUserQuery = (
select: (data) => camelcaseKeys(data, { deep: true }),
onError: (error) => handleError(error),
onSuccess: (data) => {
setLocalStorageItem(LOCAL_STORAGE_KEYS.CSRF_TOKEN, data.csrfToken);
if (data.id && data.termsOfServiceApprovalNeeded)
const { id, csrfToken, termsOfServiceApprovalNeeded } = data;
setLocalStorageItem(LOCAL_STORAGE_KEYS.CSRF_TOKEN, csrfToken);
axios.defaults.headers['X-CSRFToken'] = csrfToken;
if (id && termsOfServiceApprovalNeeded)
setLocalStorageItem(
LOCAL_STORAGE_KEYS.IS_TERMS_OF_SERVICE_APPROVED,
'false'
Expand Down
11 changes: 5 additions & 6 deletions frontend/benefit/handler/src/hooks/useUserQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,6 @@ const useUserQuery = <T extends User>(
}
};

const onSuccessHandler = (user: User): void => {
checkForStaffStatus(user);
setLocalStorageItem(LOCAL_STORAGE_KEYS.CSRF_TOKEN, user.csrf_token);
};

return useQuery(
`${BackendEndpoint.USER_ME}`,
() => handleResponse<User>(axios.get(BackendEndpoint.USER_ME)),
Expand All @@ -60,7 +55,11 @@ const useUserQuery = <T extends User>(
enabled: !logout,
retry: false,
select,
onSuccess: onSuccessHandler,
onSuccess: (user: User): void => {
checkForStaffStatus(user);
setLocalStorageItem(LOCAL_STORAGE_KEYS.CSRF_TOKEN, user.csrf_token);
axios.defaults.headers['X-CSRFToken'] = user.csrf_token;
},
onError: (error) => handleError(error),
}
);
Expand Down

0 comments on commit 9d8009d

Please sign in to comment.