Refactor authentication code