Skip to content

Commit 8b645da

Browse files
committed
revert!: fetching sanctum csrf cookie automatically
1 parent 812d1d7 commit 8b645da

File tree

4 files changed

+81
-74
lines changed

4 files changed

+81
-74
lines changed

src/httpClient.ts

+1-47
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
import {HttpMethod} from './drivers/default/enums/httpMethod';
22
import {Orion} from './orion';
33
import {AxiosInstance, AxiosRequestConfig, AxiosResponse} from 'axios';
4-
import {AuthDriver} from "./drivers/default/enums/authDriver";
54

65
export class HttpClient {
7-
protected static csrfTokenFetched = false;
8-
9-
constructor(protected baseUrl: string, protected client: AxiosInstance, protected authDriver: AuthDriver) {
6+
constructor(protected baseUrl: string, protected client: AxiosInstance) {
107
this.baseUrl = baseUrl;
118
this.client = client;
12-
this.authDriver = authDriver;
139
}
1410

1511
public async request<Response extends Record<string, unknown>>(
@@ -27,10 +23,6 @@ export class HttpClient {
2723

2824
if (method !== HttpMethod.GET) {
2925
config.data = data;
30-
31-
if (!HttpClient.csrfTokenFetched && this.authDriver === AuthDriver.Sanctum) {
32-
await this.fetchCsrfToken();
33-
}
3426
}
3527

3628
return this.client.request<Response>(config);
@@ -60,44 +52,6 @@ export class HttpClient {
6052
)
6153
}
6254

63-
public async fetchCsrfToken(): Promise<void> {
64-
if (this.authDriver !== AuthDriver.Sanctum) {
65-
throw new Error(
66-
`Current auth driver is set to "${this.authDriver}". Fetching CSRF cookie can only be used with "sanctum" driver.`
67-
);
68-
}
69-
70-
let response = null;
71-
72-
try {
73-
response = await this
74-
.getAxios()
75-
.get(`sanctum/csrf-cookie`, {baseURL: Orion.getBaseUrl()});
76-
} catch (error) {
77-
throw new Error(
78-
`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.`
79-
);
80-
}
81-
82-
const xsrfTokenPresent =
83-
document.cookie
84-
.split(';')
85-
.filter((cookie: string) =>
86-
cookie.includes(this.getAxios().defaults.xsrfCookieName || 'XSRF-TOKEN')
87-
).length > 0;
88-
89-
if (!xsrfTokenPresent) {
90-
console.log(`Response status: ${response.status}`);
91-
console.log(`Response headers:`);
92-
console.log(response.headers);
93-
console.log(`Cookies: ${document.cookie}`);
94-
95-
throw new Error(
96-
`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.`
97-
);
98-
}
99-
}
100-
10155
public getAxios(): AxiosInstance {
10256
return this.client;
10357
}

src/orion.ts

+40-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ export class Orion {
9494
baseUrl = withPrefix ? Orion.getApiUrl() : Orion.getBaseUrl()
9595
}
9696

97-
return new HttpClient(baseUrl, client, this.getAuthDriver());
97+
return new HttpClient(baseUrl, client);
9898
}
9999

100100
public static makeHttpClientUsing(callback: () => AxiosInstance): Orion {
@@ -116,4 +116,43 @@ export class Orion {
116116

117117
return config;
118118
}
119+
120+
public static async csrf(): Promise<void> {
121+
if (this.authDriver !== AuthDriver.Sanctum) {
122+
throw new Error(
123+
`Current auth driver is set to "${this.authDriver}". Fetching CSRF cookie can only be used with "sanctum" driver.`
124+
);
125+
}
126+
127+
const httpClient = Orion.makeHttpClient();
128+
let response = null;
129+
130+
try {
131+
response = await httpClient
132+
.getAxios()
133+
.get(`sanctum/csrf-cookie`, { baseURL: Orion.getBaseUrl() });
134+
} catch (error) {
135+
throw new Error(
136+
`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.`
137+
);
138+
}
139+
140+
const xsrfTokenPresent =
141+
document.cookie
142+
.split(';')
143+
.filter((cookie: string) =>
144+
cookie.includes(httpClient.getAxios().defaults.xsrfCookieName || 'XSRF-TOKEN')
145+
).length > 0;
146+
147+
if (!xsrfTokenPresent) {
148+
console.log(`Response status: ${response.status}`);
149+
console.log(`Response headers:`);
150+
console.log(response.headers);
151+
console.log(`Cookies: ${document.cookie}`);
152+
153+
throw new Error(
154+
`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.`
155+
);
156+
}
157+
}
119158
}

tests/integration/httpClient.test.ts

-26
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { Orion } from '../../src/orion';
22
import makeServer from './drivers/default/server';
33
import { HttpMethod } from '../../src/drivers/default/enums/httpMethod';
4-
import {AuthDriver} from "../../src/drivers/default/enums/authDriver";
54

65
let server: any;
76

@@ -23,29 +22,4 @@ describe('HttpClient tests', () => {
2322
const requests = server.pretender.handledRequests;
2423
expect(requests[0].requestHeaders['Authorization']).toStrictEqual('Bearer test');
2524
});
26-
27-
test('retrieving csrf cookie', async () => {
28-
Orion.setAuthDriver(AuthDriver.Sanctum);
29-
30-
await Orion.makeHttpClient().fetchCsrfToken();
31-
32-
const requests = server.pretender.handledRequests;
33-
expect(requests[0].url).toBe('https://api-mock.test/sanctum/csrf-cookie');
34-
});
35-
36-
test('attempting to fetch csrf cookie with invalid driver', async () => {
37-
Orion.setAuthDriver(AuthDriver.Passport);
38-
39-
try {
40-
await Orion.makeHttpClient().fetchCsrfToken();
41-
expect(false).toBeTruthy();
42-
} catch (error) {
43-
expect(error.message).toBe(
44-
`Current auth driver is set to "${AuthDriver.Passport}". Fetching CSRF cookie can only be used with "sanctum" driver.`
45-
);
46-
}
47-
48-
const requests = server.pretender.handledRequests;
49-
expect(requests).toHaveLength(0);
50-
});
5125
});

tests/integration/orion.test.ts

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import { Orion } from '../../src/orion';
2+
import { AuthDriver } from '../../src/drivers/default/enums/authDriver';
3+
import makeServer from './drivers/default/server';
4+
5+
let server: any;
6+
7+
beforeEach(() => {
8+
server = makeServer();
9+
});
10+
11+
afterEach(() => {
12+
server.shutdown();
13+
});
14+
15+
describe('Orion tests', () => {
16+
test('retrieving csrf cookie', async () => {
17+
Orion.setAuthDriver(AuthDriver.Sanctum);
18+
19+
await Orion.csrf();
20+
21+
const requests = server.pretender.handledRequests;
22+
expect(requests[0].url).toBe('https://api-mock.test/sanctum/csrf-cookie');
23+
});
24+
25+
test('attempting to fetch csrf cookie with invalid driver', async () => {
26+
Orion.setAuthDriver(AuthDriver.Passport);
27+
28+
try {
29+
await Orion.csrf();
30+
expect(false).toBeTruthy();
31+
} catch (error) {
32+
expect(error.message).toBe(
33+
`Current auth driver is set to "${AuthDriver.Passport}". Fetching CSRF cookie can only be used with "sanctum" driver.`
34+
);
35+
}
36+
37+
const requests = server.pretender.handledRequests;
38+
expect(requests).toHaveLength(0);
39+
});
40+
});

0 commit comments

Comments
 (0)