login() public method

This function accepts an array $params, which controls some parts of the authentication. The accepted parameters depends on the authentication source being used. Some parameters are generic: - 'ErrorURL': A URL that should receive errors from the authentication. - 'KeepPost': If the current request is a POST request, keep the POST data until after the authentication. - 'ReturnTo': The URL the user should be returned to after authentication. - 'ReturnCallback': The function we should call after the user has finished authentication. Please note: this function never returns.
public login ( array $params = [] )
$params array Various options to the authentication request.
 public function executeSignin($request)
 {
     $user = $this->getUser();
     if ($user->isAuthenticated()) {
         return $this->redirect('@homepage');
     }
     // Create SimpleSAML module
     $simpleSAMLAuth = new SimpleSAML_Auth_Simple('default-sp');
     // If the user is authenticated from the IdP
     if ($simpleSAMLAuth->isAuthenticated()) {
         $attributes = $simpleSAMLAuth->getAttributes();
         // save the referer
         $user_referer = $user->getReferer($request->getReferer());
         // Try to find the user with his uid
         $query = Doctrine_Core::getTable('sfGuardUser')->createQuery('u')->where('u.username = ?', $attributes['eduPersonPrincipalName'][0]);
         // If the sGuardUser already exists in the database, it's OK
         if ($query->count() >= 1) {
             $guard_user = $query->fetchOne();
             $guard_user->setEmailAddress($attributes['mail'][0]);
             $guard_user->setLastName($attributes['cn'][0]);
             $guard_user->save();
         } else {
             // the user doesn't exist, we create a new one with random password
             $guard_user = new sfGuardUser();
             $guard_user->setUsername($attributes['eduPersonPrincipalName'][0]);
             $guard_user->setPassword(md5(microtime() . $attributes['eduPersonPrincipalName'][0] . mt_rand()));
             $guard_user->setEmailAddress($attributes['mail'][0]);
             $guard_user->setLastName($attributes['cn'][0]);
             $guard_user->setIsActive(true);
             $guard_user->save();
         }
         // Let the User signin
         // The auth is not rembered : the IdP can decide that
         $this->getUser()->signin($guard_user, $remember = false);
         // always redirect to a URL set in app.yml
         // or to the referer
         // or to the homepage
         $signinUrl = sfConfig::get('app_sf_guard_plugin_success_signin_url', $user_referer);
         return $this->redirect('' != $signinUrl ? $signinUrl : '@homepage');
     } else {
         if ($request->isXmlHttpRequest()) {
             $this->getResponse()->setHeaderOnly(true);
             $this->getResponse()->setStatusCode(401);
             return sfView::NONE;
         }
         // if we have been forwarded, then the referer is the current URL
         // if not, this is the referer of the current request
         $user->setReferer($this->getContext()->getActionStack()->getSize() > 1 ? $request->getUri() : $request->getReferer());
         /* gyufi $this->url_idp = $simpleSAMLAuth->login(array(
              //'saml:idp' => 'https://openidp.feide.no',
              'saml:idp' => 'https://aai.sztaki.hu/idp-partners',
              'saml:idp' => 'https://aai.sztaki.hu/idp',
            ));
            */
         $this->url_idp = $simpleSAMLAuth->login();
         // Nothing happened after there, $simpleSAMLAuth->login() calls exit()
         /*
               $module = sfConfig::get('sf_login_module');
               if ($this->getModuleName() != $module)
               {
                 return $this->redirect($module.'/'.sfConfig::get('sf_login_action'));
               }
         
               $this->getResponse()->setStatusCode(401);
         */
     }
 }
Example #2
0
 /**
  * Authenticate the user.
  *
  * This function authenticates the user.
  *
  * @param array &$state  The authentication request state.
  */
 private function authenticate(array &$state)
 {
     if (isset($state['isPassive']) && (bool) $state['isPassive']) {
         throw new SimpleSAML_Error_NoPassive('Passive authentication not supported.');
     }
     $this->authSource->login($state);
 }
Example #3
0
 /**
  * Authenticate the user.
  *
  * This function authenticates the user.
  *
  * @param array &$state  The authentication request state.
  */
 private function authenticate(array &$state)
 {
     if (isset($state['isPassive']) && (bool) $state['isPassive']) {
         throw new SimpleSAML_Error_NoPassive('Passive authentication not supported.');
     }
     $state['IdPMetadata'] = $this->getConfig()->toArray();
     $state['ReturnCallback'] = array('SimpleSAML_IdP', 'postAuth');
     $this->authSource->login($state);
 }
Example #4
0
 /**
  * Require admin access to the current page.
  *
  * This is a helper function for limiting a page to those with administrative access. It will redirect the user to
  * a login page if the current user doesn't have admin access.
  *
  * @return void This function will only return if the user is admin.
  * @throws \SimpleSAML_Error_Exception If no "admin" authentication source was configured.
  *
  * @author Olav Morken, UNINETT AS <*****@*****.**>
  * @author Jaime Perez, UNINETT AS <*****@*****.**>
  */
 public static function requireAdmin()
 {
     if (self::isAdmin()) {
         return;
     }
     // not authenticated as admin user, start authentication
     if (\SimpleSAML_Auth_Source::getById('admin') !== null) {
         $as = new \SimpleSAML_Auth_Simple('admin');
         $as->login();
     } else {
         throw new \SimpleSAML_Error_Exception('Cannot find "admin" auth source, and admin privileges are required.');
     }
 }
Example #5
0
 /**
  * Require admin access for current page.
  *
  * This is a helper-function for limiting a page to admin access. It will redirect
  * the user to a login page if the current user doesn't have admin access.
  */
 public static function requireAdmin()
 {
     if (self::isAdmin()) {
         return;
     }
     $returnTo = self::selfURL();
     /* Not authenticated as admin user. Start authentication. */
     if (SimpleSAML_Auth_Source::getById('admin') !== NULL) {
         $as = new SimpleSAML_Auth_Simple('admin');
         $as->login();
     } else {
         /* For backwards-compatibility. */
         $config = SimpleSAML_Configuration::getInstance();
         self::redirectTrustedURL('/' . $config->getBaseURL() . 'auth/login-admin.php', array('RelayState' => $returnTo));
     }
 }
Example #6
0
     $_SESSION["last_forward_from"] = $_SERVER["REFERER"];
 }
 // login with SAML
 if (!$saml_auth->isAuthenticated()) {
     if (subsite_manager_on_subsite()) {
         $site = elgg_get_site_entity();
         $main_site = $site->getOwnerEntity();
         $main_url = str_ireplace($site->url, $main_site->url, current_page_url());
         $redirect_url = $site->url . "mod/subsite_manager/procedures/simplesaml/redirect.php";
         SimpleSAML_Utilities::redirect($main_url, array("from" => $redirect_url));
     } else {
         if (get_input("from")) {
             $_SESSION["last_forward_from"] = $source;
         }
         // not logged in on IDP, so do that
         $saml_auth->login();
     }
 } else {
     // user is authenticated with IDP, so check in Elgg
     $saml_attributes = simplesaml_get_authentication_attributes($saml_auth, $source);
     // save the attributes for further use
     $_SESSION["saml_attributes"] = $saml_attributes;
     $_SESSION["saml_source"] = $source;
     // make sure we can find all users (even unvalidated)
     $hidden = access_get_show_hidden_status();
     access_show_hidden_entities(true);
     if ($user = simplesaml_find_user($source, $saml_attributes)) {
         // found a user, so login
         try {
             login($user);
             if (!empty($_SESSION["last_forward_from"]) && $_SESSION["last_forward_from"] == $source) {
 /**
  * Saves the chosen method name in the session and initialises
  * the external login process.
  *
  * @param $methodName
  * Name of the chosen login method
  */
 private function initLogin($methodName)
 {
     $method = $this->multiAuthPlugin->getMethod($methodName);
     if (!empty($method)) {
         // save selected method name
         $_SESSION['MA_methodName'] = $methodName;
         wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . ': ' . "SESSION['MA_methodName'] = {$methodName}");
         $libName = $this->multiAuthPlugin->getAuthLib($methodName);
         wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . ': ' . "Method auth settings: " . print_r($method['auth'], true));
         switch ($libName) {
             case 'simplesamlphp':
                 // init the external login
                 $ssphpPath = $this->multiAuthPlugin->config['paths']['libs']['simplesamlphp'];
                 require_once $ssphpPath . "/lib/_autoload.php";
                 $as = new SimpleSAML_Auth_Simple($method['auth']['spentityid']);
                 $return_url = $this->buildReturnURL($methodName);
                 wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . ': ' . "Redirecting to SSO login process: [SimpleSamlPHP] ReturnTo = {$return_url}");
                 if (isset($method['auth']['idpentityid'])) {
                     $as->login(array('ReturnTo' => $return_url, 'saml:idp' => $method['auth']['idpentityid']));
                 } else {
                     $as->login(array('ReturnTo' => $return_url));
                 }
                 exit;
                 break;
             default:
                 $target = $this->buildLink($methodName);
                 wfDebugLog('MultiAuthPlugin', __METHOD__ . ': ' . ': ' . "Redirecting to SSO login process: [URL] {$target}");
                 header("Location: " . $target);
                 exit;
                 break;
         }
     }
 }
Example #8
0
}
$asId = (string) $_REQUEST['as'];
$as = new SimpleSAML_Auth_Simple($asId);
if (array_key_exists('logout', $_REQUEST)) {
    $as->logout('/' . $config->getBaseURL() . 'logout.php');
}
if (array_key_exists(SimpleSAML_Auth_State::EXCEPTION_PARAM, $_REQUEST)) {
    // This is just a simple example of an error
    $state = SimpleSAML_Auth_State::loadExceptionState();
    assert('array_key_exists(SimpleSAML_Auth_State::EXCEPTION_DATA, $state)');
    $e = $state[SimpleSAML_Auth_State::EXCEPTION_DATA];
    header('Content-Type: text/plain');
    echo "Exception during login:\n";
    foreach ($e->format() as $line) {
        echo $line . "\n";
    }
    exit(0);
}
if (!$as->isAuthenticated()) {
    $url = SimpleSAML_Module::getModuleURL('core/authenticate.php', array('as' => $asId));
    $params = array('ErrorURL' => $url, 'ReturnTo' => $url);
    $as->login($params);
}
$attributes = $as->getAttributes();
$t = new SimpleSAML_XHTML_Template($config, 'status.php', 'attributes');
$t->data['header'] = '{status:header_saml20_sp}';
$t->data['attributes'] = $attributes;
// if saml:sp:IdP is set, this is SAML auth so we can pass a NameId
$t->data['nameid'] = !is_null($as->getAuthData('saml:sp:IdP')) ? $as->getAuthData('saml:sp:NameID') : FALSE;
$t->data['logouturl'] = \SimpleSAML\Utils\HTTP::getSelfURLNoQuery() . '?as=' . urlencode($asId) . '&logout';
$t->show();
Example #9
0
 public function connectAction()
 {
     $this->_helper->layout->disableLayout();
     $this->_helper->viewRenderer->setNoRender();
     $referer = trim($this->session->connectreferer);
     if (trim($referer) === "") {
         $referer = $_SERVER["HTTP_REFERER"];
         $this->session->connectreferer = $referer;
     }
     if (trim($referer) === "") {
         $referer = "https://" . $_SERVER["HTTP_HOST"];
     }
     //check if user is loggedin
     if (isset($this->session->userid) === false || is_numeric($this->session->userid) === false || intval($this->session->userid) <= 0) {
         header("Location: " . $referer);
         unset($this->session->connectreferer);
         return;
     }
     //Check if source is given
     $source = trim($this->_getParam("source"));
     if ($source == "") {
         header("Location: " . $referer);
         unset($this->session->connectreferer);
         return;
     }
     $authsource = str_replace("-sp", "", strtolower(trim($source)));
     $connectsource = str_replace("-sp", "-connect", $source);
     require_once SamlAuth::LIB_AUTOLOAD;
     //Initialize SAML
     $config = SimpleSAML_Configuration::getInstance();
     $t = new SimpleSAML_XHTML_Template($config, 'core:authsource_list.tpl.php');
     $t->data['sources'] = SimpleSAML_Auth_Source::getSourcesMatch('-connect');
     if (!in_array($connectsource, $t->data['sources'])) {
         header("Location: " . $referer);
         unset($this->session->connectreferer);
         $this->session->userError = array("title" => "Could not proceed with user account connection", "message" => "You tried to connect to a " . $authsource . " account. This type of connection is not supported.");
         exit;
     }
     //Check if SAML Authentication user account for connection is already authenticated
     $as = new SimpleSAML_Auth_Simple($connectsource);
     //In case a user is already authenticated with the source logout and redirect here again
     if ($as->isAuthenticated()) {
         $as->logout('https://' . $_SERVER["SERVER_NAME"] . '/saml/connect?source=' . $source);
         return;
     }
     //SAML Authentication new user account for connection
     //$as = new SimpleSAML_Auth_Simple($connectsource);
     //Do the login
     $as->login(array("ReturnTo" => "https://" . $_SERVER["HTTP_HOST"] . "/saml/postconnect?source=" . $source, "ErrorUrl" => "https://" . $_SERVER["HTTP_HOST"] . "/saml/postconnecterror?source=" . $source));
     return;
 }
Example #10
0
	/**
	 * Ajouter pour gepi : utilisation des cookies et requetes organisation
	 * Start an authentication process.
	 *
	 * This function never returns.
	 *
	 * This function accepts an array $params, which controls some parts of
	 * the authentication. The accepted parameters depends on the authentication
	 * source being used. Some parameters are generic:
	 *  - 'ErrorURL': An URL that should receive errors from the authentication.
	 *  - 'KeepPost': If the current request is a POST request, keep the POST
	 *    data until after the authentication.
	 *  - 'ReturnTo': The URL the user should be returned to after authentication.
	 *  - 'ReturnCallback': The function we should call after the user has
	 *    finished authentication.
	 *
	 * @param array $params  Various options to the authentication request.
	 */
	public function login(array $params = array()) {
		if (!isset($params['multiauth:preselect'])) {
			if (isset($_REQUEST['source'])) {
				$params['multiauth:preselect'] = $_REQUEST['source'];
			} else if (isset($_COOKIE['source'])) {
				$params['multiauth:preselect'] = $_COOKIE['source'];
			}
		}

		if (!isset($params['core:organization'])) {
			if (isset($_REQUEST['organization'])) {
				$params['core:organization'] = $_REQUEST['organization'];
			} else if (isset($_COOKIE['organization'])) {
				$params['core:organization'] = $_COOKIE['organization'];
			} else if (isset($_REQUEST['rne'])) {
				$params['core:organization'] = $_REQUEST['rne'];
			} else if (isset($_COOKIE['RNE'])) {
				$params['core:organization'] = $_COOKIE['RNE'];
			}
		}
		
		parent::login($params);
	}