You may want to look into a [sinatra filter](http://www.sinatrarb.com/intro#Filters) that runs this code on protected routes.