From 7702c041e538d9c2111727662efef944d68953b0 Mon Sep 17 00:00:00 2001 From: Dessalines Date: Mon, 4 Dec 2023 22:07:36 -0500 Subject: [PATCH] Move lemmyClient generation into fetchInitialData functions. Fixes #2243 (#2260) * Trying more ssr fixes. #2243 * Try to enforce cross-fetch again. * Try to forward cookies. * Try to forward cookies 2. * Trying a new cross-fetch. * Fixing headers * Fixing some auth issues. * Fixing isBanned. * Fix shutdown. * Pushing up some tries. * Moving lemmyclient building into fetchInitialData functions. --- src/server/handlers/catch-all-handler.tsx | 14 ++------- src/server/index.tsx | 4 +-- src/server/middleware.ts | 4 +-- src/server/utils/has-jwt-cookie.ts | 10 +++---- src/server/utils/set-forwarded-headers.ts | 7 +++++ .../components/community/communities.tsx | 8 ++++- src/shared/components/community/community.tsx | 8 ++++- src/shared/components/home/admin-settings.tsx | 8 ++++- src/shared/components/home/home.tsx | 30 ++++++++++++------- src/shared/components/home/instances.tsx | 8 ++++- src/shared/components/modlog.tsx | 8 ++++- src/shared/components/person/inbox.tsx | 10 +++++-- src/shared/components/person/profile.tsx | 8 ++++- .../person/registration-applications.tsx | 12 ++++++-- src/shared/components/person/reports.tsx | 8 ++++- src/shared/components/person/settings.tsx | 10 +++++-- src/shared/components/post/create-post.tsx | 8 ++++- src/shared/components/post/post.tsx | 8 ++++- .../create-private-message.tsx | 8 ++++- src/shared/components/remote-fetch.tsx | 16 +++++++--- src/shared/components/search.tsx | 10 +++++-- src/shared/interfaces.ts | 5 ++-- src/shared/utils/app/my-auth.ts | 1 + src/shared/utils/roles/is-banned.ts | 13 +------- 24 files changed, 158 insertions(+), 68 deletions(-) diff --git a/src/server/handlers/catch-all-handler.tsx b/src/server/handlers/catch-all-handler.tsx index 59773983..3466f3cc 100644 --- a/src/server/handlers/catch-all-handler.tsx +++ b/src/server/handlers/catch-all-handler.tsx @@ -1,7 +1,6 @@ import { initializeSite, isAuthPath } from "@utils/app"; import { getHttpBaseInternal } from "@utils/env"; import { ErrorPageData } from "@utils/types"; -import * as cookie from "cookie"; import type { Request, Response } from "express"; import { StaticRouter, matchPath } from "inferno-router"; import { renderToString } from "inferno-server"; @@ -20,26 +19,19 @@ import { import { createSsrHtml } from "../utils/create-ssr-html"; import { getErrorPageData } from "../utils/get-error-page-data"; import { setForwardedHeaders } from "../utils/set-forwarded-headers"; -import { authCookieName } from "../../shared/config"; +import { getJwtCookie } from "../utils/has-jwt-cookie"; export default async (req: Request, res: Response) => { try { const activeRoute = routes.find(route => matchPath(req.path, route)); const headers = setForwardedHeaders(req.headers); + const auth = getJwtCookie(req.headers); const client = wrapClient( new LemmyHttp(getHttpBaseInternal(), { headers }), ); - const auth = req.headers.cookie - ? cookie.parse(req.headers.cookie)[authCookieName] - : undefined; - - if (auth) { - headers["Authorization"] = `Bearer ${auth}`; - client.rawClient.setHeaders(headers); - } const { path, url, query } = req; // Get site data first @@ -75,10 +67,10 @@ export default async (req: Request, res: Response) => { if (site && activeRoute?.fetchInitialData) { const initialFetchReq: InitialFetchRequest = { - client, path, query, site, + headers, }; routeData = await activeRoute.fetchInitialData(initialFetchReq); diff --git a/src/server/index.tsx b/src/server/index.tsx index 91bc9052..b3955348 100644 --- a/src/server/index.tsx +++ b/src/server/index.tsx @@ -69,7 +69,7 @@ const signals = { const exit_signal = 128; // Fatal error signal code on Linux systems const exit_timeout = 8000; // Because Docker SIGTERMs after 10 secs -const shutdown = (signal, value) => { +function shutdown(signal: string, value: number) { // TODO: Should set a flag here for the listener to reject any further // incoming connections with a HTTP 503 error while shutting down. // Otherwise the connection count may not reach zero before timeout. @@ -83,7 +83,7 @@ const shutdown = (signal, value) => { ); process.exit(exit_signal + value); }, exit_timeout); -}; +} for (const [signal, value] of Object.entries(signals)) { process.on(signal, () => { diff --git a/src/server/middleware.ts b/src/server/middleware.ts index 2dd43f63..8291f29f 100644 --- a/src/server/middleware.ts +++ b/src/server/middleware.ts @@ -1,6 +1,6 @@ import * as crypto from "crypto"; import type { NextFunction, Request, Response } from "express"; -import { hasJwtCookie } from "./utils/has-jwt-cookie"; +import { getJwtCookie } from "./utils/has-jwt-cookie"; export function setDefaultCsp({ res, @@ -52,7 +52,7 @@ export function setCacheControl( // Static content gets cached publicly for a day caching = "public, max-age=86400"; } else { - if (hasJwtCookie(req)) { + if (getJwtCookie(req.headers)) { caching = "private"; } else { caching = "public, max-age=60"; diff --git a/src/server/utils/has-jwt-cookie.ts b/src/server/utils/has-jwt-cookie.ts index c854e0df..7fd6e594 100644 --- a/src/server/utils/has-jwt-cookie.ts +++ b/src/server/utils/has-jwt-cookie.ts @@ -1,9 +1,9 @@ import * as cookie from "cookie"; -import type { Request } from "express"; import { authCookieName } from "../../shared/config"; +import { IncomingHttpHeaders } from "http"; -export function hasJwtCookie(req: Request): boolean { - return Boolean( - cookie.parse(req.headers.cookie ?? "")[authCookieName]?.length, - ); +export function getJwtCookie(headers: IncomingHttpHeaders): string | undefined { + return headers.cookie + ? cookie.parse(headers.cookie)[authCookieName] // This can actually be undefined + : undefined; } diff --git a/src/server/utils/set-forwarded-headers.ts b/src/server/utils/set-forwarded-headers.ts index 386bd7db..7ef1c9db 100644 --- a/src/server/utils/set-forwarded-headers.ts +++ b/src/server/utils/set-forwarded-headers.ts @@ -1,4 +1,5 @@ import { IncomingHttpHeaders } from "http"; +import { getJwtCookie } from "./has-jwt-cookie"; export function setForwardedHeaders(headers: IncomingHttpHeaders): { [key: string]: string; @@ -21,5 +22,11 @@ export function setForwardedHeaders(headers: IncomingHttpHeaders): { out["x-forwarded-for"] = forwardedFor as string; } + const auth = getJwtCookie(headers); + + if (auth) { + out["Authorization"] = `Bearer ${auth}`; + } + return out; } diff --git a/src/shared/components/community/communities.tsx b/src/shared/components/community/communities.tsx index da57e355..a16d51d5 100644 --- a/src/shared/components/community/communities.tsx +++ b/src/shared/components/community/communities.tsx @@ -11,6 +11,7 @@ import { Component, linkEvent } from "inferno"; import { CommunityResponse, GetSiteResponse, + LemmyHttp, ListCommunities, ListCommunitiesResponse, ListingType, @@ -23,6 +24,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { HtmlTags } from "../common/html-tags"; import { Spinner } from "../common/icon"; @@ -33,6 +35,7 @@ import { CommunityLink } from "./community-link"; import { communityLimit } from "../../config"; import { SubscribeButton } from "../common/subscribe-button"; +import { getHttpBaseInternal } from "../../utils/env"; type CommunitiesData = RouteDataResponse<{ listCommunitiesResponse: ListCommunitiesResponse; @@ -306,11 +309,14 @@ export class Communities extends Component { } static async fetchInitialData({ + headers, query: { listingType, sort, page }, - client, }: InitialFetchRequest< QueryParams >): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const listCommunitiesForm: ListCommunities = { type_: getListingTypeFromQuery(listingType), sort: getSortTypeFromQuery(sort), diff --git a/src/shared/components/community/community.tsx b/src/shared/components/community/community.tsx index 1f4e4416..96b0dec9 100644 --- a/src/shared/components/community/community.tsx +++ b/src/shared/components/community/community.tsx @@ -54,6 +54,7 @@ import { GetPosts, GetPostsResponse, GetSiteResponse, + LemmyHttp, LockPost, MarkCommentReplyAsRead, MarkPersonMentionAsRead, @@ -84,6 +85,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { setupTippy } from "../../tippy"; import { toast } from "../../toast"; @@ -98,6 +100,7 @@ import { SiteSidebar } from "../home/site-sidebar"; import { PostListings } from "../post/post-listings"; import { CommunityLink } from "./community-link"; import { PaginatorCursor } from "../common/paginator-cursor"; +import { getHttpBaseInternal } from "../../utils/env"; type CommunityData = RouteDataResponse<{ communityRes: GetCommunityResponse; @@ -230,12 +233,15 @@ export class Community extends Component< } static async fetchInitialData({ - client, + headers, path, query: { dataType: urlDataType, pageCursor, sort: urlSort }, }: InitialFetchRequest>): Promise< Promise > { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const pathSplit = path.split("/"); const communityName = pathSplit[2]; diff --git a/src/shared/components/home/admin-settings.tsx b/src/shared/components/home/admin-settings.tsx index 26a49fe2..1d2a69e2 100644 --- a/src/shared/components/home/admin-settings.tsx +++ b/src/shared/components/home/admin-settings.tsx @@ -11,6 +11,7 @@ import { EditSite, GetFederatedInstancesResponse, GetSiteResponse, + LemmyHttp, PersonView, } from "lemmy-js-client"; import { InitialFetchRequest } from "../../interfaces"; @@ -21,6 +22,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { toast } from "../../toast"; import { HtmlTags } from "../common/html-tags"; @@ -31,6 +33,7 @@ import { EmojiForm } from "./emojis-form"; import RateLimitForm from "./rate-limit-form"; import { SiteForm } from "./site-form"; import { TaglineForm } from "./tagline-form"; +import { getHttpBaseInternal } from "../../utils/env"; type AdminSettingsData = RouteDataResponse<{ bannedRes: BannedPersonsResponse; @@ -85,8 +88,11 @@ export class AdminSettings extends Component { } static async fetchInitialData({ - client, + headers, }: InitialFetchRequest): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); return { bannedRes: await client.getBannedPersons(), instancesRes: await client.getFederatedInstances(), diff --git a/src/shared/components/home/home.tsx b/src/shared/components/home/home.tsx index a3c94246..524b2a8d 100644 --- a/src/shared/components/home/home.tsx +++ b/src/shared/components/home/home.tsx @@ -52,6 +52,7 @@ import { GetPosts, GetPostsResponse, GetSiteResponse, + LemmyHttp, ListCommunities, ListCommunitiesResponse, ListingType, @@ -84,6 +85,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { setupTippy } from "../../tippy"; import { toast } from "../../toast"; @@ -97,6 +99,7 @@ import { CommunityLink } from "../community/community-link"; import { PostListings } from "../post/post-listings"; import { SiteSidebar } from "./site-sidebar"; import { PaginatorCursor } from "../common/paginator-cursor"; +import { getHttpBaseInternal } from "../../utils/env"; interface HomeState { postsRes: RequestState; @@ -163,18 +166,21 @@ function getDataTypeFromQuery(type?: string): DataType { return type ? DataType[type] : DataType.Post; } -function getListingTypeFromQuery(type?: string): ListingType | undefined { +function getListingTypeFromQuery( + type?: string, + myUserInfo = UserService.Instance.myUserInfo, +): ListingType | undefined { const myListingType = - UserService.Instance.myUserInfo?.local_user_view?.local_user - ?.default_listing_type; + myUserInfo?.local_user_view?.local_user?.default_listing_type; return type ? (type as ListingType) : myListingType; } -function getSortTypeFromQuery(type?: string): SortType { - const mySortType = - UserService.Instance.myUserInfo?.local_user_view?.local_user - ?.default_sort_type; +function getSortTypeFromQuery( + type?: string, + myUserInfo = UserService.Instance.myUserInfo, +): SortType { + const mySortType = myUserInfo?.local_user_view?.local_user?.default_sort_type; return (type ? (type as SortType) : mySortType) ?? "Active"; } @@ -303,15 +309,19 @@ export class Home extends Component { } static async fetchInitialData({ - client, query: { dataType: urlDataType, listingType, pageCursor, sort: urlSort }, site, + headers, }: InitialFetchRequest>): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); + const dataType = getDataTypeFromQuery(urlDataType); const type_ = - getListingTypeFromQuery(listingType) ?? + getListingTypeFromQuery(listingType, site.my_user) ?? site.site_view.local_site.default_post_listing_type; - const sort = getSortTypeFromQuery(urlSort); + const sort = getSortTypeFromQuery(urlSort, site.my_user); let postsRes: RequestState = EMPTY_REQUEST; let commentsRes: RequestState = EMPTY_REQUEST; diff --git a/src/shared/components/home/instances.tsx b/src/shared/components/home/instances.tsx index 40ab420a..e437a4b6 100644 --- a/src/shared/components/home/instances.tsx +++ b/src/shared/components/home/instances.tsx @@ -5,6 +5,7 @@ import { GetFederatedInstancesResponse, GetSiteResponse, Instance, + LemmyHttp, } from "lemmy-js-client"; import classNames from "classnames"; import { relTags } from "../../config"; @@ -15,10 +16,12 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { HtmlTags } from "../common/html-tags"; import { Spinner } from "../common/icon"; import Tabs from "../common/tabs"; +import { getHttpBaseInternal } from "../../utils/env"; type InstancesData = RouteDataResponse<{ federatedInstancesResponse: GetFederatedInstancesResponse; @@ -68,8 +71,11 @@ export class Instances extends Component { } static async fetchInitialData({ - client, + headers, }: InitialFetchRequest): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); return { federatedInstancesResponse: await client.getFederatedInstances(), }; diff --git a/src/shared/components/modlog.tsx b/src/shared/components/modlog.tsx index 825ac47c..729e814b 100644 --- a/src/shared/components/modlog.tsx +++ b/src/shared/components/modlog.tsx @@ -31,6 +31,7 @@ import { GetModlogResponse, GetPersonDetails, GetPersonDetailsResponse, + LemmyHttp, ModAddCommunityView, ModAddView, ModBanFromCommunityView, @@ -52,6 +53,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../services/HttpService"; import { HtmlTags } from "./common/html-tags"; import { Icon, Spinner } from "./common/icon"; @@ -60,6 +62,7 @@ import { Paginator } from "./common/paginator"; import { SearchableSelect } from "./common/searchable-select"; import { CommunityLink } from "./community/community-link"; import { PersonListing } from "./person/person-listing"; +import { getHttpBaseInternal } from "../utils/env"; type FilterType = "mod" | "user"; @@ -1004,11 +1007,14 @@ export class Modlog extends Component< } static async fetchInitialData({ - client, + headers, path, query: { modId: urlModId, page, userId: urlUserId, actionType }, site, }: InitialFetchRequest>): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const pathSplit = path.split("/"); const communityId = getIdFromString(pathSplit[2]); const modId = !site.site_view.local_site.hide_modlog_mod_names diff --git a/src/shared/components/person/inbox.tsx b/src/shared/components/person/inbox.tsx index 98b3410c..3af065c5 100644 --- a/src/shared/components/person/inbox.tsx +++ b/src/shared/components/person/inbox.tsx @@ -42,6 +42,7 @@ import { GetPersonMentionsResponse, GetRepliesResponse, GetSiteResponse, + LemmyHttp, MarkCommentReplyAsRead, MarkPersonMentionAsRead, MarkPrivateMessageAsRead, @@ -69,6 +70,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { toast } from "../../toast"; import { CommentNodes } from "../comment/comment-nodes"; @@ -77,6 +79,7 @@ import { HtmlTags } from "../common/html-tags"; import { Icon, Spinner } from "../common/icon"; import { Paginator } from "../common/paginator"; import { PrivateMessage } from "../private_message/private-message"; +import { getHttpBaseInternal } from "../../utils/env"; enum UnreadOrAll { Unread, @@ -724,8 +727,11 @@ export class Inbox extends Component { } static async fetchInitialData({ - client, + headers, }: InitialFetchRequest): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const sort: CommentSortType = "New"; const empty: EmptyRequestState = EMPTY_REQUEST; let inboxData: InboxData = { @@ -734,7 +740,7 @@ export class Inbox extends Component { repliesRes: empty, }; - if (myAuth()) { + if (headers["Authorization"]) { const [mentionsRes, messagesRes, repliesRes] = await Promise.all([ client.getPersonMentions({ sort, diff --git a/src/shared/components/person/profile.tsx b/src/shared/components/person/profile.tsx index 89ded415..e779d334 100644 --- a/src/shared/components/person/profile.tsx +++ b/src/shared/components/person/profile.tsx @@ -55,6 +55,7 @@ import { GetPersonDetails, GetPersonDetailsResponse, GetSiteResponse, + LemmyHttp, LockPost, MarkCommentReplyAsRead, MarkPersonMentionAsRead, @@ -80,6 +81,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { setupTippy } from "../../tippy"; import { toast } from "../../toast"; @@ -92,6 +94,7 @@ import { UserBadges } from "../common/user-badges"; import { CommunityLink } from "../community/community-link"; import { PersonDetails } from "./person-details"; import { PersonListing } from "./person-listing"; +import { getHttpBaseInternal } from "../../utils/env"; type ProfileData = RouteDataResponse<{ personResponse: GetPersonDetailsResponse; @@ -275,10 +278,13 @@ export class Profile extends Component< } static async fetchInitialData({ - client, + headers, path, query: { page, sort, view: urlView }, }: InitialFetchRequest>): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const pathSplit = path.split("/"); const username = pathSplit[2]; diff --git a/src/shared/components/person/registration-applications.tsx b/src/shared/components/person/registration-applications.tsx index ca6ffbb2..251a109f 100644 --- a/src/shared/components/person/registration-applications.tsx +++ b/src/shared/components/person/registration-applications.tsx @@ -1,4 +1,4 @@ -import { editRegistrationApplication, myAuth, setIsoData } from "@utils/app"; +import { editRegistrationApplication, setIsoData } from "@utils/app"; import { randomStr } from "@utils/helpers"; import { RouteDataResponse } from "@utils/types"; import classNames from "classnames"; @@ -6,6 +6,7 @@ import { Component, linkEvent } from "inferno"; import { ApproveRegistrationApplication, GetSiteResponse, + LemmyHttp, ListRegistrationApplicationsResponse, RegistrationApplicationView, } from "lemmy-js-client"; @@ -17,6 +18,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { setupTippy } from "../../tippy"; import { HtmlTags } from "../common/html-tags"; @@ -24,6 +26,7 @@ import { Spinner } from "../common/icon"; import { Paginator } from "../common/paginator"; import { RegistrationApplication } from "../common/registration-application"; import { UnreadCounterService } from "../../services"; +import { getHttpBaseInternal } from "../../utils/env"; enum UnreadOrAll { Unread, @@ -207,10 +210,13 @@ export class RegistrationApplications extends Component< } static async fetchInitialData({ - client, + headers, }: InitialFetchRequest): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); return { - listRegistrationApplicationsResponse: myAuth() + listRegistrationApplicationsResponse: headers["Authorization"] ? await client.listRegistrationApplications({ unread_only: true, page: 1, diff --git a/src/shared/components/person/reports.tsx b/src/shared/components/person/reports.tsx index c4f6ebbb..c3c59161 100644 --- a/src/shared/components/person/reports.tsx +++ b/src/shared/components/person/reports.tsx @@ -13,6 +13,7 @@ import { CommentReportResponse, CommentReportView, GetSiteResponse, + LemmyHttp, ListCommentReports, ListCommentReportsResponse, ListPostReports, @@ -39,6 +40,7 @@ import { EMPTY_REQUEST, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { CommentReport } from "../comment/comment-report"; import { HtmlTags } from "../common/html-tags"; @@ -47,6 +49,7 @@ import { Paginator } from "../common/paginator"; import { PostReport } from "../post/post-report"; import { PrivateMessageReport } from "../private_message/private-message-report"; import { UnreadCounterService } from "../../services"; +import { getHttpBaseInternal } from "../../utils/env"; enum UnreadOrAll { Unread, @@ -535,8 +538,11 @@ export class Reports extends Component { } static async fetchInitialData({ - client, + headers, }: InitialFetchRequest): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const unresolved_only = true; const page = 1; const limit = fetchLimit; diff --git a/src/shared/components/person/settings.tsx b/src/shared/components/person/settings.tsx index 864c7de6..f5df1c43 100644 --- a/src/shared/components/person/settings.tsx +++ b/src/shared/components/person/settings.tsx @@ -28,6 +28,7 @@ import { GetSiteResponse, Instance, InstanceBlockView, + LemmyHttp, ListingType, LoginResponse, PersonBlockView, @@ -42,6 +43,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { I18NextService, languages } from "../../services/I18NextService"; import { setupTippy } from "../../tippy"; @@ -61,7 +63,8 @@ import { PersonListing } from "./person-listing"; import { InitialFetchRequest } from "../../interfaces"; import TotpModal from "../common/totp-modal"; import { LoadingEllipses } from "../common/loading-ellipses"; -import { updateDataBsTheme } from "@utils/browser"; +import { updateDataBsTheme } from "../../utils/browser"; +import { getHttpBaseInternal } from "../../utils/env"; type SettingsData = RouteDataResponse<{ instancesRes: GetFederatedInstancesResponse; @@ -332,8 +335,11 @@ export class Settings extends Component { } static async fetchInitialData({ - client, + headers, }: InitialFetchRequest): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); return { instancesRes: await client.getFederatedInstances(), }; diff --git a/src/shared/components/post/create-post.tsx b/src/shared/components/post/create-post.tsx index bd5b3edf..d1b8ee09 100644 --- a/src/shared/components/post/create-post.tsx +++ b/src/shared/components/post/create-post.tsx @@ -9,6 +9,7 @@ import { GetCommunity, GetCommunityResponse, GetSiteResponse, + LemmyHttp, ListCommunitiesResponse, } from "lemmy-js-client"; import { InitialFetchRequest, PostFormParams } from "../../interfaces"; @@ -18,10 +19,12 @@ import { HttpService, RequestState, WrappedLemmyHttp, + wrapClient, } from "../../services/HttpService"; import { HtmlTags } from "../common/html-tags"; import { Spinner } from "../common/icon"; import { PostForm } from "./post-form"; +import { getHttpBaseInternal } from "../../utils/env"; export interface CreatePostProps { communityId?: number; @@ -236,11 +239,14 @@ export class CreatePost extends Component< } static async fetchInitialData({ - client, + headers, query: { communityId }, }: InitialFetchRequest< QueryParams >): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const data: CreatePostData = { initialCommunitiesRes: await fetchCommunitiesForOptions(client), communityResponse: EMPTY_REQUEST, diff --git a/src/shared/components/post/post.tsx b/src/shared/components/post/post.tsx index dec29907..b0d3a022 100644 --- a/src/shared/components/post/post.tsx +++ b/src/shared/components/post/post.tsx @@ -59,6 +59,7 @@ import { GetPost, GetPostResponse, GetSiteResponse, + LemmyHttp, LockPost, MarkCommentReplyAsRead, PostResponse, @@ -86,6 +87,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { setupTippy } from "../../tippy"; import { toast } from "../../toast"; @@ -95,6 +97,7 @@ import { HtmlTags } from "../common/html-tags"; import { Icon, Spinner } from "../common/icon"; import { Sidebar } from "../community/sidebar"; import { PostListing } from "./post-listing"; +import { getHttpBaseInternal } from "../../utils/env"; const commentsShownInterval = 15; @@ -231,9 +234,12 @@ export class Post extends Component { } static async fetchInitialData({ - client, + headers, path, }: InitialFetchRequest): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const pathSplit = path.split("/"); const pathType = pathSplit.at(1); diff --git a/src/shared/components/private_message/create-private-message.tsx b/src/shared/components/private_message/create-private-message.tsx index 7c04771f..fab9f112 100644 --- a/src/shared/components/private_message/create-private-message.tsx +++ b/src/shared/components/private_message/create-private-message.tsx @@ -6,6 +6,7 @@ import { GetPersonDetails, GetPersonDetailsResponse, GetSiteResponse, + LemmyHttp, } from "lemmy-js-client"; import { InitialFetchRequest } from "../../interfaces"; import { FirstLoadService, I18NextService } from "../../services"; @@ -14,11 +15,13 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../../services/HttpService"; import { toast } from "../../toast"; import { HtmlTags } from "../common/html-tags"; import { Spinner } from "../common/icon"; import { PrivateMessageForm } from "./private-message-form"; +import { getHttpBaseInternal } from "../../utils/env"; type CreatePrivateMessageData = RouteDataResponse<{ recipientDetailsResponse: GetPersonDetailsResponse; @@ -65,9 +68,12 @@ export class CreatePrivateMessage extends Component< } static async fetchInitialData({ - client, + headers, path, }: InitialFetchRequest): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const person_id = Number(path.split("/").pop()); const form: GetPersonDetails = { diff --git a/src/shared/components/remote-fetch.tsx b/src/shared/components/remote-fetch.tsx index 38b58720..bd1ec716 100644 --- a/src/shared/components/remote-fetch.tsx +++ b/src/shared/components/remote-fetch.tsx @@ -2,13 +2,18 @@ import { setIsoData } from "@utils/app"; import { getQueryParams } from "@utils/helpers"; import { QueryParams, RouteDataResponse } from "@utils/types"; import { Component, linkEvent } from "inferno"; -import { CommunityView, ResolveObjectResponse } from "lemmy-js-client"; +import { + CommunityView, + LemmyHttp, + ResolveObjectResponse, +} from "lemmy-js-client"; import { InitialFetchRequest } from "../interfaces"; import { FirstLoadService, HttpService, I18NextService } from "../services"; import { EMPTY_REQUEST, LOADING_REQUEST, RequestState, + wrapClient, } from "../services/HttpService"; import { HtmlTags } from "./common/html-tags"; import { Spinner } from "./common/icon"; @@ -16,6 +21,7 @@ import { LoadingEllipses } from "./common/loading-ellipses"; import { PictrsImage } from "./common/pictrs-image"; import { SubscribeButton } from "./common/subscribe-button"; import { CommunityLink } from "./community/community-link"; +import { getHttpBaseInternal } from "../utils/env"; interface RemoteFetchProps { uri?: string; @@ -206,15 +212,17 @@ export class RemoteFetch extends Component { } static async fetchInitialData({ - auth, - client, + headers, query: { uri }, }: InitialFetchRequest< QueryParams >): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const data: RemoteFetchData = { resolveObjectRes: EMPTY_REQUEST }; - if (uri && auth) { + if (uri && headers["Authorization"]) { data.resolveObjectRes = await client.resolveObject({ q: uriToQuery(uri), }); diff --git a/src/shared/components/search.tsx b/src/shared/components/search.tsx index 946c81f0..716b2de1 100644 --- a/src/shared/components/search.tsx +++ b/src/shared/components/search.tsx @@ -34,6 +34,7 @@ import { GetPersonDetails, GetPersonDetailsResponse, GetSiteResponse, + LemmyHttp, ListCommunitiesResponse, ListingType, PersonView, @@ -53,6 +54,7 @@ import { HttpService, LOADING_REQUEST, RequestState, + wrapClient, } from "../services/HttpService"; import { CommentNodes } from "./comment/comment-nodes"; import { HtmlTags } from "./common/html-tags"; @@ -64,6 +66,7 @@ import { SortSelect } from "./common/sort-select"; import { CommunityLink } from "./community/community-link"; import { PersonListing } from "./person/person-listing"; import { PostListing } from "./post/post-listing"; +import { getHttpBaseInternal } from "../utils/env"; interface SearchProps { q?: string; @@ -386,9 +389,12 @@ export class Search extends Component { } static async fetchInitialData({ - client, + headers, query: { communityId, creatorId, q, type, sort, listingType, page }, }: InitialFetchRequest>): Promise { + const client = wrapClient( + new LemmyHttp(getHttpBaseInternal(), { headers }), + ); const community_id = getIdFromString(communityId); let communityResponse: RequestState = EMPTY_REQUEST; if (community_id) { @@ -435,7 +441,7 @@ export class Search extends Component { }; searchResponse = await client.search(form); - if (myAuth()) { + if (headers["Authorization"]) { const resolveObjectForm: ResolveObject = { q: query, }; diff --git a/src/shared/interfaces.ts b/src/shared/interfaces.ts index 3968d753..304e3d9d 100644 --- a/src/shared/interfaces.ts +++ b/src/shared/interfaces.ts @@ -1,7 +1,7 @@ import { ErrorPageData } from "@utils/types"; import { CommentView, GetSiteResponse } from "lemmy-js-client"; import type { ParsedQs } from "qs"; -import { RequestState, WrappedLemmyHttp } from "./services/HttpService"; +import { RequestState } from "./services/HttpService"; /** * This contains serialized data, it needs to be deserialized before use. @@ -25,11 +25,10 @@ declare global { } export interface InitialFetchRequest { - client: WrappedLemmyHttp; path: string; query: T; site: GetSiteResponse; - auth?: string; + headers: { [key: string]: string }; } export interface PostFormParams { diff --git a/src/shared/utils/app/my-auth.ts b/src/shared/utils/app/my-auth.ts index d536d8a2..ada60cdb 100644 --- a/src/shared/utils/app/my-auth.ts +++ b/src/shared/utils/app/my-auth.ts @@ -1,5 +1,6 @@ import { UserService } from "../../services"; +// Warning, do not use this in fetchInitialData export default function myAuth(): string | undefined { return UserService.Instance.auth(); } diff --git a/src/shared/utils/roles/is-banned.ts b/src/shared/utils/roles/is-banned.ts index d71f6f4f..0e4628a1 100644 --- a/src/shared/utils/roles/is-banned.ts +++ b/src/shared/utils/roles/is-banned.ts @@ -1,16 +1,5 @@ import { Person } from "lemmy-js-client"; export default function isBanned(ps: Person): boolean { - const expires = ps.ban_expires; - // Add Z to convert from UTC date - // TODO this check probably isn't necessary anymore - if (expires) { - if (ps.banned && new Date(expires + "Z") > new Date()) { - return true; - } else { - return false; - } - } else { - return ps.banned; - } + return ps.banned; }