Refactor logout to use a middleware. Closes #273