import { define, State } from "../../../utils.ts"; import { Context } from "fresh"; import { getUserPin } from "../../../services/userService.ts"; import { hashText } from "../../../services/stateMiddleware.ts"; import { createPublicId } from "../../../helpers.ts"; import { UserPin } from "../../../db/interfaces.ts"; export const handler = define.handlers({ async GET(ctx: Context) { try { // Resolve user ID from authenticated state/session (cookie-backed) const userId = ctx.state.auth?.userId ?? ctx.state.data.user_id?.trim(); if (!userId) { return new Response( JSON.stringify({ error: "User not authenticated" }), { status: 401, headers: { "Content-Type": "application/json" }, }, ); } // Parse naunce parameter from URL const url = new URL(ctx.req.url); const naunce = url.searchParams.get("naunce") || ""; // Get user pin from database const userPin = await getUserPin(userId) as UserPin | null; if (!userPin) { return new Response( JSON.stringify({ error: "User pin not found" }), { status: 404, headers: { "Content-Type": "application/json" }, }, ); } const responsePin: UserPin = { ...userPin, user_id: await createPublicId(userPin.user_id), }; // If naunce is provided, compare with user pin hash if (naunce) { const userPinHash = await hashText(JSON.stringify(responsePin)); if (userPinHash === naunce) { return new Response("", { status: 200, headers: { "Content-Type": "application/json" }, }); } } // Return pin data including the actual pin value for localStorage sync return new Response( JSON.stringify(responsePin), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } catch (error) { console.error("Error getting user pin:", error); return new Response( JSON.stringify({ error: "Internal server error" }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } }, });