Refactor session logic using templates.