getAttributes() public méthode

This function will retrieve the attributes of the current user if the user is authenticated. If the user isn't authenticated, it will return an empty array.
public getAttributes ( ) : array
Résultat array The users attributes.
Exemple #1
1
 public function __construct()
 {
     //	Obligatoire
     parent::__construct();
     $this->data = array();
     // System FED Oxylane
     if (FEDACTIVE) {
         require __DIR__ . '/../simplesaml/lib/_autoload.php';
         $as = new SimpleSAML_Auth_Simple('Oxylane-sp');
         $isAuth = $as->isAuthenticated();
         if (!$isAuth) {
             $as->requireAuth();
         } else {
             $attributes = $as->getAttributes();
             $this->data['fed']['0'] = $attributes['uid'][0];
             //identifiant
             $this->data['fed']['1'] = $attributes['cn'][0];
             //nom de la personne
             $this->data['fed']['2'] = $attributes['mail'][0];
             //mail de la personne
         }
     } else {
         $this->data['fed']['0'] = "ID";
         $this->data['fed']['1'] = "NOM";
         $this->data['fed']['2'] = "MAIL";
     }
     // END FED
     //	Chargement des ressources pour tout le contrôleur
     $this->load->database();
     $this->load->helper('form');
     $this->load->helper('titreUrl');
     $this->load->helper('convertlien');
     $this->load->library('form_validation');
     $this->load->model('pages_model', 'pm');
     $this->load->model('plannings_model', 'plm');
     $this->load->model('types_model', 'tm');
     $this->load->model('chaines_model', 'cm');
     $this->load->model('groupes_model', 'gm');
     $this->load->model('bandeau_model', 'bm');
     if (FEDLOG) {
         $this->load->model('logs_model', 'lm');
     }
     // Récupération de toute les chaines
     $this->data['chaines'] = $this->cm->getAll();
     $this->data['superadmin'] = true;
     //	Cette méthode permet de changer les délimiteurs par défaut des messages d'erreur (<p></p>).
     $this->form_validation->set_error_delimiters('<p class="alert alert-error fade in"><a class="close" data-dismiss="alert" href="#">&times;</a>', '</p>');
 }
 /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
 public function handle($request, Closure $next)
 {
     if ($this->auth->guest()) {
         if ($request->ajax()) {
             return response('Unauthorized.', 401);
         } else {
             //return redirect()->guest('auth/login')
             //tsipizic for SAML
             //login user and get attributes
             $as = new \SimpleSAML_Auth_Simple('default-sp');
             $as->requireAuth();
             $attributes = $as->getAttributes();
             //create user if he does not exist and log him in
             $mail = $attributes['mail'][0];
             $db_user = User::where('mail', $mail)->first();
             if ($db_user) {
                 Auth::login($db_user);
             } else {
                 $user = new User();
                 $user->mail = $mail;
                 $user->save();
                 Auth::login($user);
             }
         }
     }
     return $next($request);
 }
Exemple #3
0
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
 public function executeIndex(sfWebRequest $request)
 {
     if (!$request->getParameter('sf_culture')) {
         $ssaml = new SimpleSAML_Auth_Simple('default-sp');
         $attributes = $ssaml->getAttributes();
         if ($this->getUser()->isFirstRequest()) {
             if (array_key_exists('preferredLanguage', $attributes)) {
                 $culture = $attributes['preferredLanguage'];
                 if ($culture != 'hu' && $culture != 'en') {
                     $culture = $request->getPreferredCulture(array('en', 'hu'));
                 }
             } else {
                 $culture = $request->getPreferredCulture(array('en', 'hu'));
             }
             $this->getUser()->setCulture($culture);
             $this->getUser()->isFirstRequest(false);
         } else {
             $culture = $this->getUser()->getCulture();
         }
         $this->redirect('localized_homepage');
     }
     $p = Doctrine::getTable('Principal')->findOneByFedid($this->getUser()->getUsername());
     if ($p) {
         $oos = $p->getOrganization();
         $ros = $p->getRelatedOrganizations(TRUE);
     } else {
         $p = new Principal();
         $p->setFedid($this->getUser()->getUsername());
         $p->save();
     }
     $this->oos = $oos;
     $this->ros = $ros;
 }
Exemple #4
0
function get_attributes()
{
    // Only run in step 5 or later ! So change when steps array is changed!
    if (isset($_REQUEST['s'])) {
        if ($_REQUEST['s'] >= 4) {
            if ($ssp_location = issetweb('ssp_location')) {
                $ssp_autoloader = $ssp_location . '/lib/_autoload.php';
                if (is_readable($ssp_autoloader)) {
                    //echo "<pre>sesion:"; var_dump($_SESSION); echo "rquest"; var_dump($_REQUEST);
                    include_once $ssp_autoloader;
                    if ($ssp_authsource = issetweb('ssp_authsource')) {
                        $as = new SimpleSAML_Auth_Simple($ssp_authsource);
                        if (!$as->isAuthenticated()) {
                            $as->requireAuth();
                        }
                        $attributes = $as->getAttributes();
                        foreach (array_keys($attributes) as $at) {
                            // These are key|value pairs to populate the SELECT boxes
                            $simpleattrs[$at] = $at . " (" . $attributes[$at][0] . ")";
                        }
                        // Add attributes themselves as well, for later use
                        $simpleattrs['saml'] = $attributes;
                        //	echo "<pre>"; var_dump($simpleattrs);
                        ksort($simpleattrs);
                        return $simpleattrs;
                    }
                }
            }
        }
    }
    return false;
}
 /**
  * Performs an authentication attempt using SimpleSAMLphp
  *
  * @throws Zend_Auth_Adapter_Exception If authentication cannot be performed
  * @return Zend_Auth_Result
  */
 public function authenticate()
 {
     require_once LIBRARY_PATH . '/simplesamlphp/lib/_autoload.php';
     $as = new SimpleSAML_Auth_Simple('default-sp');
     $as->requireAuth();
     // If SimpleSAMLphp didn't stop it, then the user is logged in.
     return new Zend_Auth_Result(Zend_Auth_Result::SUCCESS, $as->getAttributes(), array("Authentication Successful"));
 }
 /**
  * Check that the user has access to the statistics.
  *
  * If the user doesn't have access, send the user to the login page.
  */
 public static function checkAccess(SimpleSAML_Configuration $statconfig)
 {
     $protected = $statconfig->getBoolean('protected', FALSE);
     $authsource = $statconfig->getString('auth', NULL);
     $allowedusers = $statconfig->getValue('allowedUsers', NULL);
     $useridattr = $statconfig->getString('useridattr', 'eduPersonPrincipalName');
     $acl = $statconfig->getValue('acl', NULL);
     if ($acl !== NULL && !is_string($acl) && !is_array($acl)) {
         throw new SimpleSAML_Error_Exception('Invalid value for \'acl\'-option. Should be an array or a string.');
     }
     if (!$protected) {
         return;
     }
     if (SimpleSAML\Utils\Auth::isAdmin()) {
         // User logged in as admin. OK.
         SimpleSAML_Logger::debug('Statistics auth - logged in as admin, access granted');
         return;
     }
     if (!isset($authsource)) {
         // If authsource is not defined, init admin login.
         SimpleSAML\Utils\Auth::requireAdmin();
     }
     /* We are using an authsource for login. */
     $as = new SimpleSAML_Auth_Simple($authsource);
     $as->requireAuth();
     // User logged in with auth source.
     SimpleSAML_Logger::debug('Statistics auth - valid login with auth source [' . $authsource . ']');
     // Retrieving attributes
     $attributes = $as->getAttributes();
     if (!empty($allowedusers)) {
         // Check if userid exists
         if (!isset($attributes[$useridattr][0])) {
             throw new Exception('User ID is missing');
         }
         // Check if userid is allowed access..
         if (in_array($attributes[$useridattr][0], $allowedusers)) {
             SimpleSAML_Logger::debug('Statistics auth - User granted access by user ID [' . $attributes[$useridattr][0] . ']');
             return;
         }
         SimpleSAML_Logger::debug('Statistics auth - User denied access by user ID [' . $attributes[$useridattr][0] . ']');
     } else {
         SimpleSAML_Logger::debug('Statistics auth - no allowedUsers list.');
     }
     if (!is_null($acl)) {
         $acl = new sspmod_core_ACL($acl);
         if ($acl->allows($attributes)) {
             SimpleSAML_Logger::debug('Statistics auth - allowed access by ACL.');
             return;
         }
         SimpleSAML_Logger::debug('Statistics auth - denied access by ACL.');
     } else {
         SimpleSAML_Logger::debug('Statistics auth - no ACL configured.');
     }
     throw new SimpleSAML_Error_Exception('Access denied to the current user.');
 }
 /**
  * @inheritDoc
  */
 public function persistNewAccessToken(AccessTokenEntityInterface $accessTokenEntity)
 {
     $as = $this->config->getString('auth');
     $auth = new \SimpleSAML_Auth_Simple($as);
     // We should be authenticated so this returns the session user attributes (or [] if not)
     $attributes = $auth->getAttributes();
     $scopes = [];
     foreach ($accessTokenEntity->getScopes() as $scope) {
         $scopes[] = $scope->getIdentifier();
     }
     $this->conn->insert($this->getTableName(), ['id' => $accessTokenEntity->getIdentifier(), 'scopes' => $scopes, 'attributes' => $attributes, 'expires_at' => $accessTokenEntity->getExpiryDateTime(), 'user_id' => $accessTokenEntity->getUserIdentifier(), 'client_id' => $accessTokenEntity->getClient()->getIdentifier()], ['string', 'json_array', 'json_array', 'datetime', 'string', 'string']);
 }
 public function downloadAction()
 {
     $this->_helper->viewRenderer->setNoRender(true);
     $this->_helper->layout->disableLayout();
     $filename = APPLICATION_ROOT . '/public_html/files/' . $this->_getParam('filename');
     $filename = realpath($filename);
     try {
         $file = new SxCms_File($filename);
         $data = $file->getCleanFile();
         $identity = Zend_Auth::getInstance()->getIdentity();
         if (!$file->isAllowed($identity)) {
             $this->_helper->redirector->setExit(true)->gotoSimple('unauthorized', 'index');
             return;
         }
         if ($file->isApb()) {
             $as = new SimpleSAML_Auth_Simple('klavsts');
             $attributes = $as->getAttributes();
             if (!$attributes) {
                 $this->_forward('unauthorized', 'index', null, array('url' => $this->view->url()));
                 return;
             }
             $attributes = $attributes['urn:klav:docmanager'];
             $filecheck = new SxCms_Filesystem($file->getPath());
             $filecheck->setApb($attributes);
             if (!$filecheck->isAllowed()) {
                 $this->_helper->redirector->setExit(true)->gotoSimple('unauthorized', 'index');
                 return;
             }
         }
         // workaround for when PECL class finfo is not installed
         $mimeType = 'application/octet-stream';
         if (@class_exists('finfo')) {
             $finfo = new finfo(FILEINFO_MIME);
             $mimeType = $finfo->file($filename);
         }
         // mimetype "unknown", let's figure it out by filename extension
         if ($mimeType == 'application/octet-stream') {
             $ext = strtolower(end(explode('.', $filename)));
             $types = simplexml_load_file(APPLICATION_PATH . '/var/mime-types.xml');
             $result = $types->xpath('//mime-types/mime-type/ext[. ="' . $ext . '"]/..');
             $result = $result[0]->attributes();
             $result = (string) $result['name'];
             $mimeType = $result;
         }
         $size = mb_strlen($data);
         $this->getResponse()->setHeader('Content-Type', $mimeType)->setHeader('Content-Length', $size);
         echo $data;
     } catch (Exception $e) {
         throw new Zend_Controller_Action_Exception('File not found', 404);
     }
 }
Exemple #9
0
 function procesarFormulario()
 {
     $saml_lib_path = '/var/simplesamlphp/lib/_autoload.php';
     require_once $saml_lib_path;
     // $aplication_base_url = 'http://10.20.0.38/splocal/';
     $aplication_base_url = $this->host . $this->site . '/';
     $source = 'SPcrono';
     // Fuente de autenticación definida en el authsources del SP
     $as = new SimpleSAML_Auth_Simple($source);
     // Se pasa como parametro la fuente de autenticación
     $login_params = array('ReturnTo' => $aplication_base_url . 'index.php');
     $as->requireAuth($login_params);
     $aaa = $as->getAttributes();
     return false;
 }
 /**
  * @METHOD crear_sesion
  *
  * Crea una nueva sesión en la base de datos.
  * @PARAM usuario_aplicativo
  * @PARAM nivel_acceso
  * @PARAM expiracion
  * @PARAM conexion_id
  *
  * @return boolean
  * @access public
  */
 function crearSesion()
 {
     $saml_lib_path = '/var/simplesamlphp/lib/_autoload.php';
     require_once $saml_lib_path;
     // $aplication_base_url = 'http://10.20.0.38/splocal/';
     $aplication_base_url = $this->hostSSO . $this->site . '/';
     $source = $this->SPSSO;
     // Fuente de autenticación definida en el authsources del SP
     $as = new SimpleSAML_Auth_Simple($source);
     // Se pasa como parametro la fuente de autenticación
     $login_params = array('ReturnTo' => $aplication_base_url . 'index.php');
     $as->requireAuth($login_params);
     $atributos = $as->getAttributes();
     $this->sesionUsuario->crearSesion($atributos['usuario'][0]);
     return $atributos;
 }
 public function authenticate()
 {
     try {
         $as = new \SimpleSAML_Auth_Simple($this->_domain);
         $globalConfig = \SimpleSAML_Configuration::getInstance();
         //$globalConfig::setConfigDir(G_CONFIGDIR.'saml/');
         $as->requireAuth();
         if ($as->isAuthenticated()) {
             $attributes = $as->getAttributes();
             if (!array_key_exists($this->_sso_settings['saml_email'], $attributes)) {
                 // 					TemplateController::setMessage(("A valid email is needed for account related communication").". ".("Check that the %s attribute (%s) defined in your configuration is correct",("Email"),$this->_sso_settings['saml_email']), 'error');
                 $this->ssoLogout();
             } elseif (!array_key_exists($this->_sso_settings['saml_first_name'], $attributes)) {
                 // 					TemplateController::setMessage(("'%s' is required",("First name")).". ".("Check that the %s attribute (%s) defined in your configuration is correct",("First name"),$this->_sso_settings['saml_first_name']), 'error');
                 $this->ssoLogout();
             } elseif (!array_key_exists($this->_sso_settings['saml_last_name'], $attributes)) {
                 // 					TemplateController::setMessage(("'%s' is required",("Last name")).". ".("Check that the %s attribute (%s) defined in your configuration is correct",("Last name"),$this->_sso_settings['saml_last_name']), 'error');
                 $this->ssoLogout();
             } else {
                 if (trim($attributes[$this->_sso_settings['saml_email']][0]) == '') {
                     $attributes[$this->_sso_settings['saml_email']][0] = " ";
                     // 						TemplateController::setMessage(("A valid email is needed for account related communication"), 'error');
                 }
                 if (trim($attributes[$this->_sso_settings['saml_first_name']][0]) == '' && trim($attributes[$this->_sso_settings['saml_last_name']][0]) == '') {
                     $attributes[$this->_sso_settings['saml_first_name']][0] = ' ';
                     $attributes[$this->_sso_settings['saml_last_name']][0] = ' ';
                 } else {
                     if (trim($attributes[$this->_sso_settings['saml_first_name']][0]) == '') {
                         $attributes[$this->_sso_settings['saml_first_name']][0] = $attributes[$this->_sso_settings['saml_last_name']][0];
                     }
                     if (trim($attributes[$this->_sso_settings['saml_last_name']][0]) == '') {
                         $attributes[$this->_sso_settings['saml_last_name']][0] = $attributes[$this->_sso_settings['saml_first_name']][0];
                     }
                 }
                 $this->_login($attributes);
                 //pr($attributes);exit;
                 //echo "redirect now";exit;
                 //\SimpleSAML_Utilities::postRedirect("https://index.php", $attributes);
             }
         }
     } catch (\SimpleSAML_Error_Error $e) {
         $this->_samlErrorHandler($e);
     } catch (\Exception $e) {
         handleNormalFlowExceptions($e);
     }
     return $this;
 }
 public function beforeProcess(&$action)
 {
     if (CopixConfig::get('conf_Saml_actif') != 1) {
         return;
     }
     require_once COPIX_UTILS_PATH . '../../simplesamlphp/lib/_autoload.php';
     $asId = 'iconito-sql';
     if (CopixConfig::exists('default|conf_Saml_authSource') && CopixConfig::get('default|conf_Saml_authSource')) {
         $asId = CopixConfig::get('default|conf_Saml_authSource');
     }
     $as = new SimpleSAML_Auth_Simple($asId);
     $ppo->user = _currentUser();
     if ($as->isAuthenticated() && !$ppo->user->isConnected()) {
         $attributes = $as->getAttributes();
         $uidAttribute = 'login_dbuser';
         if (CopixConfig::exists('default|conf_Saml_uidAttribute') && CopixConfig::get('default|conf_Saml_uidAttribute')) {
             $uidAttribute = CopixConfig::get('default|conf_Saml_uidAttribute');
         }
         $ppo->saml_user = null;
         if (isset($attributes[$uidAttribute]) && isset($attributes[$uidAttribute][0])) {
             $ppo->saml_user = $attributes[$uidAttribute][0];
         }
         if ($ppo->saml_user) {
             $ppo->iconito_user = Kernel::getUserInfo("LOGIN", $ppo->saml_user);
             if ($ppo->iconito_user['login']) {
                 _currentUser()->login(array('login' => $ppo->iconito_user['login'], 'assistance' => true));
                 $url_return = CopixUrl::get('kernel||doSelectHome');
                 // $url_return = CopixUrl::get ('assistance||users');
                 return new CopixActionReturn(COPIX_AR_REDIRECT, $url_return);
             } else {
                 $ppo->cas_error = 'no-iconito-user';
                 return _arPpo($ppo, 'cas.tpl');
             }
         }
     }
     if (!$as->isAuthenticated() && $ppo->user->isConnected()) {
         $ppo->user = _currentUser();
         if ($ppo->user->isConnected()) {
             CopixAuth::getCurrentUser()->logout(array());
             CopixEventNotifier::notify('logout', array('login' => CopixAuth::getCurrentUser()->getLogin()));
             CopixAuth::destroyCurrentUser();
             CopixSession::destroyNamespace('default');
         }
     }
 }
Exemple #13
0
 public function __construct()
 {
     //	Obligatoire
     parent::__construct();
     $this->data = array();
     // System FED Oxylane
     if (FEDACTIVE) {
         require __DIR__ . '/../simplesaml/lib/_autoload.php';
         $as = new SimpleSAML_Auth_Simple('Oxylane-sp');
         $isAuth = $as->isAuthenticated();
         $url = $as->getLoginURL();
         if (!$isAuth) {
             //$url = $as->getLoginURL();
             //echo '<p>You are not authenticated. <a href="' . htmlspecialchars($url) . '">Log in</a>.</p>';
             $as->requireAuth();
         } else {
             //$url = $as->getLogoutURL();
             //echo '<p>You are currently authenticated. <a href="' . htmlspecialchars($url) . '">Log out</a>.</p>';
             $attributes = $as->getAttributes();
             $uid = $attributes['uid'][0];
             $this->data['fed']['0'] = $uid;
             $this->data['fed']['1'] = $attributes['cn'][0];
             $this->data['fed']['2'] = $attributes['mail'][0];
             $this->load->model('admins_model', 'am');
             $admins = $this->am->getAll();
             if (!$this->in_array_column($uid, $admins)) {
                 echo "Utilisateur non autoris&eacute;s";
                 redirect('welcome', 'refresh');
             }
         }
     } else {
         $this->data['fed']['0'] = "ID";
         $this->data['fed']['1'] = "NOM";
         $this->data['fed']['2'] = "MAIL";
     }
     // END System FED Oxylane
     //	Chargement des ressources pour tout le contrôleur
     $this->load->database();
     $this->load->helper('form');
     $this->load->library('form_validation');
     $this->load->model('pages_model', 'pm');
     $this->load->model('chaines_model', 'cm');
     $this->load->model('groupes_model', 'gm');
     $this->load->model('logs_model', 'lm');
 }
function getUser(SimpleSAML_Auth_Simple $as, ConfigProxy $janus_config)
{
    // Get data from config
    /** @var string $useridattr */
    $useridattr = $janus_config->getValue('useridattr', 'eduPersonPrincipalName');
    // Validate user
    $attributes = $as->getAttributes();
    // Check if userid exists
    if (!isset($attributes[$useridattr])) {
        echo json_encode(array('status' => 'user_id_is_missing'));
        exit;
    }
    $userid = $attributes[$useridattr][0];
    $user = new sspmod_janus_User();
    $user->setUserid($userid);
    $user->load(sspmod_janus_User::USERID_LOAD);
    return $user;
}
Exemple #15
0
 /**
  * Retrieve the current user ID.
  *
  * @return string  The current user ID, or NULL if the user isn't authenticated.
  */
 public function getUserId()
 {
     if (!$this->authSource->isAuthenticated()) {
         return NULL;
     }
     $attributes = $this->authSource->getAttributes();
     if (!array_key_exists($this->usernameAttribute, $attributes)) {
         throw new SimpleSAML_Error_Exception('Missing username attribute ' . var_export($this->usernameAttribute, TRUE) . ' in the attributes of the user.');
     }
     $values = array_values($attributes[$this->usernameAttribute]);
     if (empty($values)) {
         throw new SimpleSAML_Error_Exception('Username attribute was empty.');
     }
     if (count($values) > 1) {
         throw new SimpleSAML_Error_Exception('More than one attribute value in username.');
     }
     $userId = $values[0];
     return $userId;
 }
 public function loginAction()
 {
     //$logger = Zend_Registry::get('logger');
     //$logger->log('bericht hier', Zend_Log::INFO);
     $this->_helper->viewRenderer->setNoRender(true);
     $this->_helper->layout->disableLayout();
     $config = Zend_Registry::get('config');
     $url = $config->system->web->url . $config->system->web->baseurl;
     $as = new SimpleSAML_Auth_Simple('klavsts');
     $options = array('saml:IsPassive' => true, 'KeepPost' => false, 'ReturnTo' => $this->view->url(), 'ErrorURL' => $url . '/index/unauthorized');
     $as->requireAuth($options);
     $attributes = $as->getAttributes();
     $user = new SxCms_User_Klav();
     $user->setFirstName($attributes['urn:klav:data:Username'][0]);
     $user->setEmail($attributes['urn:klav:data:Email'][0]);
     $user->setDoccheck($attributes['urn:klav:data:doccheck'][0]);
     $user->setFarmanager($attributes['urn:klav:data:farmanager']);
     $user->setClientId($attributes['urn:klav:data:client'][0]);
     $user->setLanguage($attributes['urn:klav:data:taal_cd'][0]);
     $user->setGroups($attributes['urn:klav:groups']);
     $user->setDocmanager($attributes['urn:klav:docmanager']);
     $user->setClients($attributes['urn:klav:clients']);
     $user->setNamed($attributes['urn:klav:data:named'][0]);
     $user->setSessionId($attributes['urn:klav:sessionid'][0]);
     $user->setUsername($attributes['UserName'][0]);
     $mapper = new SxCms_Group_DataMapper();
     $groups = $attributes['groups'];
     foreach ($groups as $samlId) {
         $group = $mapper->getBySamlId($samlId);
         if ($group) {
             $user->addGroup($group);
         }
     }
     $auth = Zend_Auth::getInstance();
     $storage = $auth->getStorage();
     $storage->write($user);
     // full requested url
     $burl = $this->_getParam('url', '');
     $burl = base64_decode($burl);
     $burl = urldecode($burl);
     $burl = 'http://' . $this->getRequest()->getHttpHost() . $burl;
     $this->_helper->redirector->setGotoUrl($burl);
 }
Exemple #17
0
 public function authenticate(TokenInterface $token)
 {
     /** @var string $authenticationType */
     $authenticationType = $this->config->getValue('auth', 'login-admin');
     if (php_sapi_name() === 'cli') {
         return $this->getTokenForUsername($authenticationType);
     }
     $as = new \SimpleSAML_Auth_Simple($authenticationType);
     if (!$as->isAuthenticated()) {
         throw new AuthenticationException("Authsource '{$authenticationType}' is invalid");
     }
     /** @var string $userIdAttributeName */
     $userIdAttributeName = $this->config->getValue('useridattr', 'eduPersonPrincipalName');
     // Check if userid exists
     $attributes = $as->getAttributes();
     if (!isset($attributes[$userIdAttributeName])) {
         throw new AuthenticationException("Attribute '{$userIdAttributeName}' with User ID is missing.");
     }
     return $this->getTokenForUsername($attributes[$userIdAttributeName][0]);
 }
Exemple #18
0
 function mostrarBotonLogin()
 {
     //configuración de simplesaml para autenticación SSO (single sign ON)
     $saml_lib_path = '/var/simplesamlphp/lib/_autoload.php';
     require_once $saml_lib_path;
     $aplication_base_url = $this->host . $this->site;
     $source = 'SP_SNIES';
     # Fuente de autenticación definida en el authsources del SP
     $as = new SimpleSAML_Auth_Simple($source);
     # Se pasa como parametro la fuente de autenticación
     //var_dump($as->isAuthenticated());
     if (!$as->isAuthenticated()) {
         $this->formulario();
     } else {
         //$valorCodificado = "action=loginSso";
         $valorCodificado = "&pagina=listadoVariablesSnies";
         //$esteBloque=$this->miConfigurador->getVariableConfiguracion ( 'esteBloque' );
         //$valorCodificado .= "&bloque=" . $esteBloque ['nombre'];
         //$valorCodificado .= "&bloqueGrupo=" . $esteBloque ["grupo"];
         $valorCodificado = $this->miConfigurador->fabricaConexiones->crypto->codificar($valorCodificado);
         //Mostrar enlace
         //Rescatar el parámetro enlace desde los datos de configuraión en la base de datos
         $variable = $this->miConfigurador->getVariableConfiguracion("enlace");
         $miEnlace = $this->host . $this->site . '/index.php?' . $variable . '=' . $valorCodificado;
         header("Location: " . $miEnlace);
         //var_dump($miEnlace);
         $attributes = $as->getAttributes();
         if (empty($attributes)) {
             echo 'No se obtuvieron atributos del usuario';
         } else {
             echo '<table class="table table-bordered table-striped">';
             foreach ($attributes as $key => $values) {
                 echo '<tr><td>' . $key . '</td><td>';
                 echo implode('<br>', $values);
                 echo '</td></tr>';
             }
             echo '</table>';
         }
         //echo '<p><a class="btn" href="logout.php">Cerrar sesión</a></p>';
     }
 }
Exemple #19
0
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
 public function executeIndex(sfWebRequest $request)
 {
     if (!$request->getParameter('sf_culture')) {
         $ssaml = new SimpleSAML_Auth_Simple('default-sp');
         $attributes = $ssaml->getAttributes();
         //die(var_dump($attributes['preferredLanguage']));
         if ($this->getUser()->isFirstRequest()) {
             if (array_key_exists('preferredLanguage', $attributes)) {
                 $culture = $attributes['preferredLanguage'];
                 if ($culture != 'hu' && $culture != 'en') {
                     $culture = $request->getPreferredCulture(array('hu', 'en'));
                 }
             } else {
                 $culture = $request->getPreferredCulture(array('hu', 'en'));
             }
             $this->getUser()->setCulture($culture);
             $this->getUser()->isFirstRequest(false);
         } else {
             $culture = $this->getUser()->getCulture();
         }
         $this->redirect('localized_homepage');
     }
 }
Exemple #20
0
 /**
  * Process a request.
  *
  * This function never returns.
  *
  * @param Auth_OpenID_Request $request  The request we are processing.
  */
 public function processRequest(array $state)
 {
     assert('isset($state["request"])');
     $request = $state['request'];
     $sreg_req = Auth_OpenID_SRegRequest::fromOpenIDRequest($request);
     $ax_req = Auth_OpenId_AX_FetchRequest::fromOpenIDRequest($request);
     /* In resume.php there should be a way to display data requested through sreg or ax. */
     if (!$this->authSource->isAuthenticated()) {
         if ($request->immediate) {
             /* Not logged in, and we cannot show a login form. */
             $this->sendResponse($request->answer(FALSE));
         }
         $resumeURL = $this->getStateURL('resume.php', $state);
         $this->authSource->requireAuth(array('ReturnTo' => $resumeURL));
     }
     $identity = $this->getIdentity();
     assert('$identity !== FALSE');
     /* Should always be logged in here. */
     if (!$request->idSelect() && $identity !== $request->identity) {
         /* The identity in the request doesn't match the one of the logged in user. */
         throw new SimpleSAML_Error_Exception('Logged in as different user than the one requested.');
     }
     if ($this->isTrusted($identity, $request->trust_root)) {
         $trusted = TRUE;
     } elseif (isset($state['TrustResponse'])) {
         $trusted = (bool) $state['TrustResponse'];
     } else {
         if ($request->immediate) {
             /* Not trusted, and we cannot show a trust-form. */
             $this->sendResponse($request->answer(FALSE));
         }
         $trustURL = $this->getStateURL('trust.php', $state);
         SimpleSAML_Utilities::redirectTrustedURL($trustURL);
     }
     if (!$trusted) {
         /* The user doesn't trust this site. */
         $this->sendResponse($request->answer(FALSE));
     }
     $response = $request->answer(TRUE, NULL, $identity);
     //Process attributes
     $attributes = $this->authSource->getAttributes();
     foreach ($attributes as $key => $attr) {
         if (is_array($attr) && count($attr) === 1) {
             $attributes[$key] = $attr[0];
         }
     }
     $pc = new SimpleSAML_Auth_ProcessingChain($this->authProc, array(), 'idp');
     $state = array('Attributes' => $attributes, 'isPassive' => TRUE);
     $pc->processStatePassive(&$state);
     $attributes = $state['Attributes'];
     //Process SREG requests
     $sreg_resp = Auth_OpenID_SRegResponse::extractResponse($sreg_req, $attributes);
     $sreg_resp->toMessage($response->fields);
     //Process AX requests
     $ax_resp = new Auth_OpenID_AX_FetchResponse();
     foreach ($ax_req->iterTypes() as $type_uri) {
         if (isset($attributes[$type_uri])) {
             $ax_resp->addValue($type_uri, $attributes[$type_uri]);
         }
     }
     $ax_resp->toMessage($response->fields);
     /* The user is authenticated, and trusts this site. */
     $this->sendResponse($response);
 }
Exemple #21
0
 * @copyright  2009 Jacob Christiansen
 * @license    http://www.opensource.org/licenses/mit-license.php MIT License
 * @link       http://github.com/janus-ssp/janus/
 * @since      File available since Release 1.5.1
 */
require __DIR__ . '/_includes.php';
// Initial setup
$config = SimpleSAML_Configuration::getInstance();
$janus_config = sspmod_janus_DiContainer::getInstance()->getConfig();
$authsource = $janus_config->getValue('auth', 'login-admin');
$useridattr = $janus_config->getValue('useridattr', 'eduPersonPrincipalName');
$et = new SimpleSAML_XHTML_Template($config, 'janus:editentity.php', 'janus:editentity');
$as = new SimpleSAML_Auth_Simple($authsource);
// Validate user
if ($as->isAuthenticated()) {
    $attributes = $as->getAttributes();
    // Check if userid exists
    if (!isset($attributes[$useridattr])) {
        throw new Exception('User ID is missing');
    }
    $userid = $attributes[$useridattr][0];
} else {
    echo $et->t('error_no_access');
    exit;
}
// Get Entity controller
$mcontroller = sspmod_janus_DiContainer::getInstance()->getEntityController();
// Get the user
$user = new sspmod_janus_User();
$user->setUserid($userid);
$user->load(sspmod_janus_User::USERID_LOAD);
    reqLib('eyeSessions', 'checkAndSstartSession');
    service('extern', 'getFile', array($myExtern, $type), 1);
} elseif (isset($_GET['api'])) {
    require_once EYE_ROOT . '/xml-rpc/server.eyecode';
    xmlrpc_parseRequest();
} else {
    //Loading eyeWidgets definitions
    reqLib('eyeWidgets', 'loadWidgets');
    //Starting a simple session
    reqLib('eyeSessions', 'startSession');
    //for SAML 2.0 authentication abay
    global $ssoUser;
    global $ssoUserGroup;
    if (empty($ssoUser)) {
        $sa = new SimpleSAML_Auth_Simple('default-sp');
        $attributes = $sa->getAttributes();
        $ssoUser = $attributes["UserName"][0];
        $ssoUserGroup = $attributes["urn:oid:1.3.6.1.4.1.5923.1.1.1.5"][0];
    }
    //If widget table does not exist, create it
    reqLib('eyeWidgets', 'checkTable');
    //if a shorturl is present
    if (!empty($myInfo)) {
        //check if the shorturl exists, and get the msg and checknum associated to it
        if (is_array($_SESSION['shortUrls'][$myInfo])) {
            $msg = $_SESSION['shortUrls'][$myInfo]['msg'];
            $checknum = $_SESSION['shortUrls'][$myInfo]['checknum'];
            $_GET['msg'] = $msg;
            $_REQUEST['msg'] = $msg;
            $_GET['checknum'] = $checknum;
            $_REQUEST['checknum'] = $checknum;
Exemple #23
0
function authenticated_via_saml(&$saml_username = NULL, &$saml_displayname = NULL)
{
    global $SAML_options, $debug_mode, $auto_tags;
    if (!file_exists($SAML_options['simplesamlphp_basedir'] . '/lib/_autoload.php')) {
        throw new RackTablesError('Configured for SAML authentication, but simplesaml is not found.', RackTablesError::MISCONFIGURED);
    }
    require_once $SAML_options['simplesamlphp_basedir'] . '/lib/_autoload.php';
    $as = new SimpleSAML_Auth_Simple($SAML_options['sp_profile']);
    if (!$as->isAuthenticated()) {
        $as->requireAuth();
    }
    $attributes = $as->getAttributes();
    $saml_username = saml_getAttributeValue($attributes, $SAML_options['usernameAttribute']);
    $saml_displayname = saml_getAttributeValue($attributes, $SAML_options['fullnameAttribute']);
    if (array_key_exists('groupListAttribute', $SAML_options)) {
        foreach (saml_getAttributeValues($attributes, $SAML_options['groupListAttribute']) as $autotag) {
            $auto_tags[] = array('tag' => '$sgcn_' . $autotag);
        }
    }
    return $as->isAuthenticated();
}
Exemple #24
0
<?php 
global $CONNECT, $RESULT, $DBDATABASE, $DBUSER, $DBPASSWORD;
require_once "/var/www/simplesamlphp/lib/_autoload.php";
$auth = new SimpleSAML_Auth_Simple("osm");
$DBHOST = "localhost";
$DBDATABASE = "pedro";
$DBUSER = "******";
$DBPASSWORD = "******";
$CONNECT = pg_connect("host={$DBHOST} dbname={$DBDATABASE} password={$DBPASSWORD} user={$DBUSER}") or die("Databaze je down.");
$set = pg_query($CONNECT, "set client_encoding to UNICODE;");
$logged = false;
if (!$auth->isAuthenticated()) {
    echo "Uživatel nepřihlášen - <a href=\"" . $auth->getLoginURL() . "\">přihlásit</a>";
}
if ($auth->isAuthenticated()) {
    $attr = $auth->getAttributes();
    $user_id = '';
    $user_nick = '';
    $osm_user = '';
    if (isset($attr["id"])) {
        $user_id = $attr["id"][0];
    }
    if (isset($attr["nick"])) {
        $user_nick = $attr["nick"][0];
    }
    if (isset($attr["osm_user"])) {
        $logged = true;
    }
}
if ($logged) {
    echo "Přihlášen jako " . $user_nick . " - ";
    }
}
// taken from Moodle clean_param - make sure the wantsurl is correctly formed
include_once 'validateurlsyntax.php';
if (!validateUrlSyntax($wantsurl, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
    $wantsurl = $CFG->wwwroot;
}
// trim off any reference to login and stash
$_SESSION['wantsurl'] = preg_replace('/\\&login$/', '', $wantsurl);
// now - are we logged in?
$as->requireAuth();
// ensure that $_SESSION is cleared for simplesamlphp
if (isset($_SESSION['wantsurl'])) {
    unset($_SESSION['wantsurl']);
}
$saml_attributes = $as->getAttributes();
@session_write_close();
// now - let's continue with the session handling that would normally be done
// by Maharas init.php
// the main thin is that it sets the session cookie name back to what it should be
// session_name(get_config('cookieprefix') . 'mahara');
// and starts the session again
// ***********************************************************************
// copied from original init.php
// ***********************************************************************
// Only do authentication once we know the page theme, so that the login form
// can have the correct theming.
require_once dirname(dirname(dirname(__FILE__))) . '/auth/lib.php';
$SESSION = Session::singleton();
$USER = new LiveUser();
$THEME = new Theme($USER);
 public function processLogin()
 {
     require_once COPIX_UTILS_PATH . '../../simplesamlphp/lib/_autoload.php';
     $asId = 'iconito-sql';
     if (CopixConfig::exists('default|conf_Saml_authSource') && CopixConfig::get('default|conf_Saml_authSource')) {
         $asId = CopixConfig::get('default|conf_Saml_authSource');
     }
     $as = new SimpleSAML_Auth_Simple($asId);
     $_SESSION['chartValid'] = false;
     $ppo = new CopixPPO();
     $ppo->user = _currentUser();
     if ($ppo->user->isConnected()) {
         $url_return = CopixUrl::get('kernel||doSelectHome');
         /*
          * PATCH FOR CHARTE
          */
         $this->user->forceReload();
         if (!$this->service('charte|CharteService')->checkUserValidation()) {
             $this->flash->redirect = $url_return;
             return $this->go('charte|charte|valid');
         }
         return _arRedirect($url_return);
         //return new CopixActionReturn (COPIX_AR_REDIRECT, $url_return);
     } else {
         $as->requireAuth();
         $attributes = $as->getAttributes();
         /*
         echo "<pre>";
         print_r($attributes);
         die();
         */
         $uidAttribute = 'login_dbuser';
         if (CopixConfig::exists('default|conf_Saml_uidAttribute') && CopixConfig::get('default|conf_Saml_uidAttribute')) {
             $uidAttribute = CopixConfig::get('default|conf_Saml_uidAttribute');
         }
         $ppo->saml_user = null;
         if (isset($attributes[$uidAttribute]) && isset($attributes[$uidAttribute][0])) {
             $ppo->saml_user = $attributes[$uidAttribute][0];
         } else {
             $ppo->saml_error = 'bad-conf-uidattribute';
             return _arPpo($ppo, 'saml-error.tpl');
         }
         if ($ppo->saml_user) {
             $ppo->iconito_user = Kernel::getUserInfo("LOGIN", $ppo->saml_user);
             if ($ppo->iconito_user['login']) {
                 _currentUser()->login(array('login' => $ppo->iconito_user['login'], 'assistance' => true));
                 $url_return = CopixUrl::get('kernel||doSelectHome');
                 // $url_return = CopixUrl::get ('assistance||users');
                 return new CopixActionReturn(COPIX_AR_REDIRECT, $url_return);
             } else {
                 $ppo->saml_error = 'no-iconito-user';
                 return _arPpo($ppo, 'saml-error.tpl');
             }
         }
     }
     // $as->getLoginURL();
     /*
     if (!$as->isAuthenticated()) {
     	$url = SimpleSAML_Module::getModuleURL('core/authenticate.php', array('as' => $asId));
     	$params = array(
     		'ErrorURL' => CopixUrl::get ('auth|saml|test_error'),
     		'ReturnTo' => CopixUrl::get ('auth|saml|test_ok'),
     	);
     	$as->login($params);
     }
     */
     /*
     $attributes = $as->getAttributes();
     
     echo "<pre>";
     print_r($attributes);
     die();
     */
 }
Exemple #27
0
/**
 * Get the attributes from an SAML authentication exchange.
 *
 * These attributes can include all kinds of information, for example:
 * - firstname
 * - lastname
 * - email address
 * - etc.
 *
 * @param SimpleSAML_Auth_Simple $saml_auth the Authentication object from the SimpleSAMLPHP library
 * @param string                 $source    the name of the Service Provider
 *
 * @return bool|array an array with the provided attributes, false on failure
 */
function simplesaml_get_authentication_attributes(SimpleSAML_Auth_Simple $saml_auth, $source)
{
    $result = false;
    if (!empty($saml_auth) && $saml_auth instanceof SimpleSAML_Auth_Simple && !empty($source)) {
        $result = $saml_auth->getAttributes();
        $auth_source = $saml_auth->getAuthSource();
        if ($auth_source instanceof sspmod_saml_Auth_Source_SP) {
            // only check extra data for SAML sources
            $setting = elgg_get_plugin_setting($source . "_external_id", "simplesaml");
            if (!empty($setting)) {
                $external_id = $saml_auth->getAuthData($setting);
                if (!empty($external_id)) {
                    $result["elgg:external_id"] = array($external_id["Value"]);
                }
            }
        }
    }
    return $result;
}
Exemple #28
0
<?php

//require_once('/var/simplesamlphp/lib/_autoload.php');
require_once 'c:/simplesaml/lib/_autoload.php';
$as = new SimpleSAML_Auth_Simple('mewSQLAuth');
$as->requireAuth();
//$as = new SimpleSAML_Auth_Simple('mewSQLStatic');
//$as->requireAuth( array('saml:idp' => 'http://localhost/simplesaml') );
////$as->requireAuth( array('KeepPost' => TRUE, 'loginNames' => $_GET['loginNames']));
$attributes[] = $as->getAttributes();
$authSource = $as->getAuthSource();
$session = SimpleSAML_Session::getInstance();
//$session->doLogout($authSource);
//$as->logout(array());
$json = json_encode($attributes);
header('Content-type: application/json; charset=utf-8');
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 1 Jan 1990 00:00:00 GMT');
print isset($_GET['callback']) ? "{$_GET['callback']}({$json})" : $json;
Exemple #29
0
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */
if (isset($_GET['samlroute'])) {
    require_once __DIR__ . '/lib/_autoload.php';
    $saml = new \SimpleSAML_Auth_Simple('default-sp');
    if (!$saml->isAuthenticated()) {
        /* Show login link. */
        $saml->requireAuth();
    } else {
        $user = $saml->getAttributes();
        foreach ($user as $key => $value) {
            $user[$key] = $value[0];
        }
        $attr = json_encode($user);
        header('Location: ' . $_SERVER['SCRIPT_NAME'] . '/../../index.php/service/syntarsus/login/handler?tk=' . $_GET['tk'] . '&ref=' . $_GET['ref'] . '&route=' . $_GET['samlroute'] . '&attr=' . $attr);
    }
}
Exemple #30
0
 public function postconnectAction()
 {
     $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);
         return;
     }
     //Check if source is given
     $source = trim($this->_getParam("source"));
     if ($source == "") {
         header("Location: https://" . $_SERVER["HTTP_HOST"]);
         return;
     }
     $this->session->connectdaccountsource = $source;
     $authsource = str_replace("-sp", "", strtolower(trim($source)));
     $connectedsource = str_replace("-sp", "-connect", strtolower(trim($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($connectedsource, $t->data['sources'])) {
         header("Location: " . $referer);
         return;
     }
     //SAML Authentication new user account for connection
     $as = new SimpleSAML_Auth_Simple($connectedsource);
     $attributes = $as->getAttributes();
     $uid = $attributes['idp:uid'][0];
     if (trim($uid) == "") {
         $this->session->userError = array("title" => "New Account Connection", "message" => "Could not connect with new user account. Not enough information returned from account provider.");
         $this->_helper->redirector('postconnected');
         return;
     }
     //Check if user is already connected to the requested account
     //If true redirect the user to the previous location (referer)
     $uaccount = AccountConnect::isConnectedTo($this->session, $uid, $authsource);
     if ($uaccount !== false) {
         $this->_helper->redirector('postconnected');
         return;
     } else {
         //Check if this account is already connected to another profile
         $user = SamlAuth::getUserByAccountValues($uid, $authsource);
         if ($user !== null && $user->id != $this->session->userid) {
             $this->session->userError = array("title" => "Could not connect to " . str_replace("-", " ", $authsource) . " account", "message" => "The " . str_replace("-", " ", $authsource) . " account you tried to connect your profile to is already connected to another user profile.");
             $this->_helper->redirector('postconnected');
             return;
         }
     }
     //Build account name for user account
     $userFirstName = isset($attributes["idp:givenName"]) === true && count($attributes["idp:givenName"]) > 0 ? $attributes["idp:givenName"][0] : "";
     $userLastName = isset($attributes["idp:sn"]) === true && count($attributes["idp:givenName"]) > 0 ? $attributes["idp:sn"][0] : "";
     $userFullName = trim($userFirstName . " " . $userLastName);
     $idptrace = isset($attributes["idp:traceidp"]) === true && count($attributes["idp:traceidp"]) > 0 ? $attributes["idp:traceidp"] : array();
     if ($userFullName === "") {
         $userFullName = null;
     }
     //Do the account connection
     AccountConnect::connectAccountToProfile($this->session->userid, $uid, $authsource, $userFullName, $idptrace);
     //Update connected user accounts
     $this->session->currentUserAccounts = SamlAuth::getUserAccountsByUser($this->session->userid, true);
     //redirect to post connected action to logout connected account
     $this->_helper->redirector('postconnected');
 }