lucia-auth / lucia

Authentication, simple and clean
https://lucia-auth.com
MIT License
9.21k stars 466 forks source link

[Bug]: DrizzleSQLiteAdapter `validateSession()` query fails with D1 #1498

Closed colecrouter closed 6 months ago

colecrouter commented 6 months ago

Package

​@lucia-auth/session-drizzle

Describe the bug

Session schema as per docs:

// schema.ts
export const userTable = sqliteTable('user', {
    id: text("id").notNull().primaryKey(),
    providerId: text("provider_id").notNull(),
    provider: text("provider").notNull(),
});

export const sessionTable = sqliteTable('session', {
    id: text("id").notNull().primaryKey(),
    userId: text("user_id")
        .notNull()
        .references(() => userTable.id),
    expiresAt: integer('expires_at').notNull()
});
// hooks.server.ts
import { DrizzleSQLiteAdapter } from "@lucia-auth/adapter-drizzle";
import { Lucia } from "lucia";
...
const adapter = new DrizzleSQLiteAdapter(drizzle(event.platform.env.DB, {
            schema: {
                user: userTable,
                session: sessionTable,
            }
        }), sessionTable, userTable);
const lucia = new Lucia(adapter);
const sessionId = event.cookies.get(lucia.sessionCookieName);
const { session, user } = await lucia.validateSession(sessionId);
console.log(session) // null
...

It seems that the issue lies within this query. It returns:

{ id: 'r3e9l9mpwwef1i8', userId: 1713552867, expiresAt: undefined }

where the original unmodified object looks like this:

{ id: 'oldpey50k1u7351frjg3n5xmmmnwljgxa8a6w2b8', userId: 'r3e9l9mpwwef1i8', expiresAt: 1713552867}
Picture of data in db:
![image](https://github.com/lucia-auth/lucia/assets/15883173/8244a11e-006d-4d9c-8c74-b97555f83379)

I tried to run a similar SQL query on the file:

SELECT user.*, session.*
FROM session
INNER JOIN user ON session.user_id = user.id
WHERE session.id = "oldpey50k1u7351frjg3n5xmmmnwljgxa8a6w2b8";

this is what I get:

id provider_id provider id user_id expires_at
r3e9l9mpwwef1i8 15883173 github oldpey50k1u7351frjg3n5xmmmnwljgxa8a6w2b8 r3e9l9mpwwef1i8 1713552867

—which looks right. I ran this both using an external program, and from within my script directly on the (D1) db object.

Of course, once this reaches validateSession, it immediately fails here due to expiresAt being Invalid Date.

There's a test that should catch this, but I can't run pnpm on my work machine, so I can't verify/test. Has anyone else ran into this issue? Is this possibly an issue with Drizzle? I feel like I'm going crazy.

pilcrowOnPaper commented 6 months ago

Ah yeah, this is a known issue with Drizzle and D1. Will fix it