Skip to content
This repository has been archived by the owner on Nov 27, 2024. It is now read-only.

Commit

Permalink
test with lucia
Browse files Browse the repository at this point in the history
  • Loading branch information
syhner committed Apr 3, 2024
1 parent 061f4fe commit 581da5a
Showing 1 changed file with 62 additions and 4 deletions.
66 changes: 62 additions & 4 deletions api/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down

0 comments on commit 581da5a

Please sign in to comment.