A US judge has ruled that the US government has no legal basis for holding an Afghan man at its Guantanamo Bay prison in Cuba.