perf upgrade
This commit is contained in:
+21
-140
@@ -3,100 +3,20 @@ import {
|
||||
createServerFn,
|
||||
createServerOnlyFn,
|
||||
} from "@tanstack/react-start";
|
||||
import { getRequest, setResponseHeader } from "@tanstack/react-start/server";
|
||||
import { redirect as redirect } from "@tanstack/react-router";
|
||||
import UserRoles from "supertokens-node/recipe/userroles";
|
||||
import UserMetadata from "supertokens-node/recipe/usermetadata";
|
||||
import { getSessionForStart } from "@/lib/supertokens/recipes/start-session";
|
||||
import { getRequest } from "@tanstack/react-start/server";
|
||||
import { Logger } from "@/lib/logger";
|
||||
import z from "zod";
|
||||
import { serverFnLoggingMiddleware } from "./activities";
|
||||
import { pbAdmin } from "@/lib/pocketbase/client";
|
||||
|
||||
const logger = new Logger("Middleware");
|
||||
|
||||
export const PUBLIC_ROUTES = ["/login", "/logout", "/refresh-session"];
|
||||
|
||||
const verifySuperTokensSession = async (
|
||||
request: Request
|
||||
) => {
|
||||
let session = await getSessionForStart(request, { sessionRequired: false });
|
||||
|
||||
if (session?.needsRefresh) {
|
||||
logger.info("Session needs refresh - redirecting to client");
|
||||
return { context: { session: { tryRefresh: true } } };
|
||||
export const getSessionContext = createServerOnlyFn(
|
||||
async (request: Request, options?: { isServerFunction?: boolean }) => {
|
||||
const { getSessionContextCore } = await import("./supertokens-core.server");
|
||||
return getSessionContextCore(request, options);
|
||||
}
|
||||
|
||||
const userAuthId = session?.userId;
|
||||
|
||||
if (!userAuthId || !session) {
|
||||
logger.info("No authenticated user");
|
||||
return { context: { userAuthId: null, roles: [] } };
|
||||
}
|
||||
|
||||
const { roles } = await fetchUserRoles(userAuthId);
|
||||
const { metadata } = await UserMetadata.getUserMetadata(userAuthId);
|
||||
|
||||
return {
|
||||
context: {
|
||||
userAuthId,
|
||||
roles,
|
||||
metadata,
|
||||
phone: session.phone,
|
||||
session: {
|
||||
accessTokenPayload: session.accessTokenPayload,
|
||||
sessionHandle: session.sessionHandle,
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
export const getSessionContext = createServerOnlyFn(async (request: Request, options?: { isServerFunction?: boolean }) => {
|
||||
const session = await verifySuperTokensSession(request);
|
||||
|
||||
if (session.context.session?.tryRefresh) {
|
||||
if (options?.isServerFunction) {
|
||||
throw new Error("SESSION_REFRESH_REQUIRED");
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
|
||||
if (PUBLIC_ROUTES.some((route) => url.pathname.startsWith(route))) {
|
||||
throw new Error("Unauthenticated");
|
||||
}
|
||||
|
||||
const from = url.pathname + url.search;
|
||||
|
||||
throw redirect({
|
||||
to: "/refresh-session",
|
||||
search: from === "/" ? {} : { redirect: from },
|
||||
});
|
||||
}
|
||||
|
||||
if (!session.context.userAuthId) {
|
||||
logger.error("Unauthenticated user", session.context);
|
||||
throw new Error("Unauthenticated");
|
||||
}
|
||||
|
||||
const context = {
|
||||
userAuthId: session.context.userAuthId,
|
||||
roles: session.context.roles,
|
||||
metadata: session.context.metadata,
|
||||
phone: session.context.phone
|
||||
};
|
||||
|
||||
try {
|
||||
const player = await pbAdmin.getPlayerByAuthId(session.context.userAuthId);
|
||||
if (player) {
|
||||
await pbAdmin.updatePlayer(player.id, {
|
||||
last_activity: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error("Failed to update player last_activity", error);
|
||||
}
|
||||
|
||||
return context;
|
||||
});
|
||||
);
|
||||
|
||||
export const superTokensRequestMiddleware = createMiddleware({
|
||||
type: "request",
|
||||
@@ -109,18 +29,18 @@ export const superTokensFunctionMiddleware = createMiddleware({
|
||||
type: "function",
|
||||
}).server(async ({ next }) => {
|
||||
const request = getRequest();
|
||||
|
||||
|
||||
try {
|
||||
const context = await getSessionContext(request, { isServerFunction: true });
|
||||
return next({ context });
|
||||
} catch (error: any) {
|
||||
if (error.message === "SESSION_REFRESH_REQUIRED") {
|
||||
throw new Response(
|
||||
JSON.stringify({
|
||||
JSON.stringify({
|
||||
error: "SESSION_REFRESH_REQUIRED",
|
||||
message: "Session needs to be refreshed"
|
||||
message: "Session needs to be refreshed"
|
||||
}),
|
||||
{
|
||||
{
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
}
|
||||
@@ -134,7 +54,7 @@ export const superTokensAdminFunctionMiddleware = createMiddleware({
|
||||
type: "function",
|
||||
}).server(async ({ next }) => {
|
||||
const request = getRequest();
|
||||
|
||||
|
||||
try {
|
||||
const context = await getSessionContext(request, { isServerFunction: true });
|
||||
|
||||
@@ -147,11 +67,11 @@ export const superTokensAdminFunctionMiddleware = createMiddleware({
|
||||
} catch (error: any) {
|
||||
if (error.message === "SESSION_REFRESH_REQUIRED") {
|
||||
throw new Response(
|
||||
JSON.stringify({
|
||||
JSON.stringify({
|
||||
error: "SESSION_REFRESH_REQUIRED",
|
||||
message: "Session needs to be refreshed"
|
||||
message: "Session needs to be refreshed"
|
||||
}),
|
||||
{
|
||||
{
|
||||
status: 401,
|
||||
headers: { "Content-Type": "application/json" }
|
||||
}
|
||||
@@ -161,13 +81,8 @@ export const superTokensAdminFunctionMiddleware = createMiddleware({
|
||||
}
|
||||
});
|
||||
|
||||
export const fetchUserRoles = async (userAuthId: string) => {
|
||||
const response = await UserRoles.getRolesForUser("public", userAuthId);
|
||||
return response;
|
||||
};
|
||||
|
||||
export const setUserMetadata = createServerFn({ method: "POST" })
|
||||
.inputValidator(
|
||||
.validator(
|
||||
z
|
||||
.object({
|
||||
first_name: z
|
||||
@@ -195,7 +110,11 @@ export const setUserMetadata = createServerFn({ method: "POST" })
|
||||
const { userAuthId, metadata } = context;
|
||||
if (!userAuthId) return;
|
||||
|
||||
await UserMetadata.updateUserMetadata(userAuthId, {
|
||||
const { updateUserMetadataFields } = await import(
|
||||
"./supertokens-core.server"
|
||||
);
|
||||
|
||||
await updateUserMetadataFields(userAuthId, {
|
||||
first_name: data.first_name,
|
||||
last_name: data.last_name,
|
||||
player_id: data.player_id,
|
||||
@@ -208,41 +127,3 @@ export const setUserMetadata = createServerFn({ method: "POST" })
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const updateUserColorScheme = createServerFn({ method: "POST" })
|
||||
.inputValidator((data: string) => data)
|
||||
.middleware([superTokensFunctionMiddleware, serverFnLoggingMiddleware])
|
||||
.handler(async ({ context, data }) => {
|
||||
const { userAuthId, metadata } = context;
|
||||
if (!userAuthId) return;
|
||||
|
||||
await UserMetadata.updateUserMetadata(userAuthId, {
|
||||
colorScheme: data,
|
||||
});
|
||||
|
||||
return {
|
||||
metadata: {
|
||||
...metadata,
|
||||
colorScheme: data,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
export const updateUserAccentColor = createServerFn({ method: "POST" })
|
||||
.inputValidator((data: string) => data)
|
||||
.middleware([superTokensFunctionMiddleware, serverFnLoggingMiddleware])
|
||||
.handler(async ({ context, data }) => {
|
||||
const { userAuthId, metadata } = context;
|
||||
if (!userAuthId) return;
|
||||
|
||||
await UserMetadata.updateUserMetadata(userAuthId, {
|
||||
accentColor: data,
|
||||
});
|
||||
|
||||
return {
|
||||
metadata: {
|
||||
...metadata,
|
||||
accentColor: data,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user