Refactor and complete login and logout function