From 3262d631fd1be55a5c85ede08d92a35c5fb7d2c4 Mon Sep 17 00:00:00 2001 From: Mathias Magnusson Date: Mon, 18 Aug 2025 21:43:11 +0200 Subject: Get current user session --- src/auth.tsx | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) (limited to 'src/auth.tsx') diff --git a/src/auth.tsx b/src/auth.tsx index ebda74e..eef8b8f 100644 --- a/src/auth.tsx +++ b/src/auth.tsx @@ -1,19 +1,35 @@ import { Hono } from "hono"; import * as swa from "@simplewebauthn/server"; import { randomUUID } from "node:crypto"; -import { eq } from "drizzle-orm"; +import { and, eq, gt, sql } from "drizzle-orm"; import { RP_ID, ORIGIN, db } from "./index.js"; import { sessionTable, userTable, webauthnChallenges } from "./db/schema.js"; import { stringify, parse } from "superjson"; -import { setCookie } from "hono/cookie"; - -let app = new Hono(); +import { getCookie, setCookie } from "hono/cookie"; +import type { Context } from "hono"; export const LoginForm = () =>
; +export async function getSession(c: Context) { + let sessionId = getCookie(c, "session"); + if (!sessionId) return null; + + let [result] = await db + .select() + .from(sessionTable) + .innerJoin(userTable, eq(userTable.id, sessionTable.userId)) + .where(({ sessions: session }) => and(eq(session.uuid, sessionId), gt(session.lastUse, sql`unixepoch() - ${60 * 60 * 24 * 7}`))); + if (!result) return null; + await db.update(sessionTable).set({ lastUse: sql`unixepoch()` }).where(eq(sessionTable.id, result.sessions.id)); + return { user: result.users, lastUse: result.sessions.lastUse, uuid: result.sessions.uuid }; +} + +let app = new Hono(); +export default app; + app.post("/register-begin", async c => { const username = randomUUID(); let options = await swa.generateRegistrationOptions({ @@ -89,5 +105,3 @@ app.post("/login-finish", async c => { setCookie(c, "session", uuid); return c.html(

Logged in!

); }); - -export default app; -- cgit v1.2.3