feat(api): 🔒 check csrf token for all non get request
This commit is contained in:
parent
f2348b0177
commit
6ae5348e2e
17
routes/api/_middleware.ts
Normal file
17
routes/api/_middleware.ts
Normal 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()
|
||||
}
|
Loading…
Reference in a new issue