Refactoring authorize function