diff --git a/src/auth.tsx b/src/auth.tsx index fc12f28..4028f3e 100644 --- a/src/auth.tsx +++ b/src/auth.tsx @@ -62,7 +62,7 @@ interface GuestState { authenticated: Authed.GUEST; login: () => void; } -type AuthState = +export type AuthState = | AuthenticatedState | UnAuthenticatedState | LoadingState diff --git a/src/screens/media/media.tsx b/src/screens/media/media.tsx index 03bcbb5..df44c4b 100644 --- a/src/screens/media/media.tsx +++ b/src/screens/media/media.tsx @@ -15,7 +15,7 @@ enum Page { export default function MediaScreen() { const authState = useContext(AuthContext); - const [api, setApi] = useAtom(apiAtom); + const [_api, setApi] = useAtom(apiAtom); const [page, setPage] = useState(Page.ALBUMS); const theme = useTheme(); @@ -24,9 +24,7 @@ export default function MediaScreen() { return setApi(null); } - authState.token.then((token) => { - setApi(getApi(token)); - }); + setApi(getApi(authState)); }, [authState]); return ( diff --git a/src/stores/media.ts b/src/stores/media.ts index 425d083..e11d28b 100644 --- a/src/stores/media.ts +++ b/src/stores/media.ts @@ -1,17 +1,27 @@ import { atom } from "jotai"; import { Api } from "../__generated__/media"; +import { Authed, AuthState } from "../auth"; export const apiAtom = atom | null>(null); -export function getApi(token: string) { +export function getApi(authState: AuthState) { return new Api({ baseUrl: "https://media.djoamersfoort.nl/api", baseApiParams: { credentials: "same-origin", - headers: { - authorization: `Bearer ${token}`, - }, redirect: "follow", referrerPolicy: "no-referrer", }, + async customFetch(...fetchParams: Parameters) { + if (authState.authenticated !== Authed.AUTHENTICATED) + throw new Error("Unauthenticated"); + if (!fetchParams[1]) fetchParams[1] = {}; + if (!fetchParams[1].headers) fetchParams[1].headers = {}; + + Object.assign(fetchParams[1].headers, { + authorization: `Bearer ${await authState.token}`, + }); + + return fetch(...fetchParams); + }, }); }