Support single sign on; refactor SQL to separate function