Deduplicate a piece of code from middleware and login view, also make view names configurable