Skip to content

Commit

Permalink
distill cookie optiosn to authkit module
Browse files Browse the repository at this point in the history
  • Loading branch information
chantastic committed Jul 14, 2024
1 parent b229ad1 commit 6c63a35
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 20 deletions.
11 changes: 8 additions & 3 deletions chan.dev/src/lib/authkit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,13 @@ import type {User} from '@workos-inc/node'

export const COOKIE_NAME = 'wos-session'

export const COOKIE_OPTIONS = {
path: '/',
httpOnly: true,
secure: true,
sameSite: 'lax',
}

export interface Session {
accessToken: string
refreshToken: string
Expand All @@ -27,9 +34,7 @@ export async function decryptSession(
}

export async function encryptSession(session: Session) {
let encryptedSession = await sealData(session, {
return await sealData(session, {
password: import.meta.env.WORKOS_COOKIE_PASSWORD,
})

return encryptedSession
}
17 changes: 7 additions & 10 deletions chan.dev/src/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {minimatch} from 'minimatch'
import {WorkOS} from '@workos-inc/node'
import {createRemoteJWKSet, jwtVerify} from 'jose'
import * as AUTHKIT from '#lib/authkit'
import type {AstroCookieSetOptions} from 'astro'

export const onRequest = defineMiddleware(
async (context, next) => {
Expand Down Expand Up @@ -49,20 +50,16 @@ export const onRequest = defineMiddleware(
refreshToken: session.refreshToken,
}
)
const encryptedRefreshedSession = await encryptSession({
user: session.user,
...refreshedSession,
})
const encryptedRefreshedSession =
await AUTHKIT.encryptSession({
user: session.user,
...refreshedSession,
})

context.cookies.set(
AUTHKIT.COOKIE_NAME,
encryptedRefreshedSession,
{
path: '/',
httpOnly: true,
secure: true,
sameSite: 'lax',
}
AUTHKIT.COOKIE_OPTIONS as AstroCookieSetOptions
)
} catch (e) {
return context.redirect('/sign-in')
Expand Down
13 changes: 6 additions & 7 deletions chan.dev/src/pages/auth/callback.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type {APIRoute} from 'astro'
import type {APIRoute, AstroCookieSetOptions} from 'astro'
import {WorkOS} from '@workos-inc/node'
import * as AUTHKIT from '#lib/authkit'

Expand All @@ -20,12 +20,11 @@ export const GET: APIRoute = async ({

const encryptedSession = await AUTHKIT.encryptSession(session)

cookies.set(AUTHKIT.COOKIE_NAME, encryptedSession, {
path: '/',
httpOnly: true,
secure: true,
sameSite: 'lax',
})
cookies.set(
AUTHKIT.COOKIE_NAME,
encryptedSession,
AUTHKIT.COOKIE_OPTIONS as AstroCookieSetOptions
)

return redirect('/dashboard')
}
Expand Down

0 comments on commit 6c63a35

Please sign in to comment.