new page thing
This commit is contained in:
44
lib/utils.ts
44
lib/utils.ts
@@ -7,7 +7,10 @@ export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
export async function proxyFetch(
|
||||
/**
|
||||
* ! Do not use in actual code, only used by proxy fetch to fix the CSRF thing
|
||||
*/
|
||||
async function proxyFetchRaw(
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit
|
||||
): Promise<Response> {
|
||||
@@ -15,13 +18,14 @@ export async function proxyFetch(
|
||||
typeof input === "string"
|
||||
? input
|
||||
: input instanceof Request
|
||||
? input.url
|
||||
: "";
|
||||
? input.url
|
||||
: "";
|
||||
|
||||
const proxyUrl = `/api/proxy?url=${encodeURIComponent(url)}`;
|
||||
|
||||
// fix headers
|
||||
// Fix headers
|
||||
const headers = new Headers(init?.headers || {});
|
||||
headers.delete("accept-encoding"); // prevent stupid encoding bug
|
||||
headers.delete("accept-encoding"); // prevent encoding issues
|
||||
|
||||
const fetchInit: RequestInit = {
|
||||
...init,
|
||||
@@ -32,3 +36,33 @@ export async function proxyFetch(
|
||||
|
||||
return window.fetch(proxyUrl, fetchInit);
|
||||
}
|
||||
|
||||
// CSRF-aware proxy fetch
|
||||
export async function proxyFetch(
|
||||
input: RequestInfo | URL,
|
||||
init?: RequestInit
|
||||
): Promise<Response> {
|
||||
const xsrfRequestMethods = ["POST", "PATCH", "DELETE"];
|
||||
const csrfTokenHeader = "x-csrf-token";
|
||||
const csrfInvalidResponseCode = 403;
|
||||
|
||||
const method = init?.method?.toUpperCase() || "GET";
|
||||
|
||||
let response = await proxyFetchRaw(input, init);
|
||||
|
||||
if (
|
||||
xsrfRequestMethods.includes(method) &&
|
||||
response.status === csrfInvalidResponseCode &&
|
||||
response.headers.has(csrfTokenHeader)
|
||||
) {
|
||||
const newHeaders = new Headers(init?.headers || {});
|
||||
newHeaders.set(csrfTokenHeader, response.headers.get(csrfTokenHeader)!);
|
||||
|
||||
response = await proxyFetchRaw(input, {
|
||||
...init,
|
||||
headers: newHeaders
|
||||
});
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user