Spain prevailed in an eight-goal thriller to beat France 5-3 after extra time and win the Olympic men's football gold medal for the first time since 1992.