refresh test

This commit is contained in:
yohlo
2025-09-13 00:50:41 -05:00
parent a926dcde07
commit 7d3c0a3fa4
6 changed files with 102 additions and 23 deletions

View File

@@ -70,10 +70,14 @@ export const verifySuperTokensSession = async (
};
};
export const getSessionContext = async (request: Request): Promise<any> => {
export const getSessionContext = async (request: Request, options?: { isServerFunction?: boolean }): Promise<any> => {
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);
const from = encodeURIComponent(url.pathname + url.search);
throw redirect({
@@ -107,22 +111,56 @@ export const superTokensFunctionMiddleware = createMiddleware({
type: "function",
}).server(async ({ next, response }) => {
const request = getWebRequest();
const context = await getSessionContext(request);
return next({ context });
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({
error: "SESSION_REFRESH_REQUIRED",
message: "Session needs to be refreshed"
}),
{
status: 401,
headers: { "Content-Type": "application/json" }
}
);
}
throw error;
}
});
export const superTokensAdminFunctionMiddleware = createMiddleware({
type: "function",
}).server(async ({ next }) => {
const request = getWebRequest();
const context = await getSessionContext(request);
try {
const context = await getSessionContext(request, { isServerFunction: true });
if (context.roles?.includes("Admin")) {
return next({ context });
if (context.roles?.includes("Admin")) {
return next({ context });
}
logger.error("Unauthorized user in admin function.", context);
throw new Error("Unauthorized");
} catch (error: any) {
if (error.message === "SESSION_REFRESH_REQUIRED") {
throw new Response(
JSON.stringify({
error: "SESSION_REFRESH_REQUIRED",
message: "Session needs to be refreshed"
}),
{
status: 401,
headers: { "Content-Type": "application/json" }
}
);
}
throw error;
}
logger.error("Unauthorized user in admin function.", context);
throw new Error("Unauthorized");
});
export const fetchUserRoles = async (userAuthId: string) => {