Refactored code to have a clearer flow for the gateway mode (on init) and the normal login. Fix infinite redirection loop issue.