Skip to content

Commit

Permalink
clean up related outdated sessions on login
Browse files Browse the repository at this point in the history
a cron job to clean it would probably be better, but this is for now.
  • Loading branch information
nichtsam committed Jan 11, 2025
1 parent c17fa1f commit 556794d
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 20 deletions.
22 changes: 14 additions & 8 deletions app/utils/auth/auth.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createCookieSessionStorage, redirect } from '@remix-run/node'
import dayjs from 'dayjs'
import { eq } from 'drizzle-orm'
import { and, eq, lt } from 'drizzle-orm'
import { redirectBack } from 'remix-utils/redirect-back'
import { safeRedirect } from 'remix-utils/safe-redirect'
import { type z } from 'zod'
Expand Down Expand Up @@ -176,6 +176,15 @@ export const login = async (
},
init?: ResponseInit,
) => {
await db
.delete(sessionTable)
.where(
and(
eq(sessionTable.user_id, userId),
lt(sessionTable.expiration_at, new Date()),
),
)

const session = (
await db
.insert(sessionTable)
Expand Down Expand Up @@ -221,13 +230,10 @@ export const signUpWithConnection = async ({
)[0]!
const user_id = user.id

await db
.insert(connectionTable)
.values({
...connectionInsert,
user_id,
})
.then()
await db.insert(connectionTable).values({
...connectionInsert,
user_id,
})

if (userImageUrl) {
await downloadFile(userImageUrl)
Expand Down
30 changes: 18 additions & 12 deletions drizzle/schema.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { relations, sql } from 'drizzle-orm'
import {
blob,
index,
integer,
sqliteTable,
text,
Expand Down Expand Up @@ -53,20 +54,25 @@ export const connectionTable = sqliteTable(
(table) => [unique().on(table.provider_name, table.provider_id)],
)

export const sessionTable = sqliteTable('session', {
id: text('id').primaryKey().$default(createId).notNull(),
export const sessionTable = sqliteTable(
'session',
{
id: text('id').primaryKey().$default(createId).notNull(),

expiration_at: integer('expiration_at', {
mode: 'timestamp_ms',
}).notNull(),
user_id: text('user_id')
.references(() => userTable.id, { onDelete: 'cascade' })
.notNull(),
expiration_at: integer('expiration_at', {
mode: 'timestamp_ms',
}).notNull(),

created_at: integer('created_at', { mode: 'timestamp_ms' })
.default(sql`(unixepoch('subsec') * 1000)`)
.notNull(),
})
user_id: text('user_id')
.references(() => userTable.id, { onDelete: 'cascade' })
.notNull(),

created_at: integer('created_at', { mode: 'timestamp_ms' })
.default(sql`(unixepoch('subsec') * 1000)`)
.notNull(),
},
(table) => [index('user_id_idx').on(table.user_id)],
)

export const userSchema = createInsertSchema(userTable)
export const imageSchema = createInsertSchema(userImageTable)
Expand Down

0 comments on commit 556794d

Please sign in to comment.