Files
Ivan Starkov 9348ce0af0 fix: Image upload via share link (#4083)
## Description

Use authToken token implicitly. Except queue cases like image upload and
patches.

## Steps for reproduction

Open any project with build or admin share link, upload image.

https://p-a82eaa2b-698e-4d3f-aa46-d4f3eee05fe0-dot-img-fix.development.webstudio.is/?authToken=a74ddf79-2638-47af-9dd1-e62f78187a8d&mode=edit

<img width="1025" alt="image"
src="https://github.com/user-attachments/assets/1de48271-f8c3-4df8-aa51-e61d74eb5c32">


## Code Review

- [ ] hi @kof, I need you to do
  - conceptual review (architecture, feature-correctness)
  - detailed review (read every line)
  - test it on preview

## Before requesting a review

- [ ] made a self-review
- [ ] added inline comments where things may be not obvious (the "why",
not "what")

## Before merging

- [ ] tested locally and on preview environment (preview dev login:
5de6)
- [ ] updated [test
cases](https://github.com/webstudio-is/webstudio/blob/main/apps/builder/docs/test-cases.md)
document
- [ ] added tests
- [ ] if any new env variables are added, added them to `.env` file
2024-09-07 18:43:03 +03:00

39 lines
1.2 KiB
TypeScript

import { toast } from "@webstudio-is/design-system";
import { csrfToken } from "./csrf.client";
import { $authToken } from "./nano-states";
/**
* To avoid fetch interception from the canvas, i.e., `globalThis.fetch = () => console.log('INTERCEPTED');`,
*/
const _fetch = globalThis.fetch;
/**
* To avoid fetch interception from the canvas, i.e., `globalThis.fetch = () => console.log('INTERCEPTED');`,
* To add csrf token to the headers.
*/
export const fetch: typeof globalThis.fetch = (requestInfo, requestInit) => {
if (csrfToken === undefined) {
toast.error("CSRF token is not set.");
throw new Error("CSRF token is not set.");
}
const headers = new Headers(requestInit?.headers);
headers.set("X-CSRF-Token", csrfToken);
const authToken = $authToken.get();
// Do not override the existing x-auth-token header.
// As some mutations are queue based and they need to be authenticated with the same token as in the queue.
if (authToken !== undefined && headers.get("x-auth-token") === null) {
headers.set("x-auth-token", authToken);
}
const modifiedInit: RequestInit = {
...requestInit,
headers,
};
return _fetch(requestInfo, modifiedInit);
};