This logic is also found in authenticate.js.