all repos — stealth-developers @ 8199683b527f1f06beacd568dc6e141904b7961e

apps/api/src/lib/auth.ts (view raw)

 1
 2
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
import { getSession, getUser } from "@stealth-developers/db";
import Elysia, { t } from "elysia";

export const authPlugin = new Elysia({ name: "auth" })
	.guard({
		as: "global",
		cookie: t.Cookie({
			session_id: t.Optional(t.String()),
		}),
	})
	.resolve({ as: "global" }, async ({ cookie: { session_id } }) => {
		if (!session_id) return { session: null };

		const sessionId = session_id.value as string | undefined;
		if (!sessionId) return { session: null };

		const session = await getSession(sessionId);
		if (!session || session.expiresAt < new Date()) return { session: null };

		const user = await getUser(session.userId);
		if (!user) return { session: null };

		return { session, user };
	});