Login refactoring and tests