refactored code and added checks for if user logged in