Fix bug in authentication handler and minor refactoring