2023-08-01 17:50:00 +02:00
|
|
|
//routes/middleware-error-handler/_middleware.ts
|
2025-01-05 18:03:59 +01:00
|
|
|
import { FreshContext } from "$fresh/server.ts";
|
2023-08-01 17:50:00 +02:00
|
|
|
import { DomainError } from "@lib/errors.ts";
|
2024-06-21 11:36:23 +02:00
|
|
|
import { getCookies } from "@std/http/cookie";
|
2023-08-13 00:34:03 +02:00
|
|
|
import { verify } from "https://deno.land/x/djwt@v2.2/mod.ts";
|
2025-01-05 18:03:59 +01:00
|
|
|
import * as perf from "@lib/performance.ts";
|
2023-08-04 22:35:25 +02:00
|
|
|
import { JWT_SECRET } from "@lib/env.ts";
|
2023-08-01 17:50:00 +02:00
|
|
|
|
|
|
|
export async function handler(
|
2023-08-13 00:34:03 +02:00
|
|
|
req: Request,
|
2025-01-05 18:03:59 +01:00
|
|
|
ctx: FreshContext,
|
2023-08-01 17:50:00 +02:00
|
|
|
) {
|
|
|
|
try {
|
2023-08-13 00:34:03 +02:00
|
|
|
performance.mark("a");
|
|
|
|
const allCookies = getCookies(req.headers);
|
2023-08-04 22:35:25 +02:00
|
|
|
const sessionCookie = allCookies["session_cookie"];
|
|
|
|
if (!ctx.state.session && sessionCookie && JWT_SECRET) {
|
|
|
|
try {
|
|
|
|
const payload = await verify(sessionCookie, JWT_SECRET, "HS512");
|
|
|
|
if (payload) {
|
|
|
|
ctx.state.session = payload;
|
|
|
|
}
|
|
|
|
} catch (_err) {
|
|
|
|
//
|
2023-08-13 00:34:03 +02:00
|
|
|
console.log({ _err });
|
2023-08-04 22:35:25 +02:00
|
|
|
}
|
|
|
|
}
|
2023-08-13 00:34:03 +02:00
|
|
|
|
|
|
|
const resp = await ctx.next();
|
|
|
|
performance.mark("b");
|
|
|
|
const b = performance.measure("a->b", "a", "b");
|
2025-01-05 18:03:59 +01:00
|
|
|
perf.savePerformance(req.url, b.duration);
|
2023-08-13 00:34:03 +02:00
|
|
|
return resp;
|
2023-08-01 17:50:00 +02:00
|
|
|
} catch (error) {
|
2023-08-04 22:58:42 +02:00
|
|
|
console.error("Error", error);
|
2023-08-01 17:50:00 +02:00
|
|
|
|
|
|
|
if (error instanceof DomainError) {
|
|
|
|
return new Response(error.statusText, {
|
|
|
|
status: error.status,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
return new Response("Internal Server Error", {
|
|
|
|
status: 500,
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|