Refactor authentication middleware.