Refactored login function