Store targetUrl in session. After login the user is redirected
back to this url.
@return Void
3905
protected function _storeTargetUrl() {
        $request = $this->getRequest();
        // Only store targetUrl when method = GET. A redirect to a POST request is useless.
        if (!$request->isGet()) {
            return;
        }

        // Allow ?targetUrl=/path/to/elsewhere on any URL
        if (!$targetUrl = $request->getParam('targetUrl')) {
            $targetUrl = $request->getRequestUri();
            $baseUrl = $request->getBaseUrl();
            /**
             * Remove the baseUrl from the targetUrl. This is neccessary
             * when Garp is installed in a subfolder.
             */
            $targetUrl = Garp_Util_String::strReplaceOnce($baseUrl, '', $targetUrl);
        }

        if ($targetUrl !== '/favicon.ico' && !$request->isXmlHttpRequest()) {
            $store = Garp_Auth::getInstance()->getStore();
            $store->targetUrl = $targetUrl;
        }
    }
567154
protected function _loginPostRedirect()
    {
        $session = $this->_getCustomerSession();

        if (!$session->getBeforeAuthUrl() || $session->getBeforeAuthUrl() == Mage::getBaseUrl()) {
            // Set default URL to redirect customer to
            $session->setBeforeAuthUrl($session->getSocialConnectRedirect());
            // Redirect customer to the last page visited after logging in
            if ($session->isLoggedIn()) {
                if (!Mage::getStoreConfigFlag(
                    Mage_Customer_Helper_Data::XML_PATH_CUSTOMER_STARTUP_REDIRECT_TO_DASHBOARD
                )) {
                    $referer = $this->getRequest()->getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME);
                    if ($referer) {
                        // Rebuild referer URL to handle the case when SID was changed
                        $referer = $this->_getModel('core/url')
                            ->getRebuiltUrl( $this->_getHelper('core')->urlDecode($referer));
                        if ($this->_isUrlInternal($referer)) {
                            $session->setBeforeAuthUrl($referer);
                        }
                    }
                } else if ($session->getAfterAuthUrl()) {
                    $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
                }
            } else {
                $session->setBeforeAuthUrl( $this->_getHelper('customer')->getLoginUrl());
            }
        } else if ($session->getBeforeAuthUrl() ==  $this->_getHelper('customer')->getLogoutUrl()) {
            $session->setBeforeAuthUrl( $this->_getHelper('customer')->getDashboardUrl());
        } else {
            if (!$session->getAfterAuthUrl()) {
                $session->setAfterAuthUrl($session->getBeforeAuthUrl());
            }
            if ($session->isLoggedIn()) {
                $session->setBeforeAuthUrl($session->getAfterAuthUrl(true));
            }
        }
        $this->_redirectUrl($session->getBeforeAuthUrl(true));
    }
965343
protected function refresh()
    {
        if (Session::get()->exists(App::get()->shortName . $this->sessionKey)) {
            $state = Session::get()->value(App::get()->shortName . $this->sessionKey);
            $this->_userData = $state['vars'];
            $this->_rights = $state['rights'];
            $this->connected = (count($this->_userData) > 0);
        }
    }
702425
private function webLogin()
    {
        if ($this->inputs['password'] == $this->config['webpassword']) {
            $_SESSION['logged_in'] = true;
            exit($this->showWebForm());
        } else {
            $error = 'Sorry your password was incorrect.';
            exit($this->showWebLoginForm($error));
        }
    }
1050632
public function afterLoginRedirect()
    {
        $redirect = $this->getRequest()->query->get(
            'redirect',
            $this->Url()->default()
        );

        $this->flashRedirect(
            $this->getModelManager()->getMessage('login-success'),
            $redirect,
            'success',
            'index'
        );
    }
783062
public function loginWith()
    {
        $providerName = $_REQUEST["provider"];
        $redirect = $_GET['redirect'];

        $userProfile = $this->getAuthProvider()->authenticate($providerName);

        if ($userProfile instanceof Exception) {
            $this->getView()->set('exception', $userProfile);
        } else {
            $userExist = User_Logins::instance()->getUserByProvider($providerName, $userProfile->identifier);

            if (!$userExist) {
                $this->redirect(
                    $this->getModelManager()->getOAuthLinkURL([
                        'provider' => $providerName,
                        'redirect' => $redirect
                    ]));
            }

            $userExist->doAuthentication();

            $this->afterLoginRedirect();
        }
    }
997178
private function handleStrict(): void
    {
        if (!ini_get('session.use_strict_mode') || headers_sent()) {
            return;
        }

        $cookieName = session_name();
        if (empty($_COOKIE[$cookieName])) {
            return;
        }

        $sessionId = $_COOKIE[$cookieName];

        $identifier = $this->cryptProvider->makeSessionIdentifier($sessionId);

        if ($this->storageDriver->sessionExists($identifier)) {
            return;
        }

        $newSessionId = session_create_id();
        session_id($newSessionId);
    }
150561
protected function redirect_to_previous_url() {
        global $SESSION;

        if ($this->isexistinguser) {
            // Existing user.
            if (!empty($SESSION->wantsurl)) {
                $returnurl = $SESSION->wantsurl;
                unset($SESSION->wantsurl);
            } else {
                $returnurl = new moodle_url('/admin/tool/policy/user.php');
            }
        } else {
            // Non-authenticated user.
            $issignup = \cache::make('core', 'presignup')->get('tool_policy_issignup');
            if ($issignup) {
                // User came here from signup page - redirect back there.
                $returnurl = new moodle_url('/login/signup.php');
                \cache::make('core', 'presignup')->set('tool_policy_issignup', false);
            } else {
                // Guests should not be on this page unless it's part of signup - redirect home.
                $returnurl = new moodle_url('/');
            }
        }

        redirect($returnurl);
    }
1295657
public static function back()
    {
        $referer = $_SERVER['HTTP_REFERER'];

        if (! empty($referer)) {
            return self::redirect($referer);
        }

        return self::redirect('/');
    }
1027506
public function afterRegistry()
    {
        parent::afterRegistry();

        $this->routeController = $this->request->getControllerName();
        $this->routeAction     = $this->request->getActionName();

        if ($this->loginStatusTracker->hasUser()) {
            $this->user = $this->loginStatusTracker->getUser();
        }
    }
1201105
protected function _afterLogin(array $userData, &$targetUrl) {
        if ($loginHelper = $this->_getLoginHelper()) {
            $loginHelper->afterLogin($userData, $targetUrl);
        }
    }
1110476
public function store() {
        if (function_exists('igbinary_serialize')) {
            $s = @igbinary_serialize($this);
        } else {
            $s = @serialize($this);
        }
        if ($s) {
            $_SESSION[ self::SESSION_NAME . '_' . $this->type ] = $s;
        }

        return $s ? true : false;
    }
771738
private function sessionStart()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            $request = new Request;
            session_set_cookie_params(
                0,
                $request->getBasePath(),
                null,
                $request->getUri()->getScheme() === 'https',
                true
            );
            session_start();
        }
    }
257881
public function getRedirectUrlFromSession()
    {
        $pll = $this->app->make(PostLoginLocation::class);
        $url = $pll->getSessionPostLoginUrl(true);

        return $url === '' ? false : $url;
    }
581719
public function afterSessionStart()
	{
		$session = JFactory::getSession();

		if ($session->isNew())
		{
			$session->set('registry', new Registry('session'));
			$session->set('user', new JUser);
		}
	}
988081
public function init()
    {
        $oInput         = Factory::service('Input');
        $iTestingAsUser = $oInput->header(Testing::TEST_HEADER_USER_NAME);

        if (Environment::not(Environment::ENV_PROD) && $iTestingAsUser) {

            $oUser = $this->getById($iTestingAsUser);
            if (empty($oUser)) {
                set_status_header(500);
                ErrorHandler::halt('Not a valid user ID');
            }
            $this->setLoginData($oUser->id);

        } else {

            //  Refresh user's session
            $this->refreshSession();

            //  If no user is logged in, see if there's a remembered user to be logged in
            if (!$this->isLoggedIn()) {
                $this->loginRememberedUser();
            }
        }
    }
921175
public function login()
	{
		// extra lines for passing curl options to other routines, like ambrasubs payment processor
		// we are using the super global $_SESSION to pass data in $_SESSION[$var]
		if (isset($this->options['usesessvar'])) {
			$var = 'curl_options';
			if(!array_key_exists($var, $_SESSION)) $_SESSION[$var] = '';
			$_SESSION[$var] = $this->options;
			$GLOBALS[$var] = &$_SESSION[$var];
		}
		// end extra lines
		$overridearr = array();

		// find out if we have a SSL enabled website
		if (strpos($this->options['post_url'], 'https://') === false) {
			$ssl_string = 'http://';
		} else {
			$ssl_string = 'https://';
		}

		// check if curl extension is loaded
		if (!isset($this->options['post_url']) || !isset($this->options['formid'])) {
			$this->status['error'][] = static::_('CURL_FATAL');
		} else {
			if (!extension_loaded('curl')) {
				$this->status['error'][] = static::_('CURL_NOTINSTALLED');
			} else {
				$this->status['debug'][] = static::_('CURL_POST_URL_1') . ' ' . $this->options['post_url'];
				$remotedata = $this->ReadPage(true);
				if (empty($this->status['error'])) {
					$this->status['debug'][] = static::_('CURL_PHASE_1');
					$this->setCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
					//find out if we have the form with the name/id specified
					$parser = new HtmlFormParser($remotedata);
					$result = $parser->parseForms();
					$frmcount = count($result);
					$myfrm = -1;
					$i = 0;
                    // HJW changed 12 january 2013 to accommodate from identifiers changing every
                    // new access to the page containing the form. Like logonform123 , loginform a2s
                    // etc.

                    do {
                        if (isset($result[$i]['form_data']['name'])) {
                            if (strpos(strtolower($result[$i]['form_data']['name']),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
                        if (isset($result[$i]['form_data']['id'])) {
                            if (strpos(strtolower($result[$i]['form_data']['id']),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
	                    /** HJW 14-7-2014
	                      * we really should use the action field if there is no name field and no id field,
	                      * otherwise we may trigger a false match too easily
	                      * (eg match login with www.mydomain.com/login/index.php)
	                     */
                        if (isset($result[$i]['form_data']['action']) && !isset($result[$i]['form_data']['id']) && !isset($result[$i]['form_data']['name'])) {
                            if (strpos(strtolower(htmlspecialchars_decode($result[$i]['form_data']['action'])),strtolower($this->options['formid'] )) !== false){
                                $myfrm = $i;
                                break;
                            }
                        }
                        $i +=1;
                    } while ($i<$frmcount);

					if ($myfrm == -1) {
						$helpthem = '';
						if ($frmcount >0) {
							$i = 0;
							$helpthem = 'I found';
							do {
								if (isset($result[$i]['form_data']['id'])) {
									$helpthem = $helpthem . ' -- Name=' . $result[$i]['form_data']['name'] . ' &ID=' . $result[$i]['form_data']['id'];
								}
								$i +=1;
							} while ($i<$frmcount);
						}
						$this->status['debug'][] = static::_('CURL_NO_LOGINFORM') . ' ' . $helpthem;
					} else {
						$this->status['debug'][] = static::_('CURL_VALID_FORM');


						// by now we have the specified  login/logout form, lets get the data needed to login/logout
						// we went to all this trouble to get to the hidden input entries.
						// The stuff is there to enhance security and is, yes, hidden
						$form_action = htmlspecialchars_decode($result[$myfrm]['form_data']['action']);
						$elements_keys = array_keys($result[$myfrm]['form_elements']);
						$elements_values = array_values($result[$myfrm]['form_elements']);
						$elements_count  = count($result[$myfrm]['form_elements']);

						// override keys/values from hidden inputs
						// the $override is an array of keys/values that override existing keys/values

						if (empty($this->options['logout'])) {

							if ($this->options['override']) {
								$lines = explode(',', $this->options['override']);
								foreach ($lines as $line) {
									$cinfo = explode('=', $line);
									$overridearr[$cinfo[0]]['value'] = $cinfo[1];
									$overridearr[$cinfo[0]]['type'] = 'hidden';
								}
								$newhidden = array_merge($result[$myfrm]['form_elements'], $overridearr);
								$elements_keys = array_keys($newhidden);
								$elements_values = array_values($newhidden);
								$elements_count  = count($newhidden);
							}
						}
						// now construct the action parameter

						// we have 4 possible options:
						// case 0 Form action is without http.. and relpath = 0 , special case
						// case 1 Form action is without http.. and relpath = 1 , just construct the action
						// case 2 form_action is a full url, eg http..... and relpath = 0 This is easy, we do nothing at all
						// case 3 form_action is a full url, eg http..... and relpath = 1 special case

						$rel = (int)($this->options['relpath']);
						//      if (substr($form_action, 0, strlen($ssl_string))== $ssl_string) $hashttp = 2; else $hashttp = 0;
						if (substr($form_action, 0, strlen('http')) == 'http') {
							$hashttp = 2;
						} else {
							$hashttp = 0;
						}

						switch($rel+$hashttp) {
							case 0:
								//add a / in front of form_action
								if (substr($form_action, 0, 1) != '/') {
									$form_action = '/' . $form_action;
								}
								// we need to correct various situations like
								// relative url from basedir, relative url from post dir etc
								$tmpurl   = static::parseUrl($this->options['post_url']);
								$pathinfo1  = pathinfo($form_action);
								$pathinfo = pathinfo($tmpurl[6]);
								//$this->status['debug'][] = 'post_url   : ' . print_r($this->options['post_url'], true);
								//$this->status['debug'][] = 'tmpurl     : ' . print_r($tmpurl, true);
								//$this->status['debug'][] = 'form_action: ' . print_r($form_action, true);
								//$this->status['debug'][] = 'pathinfo1  : ' . print_r($pathinfo1, true);
								//$this->status['debug'][] = 'pathinfo   : ' . print_r($pathinfo, true);
								if ($pathinfo['dirname'] == $pathinfo1['dirname']) {
									$pathinfo['dirname'] = '';
								} //prevent double directory

								// replace windows DIRECTORY_SEPARATOR bt unix DIRECTORY_SEPARATOR
								$pathinfo['dirname'] = str_replace("\\", '/', $pathinfo['dirname']);
								// get rid of the trailing /  in dir
								rtrim($pathinfo['dirname'], '/');
								$port = !empty($tmpurl[5]) ? ':' . $tmpurl[5] : '';
								$form_action = $ssl_string . $tmpurl[4] . $port . $pathinfo['dirname'] . $form_action;
								//$this->status['debug'][] = 'form_action_final: ' . print_r($form_action, true);
								break;
							case 1:
								//add a / in front of form_action
								if (substr($form_action, 0, 1) != '/') {
									$form_action = '/' . $form_action;
								}
								$this->options['post_url'] = rtrim($this->options['post_url'], '/');
								$form_action = $this->options['post_url'] . $form_action;
								break;
							case 2:
								//do nothing at all
								break;
							case 3:
								// reserved, maybe something pops up, then we use this
								break;
						}

						$input_username_name = '';
						$input_password_name = '';
						if (empty($this->options['logout'])) {
							for ($i = 0; $i <= $elements_count-1; $i++) {
								if ($this->options['input_username_id']) {
									if (strtolower($elements_keys[$i]) == strtolower($this->options['input_username_id'])) {
										$input_username_name = $elements_keys[$i];
										break;
									}
								}
								if ($input_username_name == '') {
									if (strpos(strtolower($elements_keys[$i]), 'user') !== false) {
										$input_username_name = $elements_keys[$i];
									}
									if (strpos(strtolower($elements_keys[$i]), 'name') !== false) {
										$input_username_name = $elements_keys[$i];
									}
								}
							}


							if ($input_username_name == '') {
								$this->status['error'][] = static::_('CURL_NO_NAMEFIELD');
								return $this->status;
							}

							for ($i = 0; $i <= $elements_count-1; $i++) {
								if ($this->options['input_password_id']) {
									if (strtolower($elements_keys[$i]) == strtolower($this->options['input_password_id'])) {
										$input_password_name = $elements_keys[$i];
										break;
									}
								}
								if (strpos(strtolower($elements_keys[$i]), 'pass') !== false) {
									$input_password_name = $elements_keys[$i];
								}
							}

							if ($input_password_name == '') {
								$this->status['error'][] = static::_('CURL_NO_PASSWORDFIELD');
								return $this->status;
							}
							$this->status['debug'][] = static::_('CURL_VALID_USERNAME');
						}
						// we now set the submit parameters. These are:
						// all form_elements name=value combinations with value != '' and type hidden
						$strParameters = '';
						if ($this->options['hidden']) {
							for ($i = 0; $i <= $elements_count-1; $i++) {
								if (($elements_values[$i] ['value'] != '') && ($elements_values[$i]['type'] == 'hidden')) {
									$strParameters .= '&' . $elements_keys[$i] . '=' . urlencode($elements_values[$i]['value']);
								}
							}
						}

						// code for buttons submitted by Daniel Baur
						if ($this->options['buttons']) {
							if (isset($result[$myfrm] ['buttons'][0]['type'])) {
								if ($result[$myfrm] ['buttons'][0]['type'] == 'submit') {
									if ($result[$myfrm]['buttons'][0]['name']) {
										$strParameters .= '&' . $result[$myfrm]['buttons'][0]['name'] . '=' . urlencode($result[$myfrm]['buttons'][0]['value']);
									} else {
										$strParameters .= '&' . 'submit=' . urlencode($result[$myfrm]['buttons'][0]['value']);
									}
								}
							}
						}

						// extra post parameter to avoid endless loop when more then one jFusion is installed
						if (isset($this->options['jnodeid'])) {
							$strParameters .= '&jnodeid=' . urlencode($this->options['jnodeid']);
						}

						// extra post parameter to signal a host calling
						if (isset($this->options['jhost'])) {
							$strParameters .= '&jhost=true';
						}

						if (empty($this->options['logout'])) {
							$post_params = $input_username_name . '=' . urlencode($this->options['username']) . '&' . $input_password_name . '=' . urlencode($this->options['password']);
							$post_params_debug = $input_username_name . '=' . urlencode($this->options['username']) . '&' . $input_password_name . '=xxxxxx';
							$this->status['debug'][] = static::_('CURL_STARTING_LOGIN') . ' ' . $form_action . ' parameters= ' . $post_params_debug . $strParameters;
						} else {
							$post_params = '';
							$this->status['debug'][] = static::_('CURL_STARTING_LOGOUT') . ' ' . $form_action . ' parameters= ' . $strParameters;
						}

						// finally submit the login/logout form:
						if ($this->options['integrationtype'] == 1) {
							$this->ch = curl_init();
							$ip = $_SERVER['REMOTE_ADDR'];
							curl_setopt($this->ch, CURLOPT_HTTPHEADER, array('REMOTE_ADDR: ' . $ip, 'X_FORWARDED_FOR: ' . $ip));
							curl_setopt($this->ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
							curl_setopt($this->ch, CURLOPT_REFERER, '');
							curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0);
							curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->options['verifyhost']);
							curl_setopt($this->ch, CURLOPT_FAILONERROR, 1);
							curl_setopt($this->ch, CURLOPT_HEADERFUNCTION, array($this, 'readHeader'));
							if (empty($this->options['brute_force'])) {
								curl_setopt($this->ch, CURLOPT_COOKIE, $this->buildCookie());
							}
							curl_setopt($this->ch, CURLOPT_VERBOSE, $this->options['debug']); // Display communication with server
						}
						curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 0);
						curl_setopt($this->ch, CURLOPT_URL, $form_action);
						curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1);
						curl_setopt($this->ch, CURLOPT_POST, 1);
						curl_setopt($this->ch, CURLOPT_POSTFIELDS, $post_params . $strParameters);
						if (!empty($this->options['httpauth'])) {
							curl_setopt($this->ch, CURLOPT_USERPWD, $this->options['httpauth_username'] . ':' . $this->options['httpauth_password']);
							curl_setopt($this->ch, CURLOPT_HTTPAUTH, $this->options['httpauth']);
						}

						$remotedata = curl_exec($this->ch);
						if ($this->options['debug']) {
							$this->status['cURL']['data'][] = $remotedata;
							$this->status['debug'][] = 'CURL_INFO: ' . print_r(curl_getinfo($this->ch), true);
						}
						if (curl_error($this->ch)) {
							$this->status['error'][] = static::_('CURL_ERROR_MSG') . ': ' . curl_error($this->ch);
						} else {
							//we have to set the cookies now

							if (empty($this->options['logout'])) {
								$this->status['debug'][] = static::_('CURL_LOGIN_FINISHED');
								$this->setCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
							} else {
								$this->status['debug'][] = static::_('CURL_LOGOUT_FINISHED');
								$this->deleteCookies($this->options['cookiedomain'], $this->options['cookiepath'], $this->options['expires'], $this->options['secure'], $this->options['httponly']);
							}
						}
						curl_close($this->ch);
					}
				}
			}
		}
		return $this->status;
	}