A Social Choice Theory of Legitimacy