Optimize queries for permissions and users; minor cleanup