website/routes/api/_middleware.ts

18 lines
582 B
TypeScript
Raw Normal View History

import { FreshContext } from '$fresh/server.ts'
import { SessionStore } from '../../src/session/mod.ts'
import { respondApi } from '../../src/utils.ts'
export function handler(request: Request, ctx: FreshContext) {
// Check CSRF token
2024-06-13 12:43:29 +02:00
if (['POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'].includes(request.method)) {
const session = SessionStore.getFromRequest(request)
const csrf = session?.get('_csrf')
2024-06-13 12:43:29 +02:00
if (csrf === undefined || request.headers.get('X-CSRF-TOKEN') !== csrf) {
return respondApi('error', new Error('invalid csrf token'), 401)
}
}
2024-06-13 12:43:29 +02:00
return ctx.next()
}