refactor token handling code