Moves the auth code out of the controller into lib.