Skip to content

Commit

Permalink
Do not hardcode CLERK_SECRET_KEY as name of env var
Browse files Browse the repository at this point in the history
Plus simplified error messages during token verification failure
  • Loading branch information
markjaquith committed Nov 2, 2023
1 parent a11a8cd commit e6f95ac
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 15 deletions.
11 changes: 8 additions & 3 deletions src/lib/server/handleClerk.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { redirect, type Handle } from '@sveltejs/kit'
import { verifySession } from './index.js'

type ClerkErrorWithReason = {
reason?: string
[key: string]: unknown
}

export default function handleClerk(
secretKey: string,
{
Expand All @@ -21,15 +26,15 @@ export default function handleClerk(
if (sessionToken) {
debug && console.log('[Clerk SvelteKit] Found session token in cookies.')
try {
const session = await verifySession(sessionToken)
const session = await verifySession(secretKey, sessionToken)
if (session) {
debug && console.log('[Clerk SvelteKit] Session verified successfully.')
event.locals.session = session
} else {
debug && console.warn('[Clerk SvelteKit] Session verification returned no session.')
}
} catch (reason) {
console.warn('[Clerk SvelteKit] Warning during session verification:', reason)
} catch (error) {
debug && console.log('[Clerk SvelteKit] Session verification failed.', (error as ClerkErrorWithReason)?.reason ?? error)
}
} else {
debug && console.log('[Clerk SvelteKit] No session token found in cookies.')
Expand Down
15 changes: 3 additions & 12 deletions src/lib/server/session.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
import { CLERK_SECRET_KEY } from '$env/static/private'

import { verifyToken } from '@clerk/backend'
// import { json } from '@sveltejs/kit'
// import type { RequestHandler, RequestEvent } from '@sveltejs/kit'

export const verifySession = async (sessionToken: string) => {
export const verifySession = async (secretKey: string, sessionToken: string) => {
if (sessionToken) {
const issuer = (issuer: string) => issuer.startsWith('https://clerk.') || issuer.includes('.clerk.accounts')
const claims = await verifyToken(sessionToken, {
secretKey: CLERK_SECRET_KEY,
secretKey,
issuer,
})
return {
Expand All @@ -16,10 +14,3 @@ export const verifySession = async (sessionToken: string) => {
}
}
}

// export const requireSession = (handler: RequestHandler) => async (event: RequestEvent) => {
// if (!event.locals.session) {
// return json({ ok: false, error: 'Users Session not found' })
// }
// return handler(event)
// }

0 comments on commit e6f95ac

Please sign in to comment.