import { define, State } from "../../../utils.ts"; import { Context } from "fresh"; import { getUser } from "../../../services/userService.ts"; import { hashText } from "../../../services/stateMiddleware.ts"; import { User } from "../../../db/interfaces.ts"; import { createPublicId } from "../../../helpers.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 profile from database const user = await getUser(userId) as User | null; if (!user) { return new Response( JSON.stringify({ error: "User profile not found" }), { status: 404, headers: { "Content-Type": "application/json" }, }, ); } const responseUser: User = { ...user, id: await createPublicId(userId), started_on: 0, updated_on: 0, }; // If naunce is provided, compare with user hash if (naunce) { const userHash = await hashText(JSON.stringify(responseUser)); if (userHash === naunce) { console.log("User naunce matched"); return new Response("", { status: 200, headers: { "Content-Type": "application/json" }, }); } } // Return user profile data return new Response( JSON.stringify(responseUser), { status: 200, headers: { "Content-Type": "application/json" }, }, ); } catch (error) { console.error("Error getting user profile:", error); return new Response( JSON.stringify({ error: "Internal server error" }), { status: 500, headers: { "Content-Type": "application/json" }, }, ); } }, });