Authentication rewrite and general code refactoring