From 581da5a60c70c8cf6f2776e373f93532b6ee7395 Mon Sep 17 00:00:00 2001 From: syhner <71605633+syhner@users.noreply.github.com> Date: Wed, 3 Apr 2024 13:57:33 +0200 Subject: [PATCH] test with lucia --- api/index.tsx | 66 +++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 62 insertions(+), 4 deletions(-) diff --git a/api/index.tsx b/api/index.tsx index 22c73d8..df33d9e 100644 --- a/api/index.tsx +++ b/api/index.tsx @@ -4,18 +4,76 @@ */ import html from '@elysiajs/html'; -import { lucia } from '~/lib/auth'; import '../src/env'; // Validate env vars -// import { createElysia } from '../src/util/elysia'; import { Elysia } from 'elysia'; - -// import { app } from '../src/app'; +import { verifyRequestOrigin, type Session, type User } from 'lucia'; +import { lucia } from '../src/lib/auth'; export const config = { runtime: 'edge' }; +// import { app } from '../src/app'; +// const app = new Elysia({ aot: false }) +// .use(html()) +// .get('/', () => 'hello from elysia'); + const app = new Elysia({ aot: false }) + .derive( + async ( + context + ): Promise<{ + user: User | null; + session: Session | null; + }> => { + // CSRF check + if (context.request.method !== 'GET') { + const originHeader = context.request.headers.get('Origin'); + // NOTE: You may need to use `X-Forwarded-Host` instead + const hostHeader = context.request.headers.get('Host'); + if ( + !originHeader || + !hostHeader || + !verifyRequestOrigin(originHeader, [hostHeader]) + ) { + return { + user: null, + session: null, + }; + } + } + + // use headers instead of Cookie API to prevent type coercion + const cookieHeader = context.request.headers.get('Cookie') ?? ''; + const sessionId = lucia.readSessionCookie(cookieHeader); + if (!sessionId) { + return { + user: null, + session: null, + }; + } + + const { session, user } = await lucia.validateSession(sessionId); + if (session && session.fresh) { + const sessionCookie = lucia.createSessionCookie(session.id); + context.cookie[sessionCookie.name]?.set({ + value: sessionCookie.value, + ...sessionCookie.attributes, + }); + } + if (!session) { + const sessionCookie = lucia.createBlankSessionCookie(); + context.cookie[sessionCookie.name]?.set({ + value: sessionCookie.value, + ...sessionCookie.attributes, + }); + } + return { + user, + session, + }; + } + ) .use(html()) .get('/', () => 'hello from elysia');