2024-06-13 12:25:30 +02:00
|
|
|
import { FreshContext } from '$fresh/server.ts'
|
2024-07-01 13:11:20 +02:00
|
|
|
import { SessionStore } from ':src/session/mod.ts'
|
|
|
|
import { respondApi } from ':src/utils.ts'
|
2024-06-13 12:25:30 +02:00
|
|
|
|
|
|
|
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:25:30 +02:00
|
|
|
|
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:25:30 +02:00
|
|
|
|
2024-06-13 12:43:29 +02:00
|
|
|
return ctx.next()
|
2024-06-13 12:25:30 +02:00
|
|
|
}
|