Refactor authenticate middleware.