feat(api): 🔒 check csrf token for all non get request

This commit is contained in:
Julien Oculi 2024-06-13 12:25:30 +02:00
parent f2348b0177
commit 6ae5348e2e

17
routes/api/_middleware.ts Normal file
View file

@ -0,0 +1,17 @@
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
if (['POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'].includes(request.method)) {
const session = SessionStore.getFromRequest(request)
const csrf = session?.get('_csrf')
if (csrf === undefined || request.headers.get('X-CSRF-TOKEN') !== csrf) {
return respondApi('error', new Error('invalid csrf token'), 401)
}
}
return ctx.next()
}