Skip to content

Commit

Permalink
Merge branch 'lucia-1.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
rmarscher committed Feb 1, 2024
2 parents 2616cea + 02a63b2 commit 856b353
Show file tree
Hide file tree
Showing 5 changed files with 29 additions and 29 deletions.
8 changes: 4 additions & 4 deletions packages/api/src/auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { Adapter, Lucia, TimeSpan } from 'lucia'
import { DrizzleSQLiteAdapter } from '@lucia-auth/adapter-drizzle'
import { SessionTable, UserTable } from '../db/schema'
import { DB } from '../db/client'
import type { ApiContextProps } from '../context'

export const getRequestOrigin = (request?: Request) => {
if (!request) return undefined
Expand All @@ -29,10 +28,11 @@ export const getAllowedOriginHost = (app_url: string, request?: Request) => {
return requestHost === appHost ? appHost : undefined
}

export const createAuth = (db: DB) => {
export const createAuth = (db: DB, appUrl: string) => {
// @ts-ignore Expect type errors because this is D1 and not SQLite... but it works
const adapter = new DrizzleSQLiteAdapter(db, SessionTable, UserTable)
return new Lucia(adapter, {
const env = !appUrl || appUrl.startsWith('http:') ? 'DEV' : 'PROD'
return new Lucia(adapter as Adapter, {
getUserAttributes: (data: DatabaseUserAttributes) => {
return {
email: data.email || '',
Expand All @@ -48,7 +48,7 @@ export const createAuth = (db: DB) => {
name: 'auth_session',
expires: false,
attributes: {
secure: true,
secure: env !== 'PROD',
sameSite: 'lax' as const,
},
},
Expand Down
4 changes: 2 additions & 2 deletions packages/api/src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@ export const createContext = async (

// const user = await getUser()

const auth = createAuth(db)
const enableTokens = Boolean(context?.req.header('x-enable-tokens'))
const auth = createAuth(db, env.APP_URL)
const enableTokens = Boolean(context?.req?.header('x-enable-tokens'))

async function getSession() {
let user: User | undefined
Expand Down
18 changes: 18 additions & 0 deletions packages/api/src/scheduled.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { match } from 'ts-pattern'
import { createContext } from './context'
import { Bindings } from './worker'

const scheduled: ExportedHandlerScheduledHandler<Bindings> = async (event, env, _) => {
console.log('Running cron', event.cron)
const ctx = await createContext(env)
await match({ event, ctx })
.with({ event: { cron: '15 2 * * 0' } }, async ({ ctx }) => {
await ctx.auth.deleteExpiredSessions()
console.log('Deleted expired sessions')
})
.otherwise(async () => {
console.log('Unhandled cron event', event)
})
}

export default scheduled
22 changes: 2 additions & 20 deletions packages/api/src/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { appRouter } from '@t4/api/src/router'
import { cors } from 'hono/cors'
import { createContext } from '@t4/api/src/context'
import { trpcServer } from '@hono/trpc-server'
import { match } from 'ts-pattern'
import scheduled from './scheduled'

export type Bindings = Env & {
JWT_VERIFICATION_KEY: string
Expand Down Expand Up @@ -59,25 +59,7 @@ app.use('/trpc/*', async (c, next) => {
})(c, next)
})

// https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/#syntax
interface ScheduledEvent {
cron: string // The value of the Cron Trigger that started the ScheduledEvent
type: 'scheduled'
scheduledTime: number // milliseconds since epoch
}

export default {
...app,
async scheduled(event: ScheduledEvent, env: Bindings) {
const ctx = await createContext(env)
console.log('Running cron', event.cron)
await match({ event, ctx })
.with({ event: { cron: '15 2 0 * *' } }, async ({ ctx }) => {
await ctx.auth.deleteExpiredSessions()
console.log('Deleted expired sessions')
})
.otherwise(async () => {
console.log('Unhandled cron event', event)
})
},
scheduled,
}
6 changes: 3 additions & 3 deletions packages/api/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,9 @@ migrations_dir = "migrations"
# - At 3PM on first day of the month
# - At 11:59PM on the last weekday of the month
# crons = [ "*/3 * * * *", "0 15 1 * *", "59 23 LW * *" ]
# For now, we're using "15 2 0 * *" to delete expired sessions from the database weekly
# Test locally with "http://localhost:3000/__scheduled?cron=15+2+0+*+*"
crons = [ "15 2 0 * *" ]
# For now, we're using "15 2 * * 0" to delete expired sessions from the database weekly
# Test locally with "http://localhost:8787/__scheduled?cron=15+2+*+*+0"
crons = [ "15 2 * * 0" ]


# The necessary secrets are:
Expand Down

0 comments on commit 856b353

Please sign in to comment.