diff --git a/src/features/auth/authSlice.ts b/src/features/auth/authSlice.ts index c0248cc289..89f490a987 100644 --- a/src/features/auth/authSlice.ts +++ b/src/features/auth/authSlice.ts @@ -1,5 +1,5 @@ import { PayloadAction, createSelector, createSlice } from "@reduxjs/toolkit"; -import { GetSiteResponse, LemmyHttp } from "lemmy-js-client"; +import { GetSiteResponse } from "lemmy-js-client"; import { AppDispatch, RootState } from "../../store"; import Cookies from "js-cookie"; import { LemmyJWT, getRemoteHandle } from "../../helpers/lemmy"; @@ -182,8 +182,10 @@ export const localUserSelector = (state: RootState) => state.auth.site?.my_user?.local_user_view.local_user; export const login = - (client: LemmyHttp, username: string, password: string, totp?: string) => + (baseUrl: string, username: string, password: string, totp?: string) => async (dispatch: AppDispatch) => { + const client = getClient(baseUrl); + const res = await client.login({ username_or_email: username, password, @@ -195,7 +197,9 @@ export const login = throw new Error("broke"); } - const site = await client.getSite({ auth: res.jwt }); + const authenticatedClient = getClient(baseUrl, res.jwt); + + const site = await authenticatedClient.getSite({ auth: res.jwt }); const myUser = site.my_user?.local_user_view?.person; if (!myUser) throw new Error("broke"); @@ -224,7 +228,7 @@ export const getSite = const jwtPayload = jwtPayloadSelector(getState()); const instance = jwtPayload?.iss ?? getState().auth.connectedInstance; - const details = await getClient(instance).getSite({ + const details = await getClient(instance, jwtSelector(getState())).getSite({ auth: jwtSelector(getState()), }); @@ -284,10 +288,13 @@ export const urlSelector = createSelector( }, ); -export const clientSelector = createSelector([urlSelector], (url) => { - // never leak the jwt to the incorrect server - return getClient(url); -}); +export const clientSelector = createSelector( + [urlSelector, jwtSelector], + (url, jwt) => { + // never leak the jwt to the incorrect server + return getClient(url, jwt); + }, +); function updateCredentialsStorage( accounts: CredentialStoragePayload | undefined, diff --git a/src/services/lemmy.ts b/src/services/lemmy.ts index 5052c8cf44..7994e1de35 100644 --- a/src/services/lemmy.ts +++ b/src/services/lemmy.ts @@ -17,11 +17,16 @@ function buildProxiedBaseUrl(url: string): string { return `${location.origin}/api/${url}`; } -export function getClient(url: string): LemmyHttp { +export function getClient(url: string, jwt?: string): LemmyHttp { return new LemmyHttp(buildBaseUrl(url), { // Capacitor http plugin is not compatible with cross-fetch. // Bind to globalThis or lemmy-js-client will bind incorrectly fetchFunction: fetch.bind(globalThis), + headers: { + Authorization: jwt ? `Bearer ${jwt}` : undefined, + } as { + [key: string]: string; + }, }); }