Refactored and reinstated ensureAuthenticated function