Skip to content

Commit

Permalink
feat: check for xsrf token cookie presence
Browse files Browse the repository at this point in the history
  • Loading branch information
alexzarbn committed Apr 7, 2021
1 parent 651119f commit 83c1052
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 4 deletions.
33 changes: 30 additions & 3 deletions src/orion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,9 +106,36 @@ export class Orion {
);
}

await Orion.makeHttpClient()
.getAxios()
.get(`sanctum/csrf-cookie`, { baseURL: Orion.getHost() });
const httpClient = Orion.makeHttpClient();
let response = null;

try {
response = await httpClient
.getAxios()
.get(`sanctum/csrf-cookie`, { baseURL: Orion.getHost() });
} catch (error) {
throw new Error(
`Unable to retrieve XSRF token cookie due to network error. Please ensure that SANCTUM_STATEFUL_DOMAINS and SESSION_DOMAIN environment variables are configured correctly on the API side.`
);
}

const xsrfTokenPresent =
document.cookie
.split(';')
.filter((cookie: string) =>
cookie.includes(httpClient.getAxios().defaults.xsrfCookieName || 'XSRF-TOKEN')
).length > 0;

if (!xsrfTokenPresent) {
console.log(`Response status: ${response.status}`);
console.log(`Response headers:`);
console.log(response.headers);
console.log(`Cookies: ${document.cookie}`);

throw new Error(
`XSRF token cookie is missing in the response. Please ensure that SANCTUM_STATEFUL_DOMAINS and SESSION_DOMAIN environment variables are configured correctly on the API side.`
);
}
}

protected static buildHttpClientConfig(): AxiosRequestConfig {
Expand Down
3 changes: 3 additions & 0 deletions tests/integration/drivers/default/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ export default function makeServer() {
this.namespace = '';

this.get('/sanctum/csrf-cookie', () => {
const cookieExpiration = new Date(new Date().getTime() + 24 * 3600 * 1000);
document.cookie = `XSRF-TOKEN=test; path=/; expires=${cookieExpiration.toUTCString()};`;

return [];
});

Expand Down
2 changes: 1 addition & 1 deletion tests/integration/orion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ afterEach(() => {
});

describe('Orion tests', () => {
test('fetching csrf cookie', async () => {
test('retrieving csrf cookie', async () => {
Orion.setAuthDriver(AuthDriver.Sanctum);

await Orion.csrf();
Expand Down

0 comments on commit 83c1052

Please sign in to comment.