Better Auth cookie format is 'token.signature' but DB only stores the token portion. Split on '.' to extract the actual session token.
49 lines
1.5 KiB
TypeScript
49 lines
1.5 KiB
TypeScript
import { db } from "@/lib/db";
|
|
import { comparisons, sessions, users } from "@/lib/db/schema";
|
|
import { eq, sql, and, gt } from "drizzle-orm";
|
|
import { headers } from "next/headers";
|
|
|
|
export async function GET() {
|
|
// Bypass auth.api.getSession() — Drizzle queryWithCache bug (#12)
|
|
const hdrs = await headers();
|
|
const cookieHeader = hdrs.get("cookie") ?? "";
|
|
const cookieMatch = cookieHeader
|
|
.split(";")
|
|
.map((c) => c.trim())
|
|
.find((c) => c.startsWith("__Secure-better-auth.session_token=") || c.startsWith("better-auth.session_token="));
|
|
const token = cookieMatch?.split("=")?.slice(1)?.join("=")?.trim().split(".")[0];
|
|
if (!token) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const sessionRows = await db
|
|
.select()
|
|
.from(sessions)
|
|
.where(and(eq(sessions.token, token), gt(sessions.expiresAt, new Date())))
|
|
.limit(1);
|
|
if (!sessionRows.length) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const userRows = await db
|
|
.select()
|
|
.from(users)
|
|
.where(eq(users.id, sessionRows[0].userId))
|
|
.limit(1);
|
|
if (!userRows.length) {
|
|
return Response.json({ error: "Unauthorized" }, { status: 401 });
|
|
}
|
|
|
|
const userId = userRows[0].id;
|
|
|
|
const result = await db
|
|
.select({
|
|
totalComparisons: sql<number>`count(*)`,
|
|
totalViews: sql<number>`coalesce(sum(${comparisons.viewCount}), 0)`,
|
|
})
|
|
.from(comparisons)
|
|
.where(eq(comparisons.userId, userId));
|
|
|
|
return Response.json(result[0]);
|
|
}
|