Refactor + inspiration from django's csrfmiddleware