function addArpConfiguration(SimpleSAML_XHTML_Template $et, ConfigProxy $janus_config) { $arp_attributes = array(); $old_arp_attributes = $janus_config->getValue('attributes'); foreach ($old_arp_attributes as $label => $arp_attribute) { if (is_array($arp_attribute)) { $arp_attributes[$label] = $arp_attribute; } else { $arp_attributes[$arp_attribute] = array('name' => $arp_attribute); } } $et->data['arp_attributes_configuration'] = $arp_attributes; }
public function push($remoteId) { $remotes = $this->config->getArray('push.remote'); if (!isset($remotes[$remoteId])) { throw new \InvalidArgumentException("Remote 'remote' does not exist"); } $remoteUrl = $remotes[$remoteId]['url']; $connections = $this->connectionService->findAll(); $serializer = SerializerBuilder::create()->build(); $serializedConnections = $serializer->serialize($connections, 'json'); $client = new Client(); $request = $client->createRequest('POST', $remoteUrl, array('Content-Type' => 'application/json', 'User-Agent' => 'JANUS Guzzle HTTP Client (see: https://github.com/janus-ssp/janus)'), $serializedConnections, $this->config->getArray('push.requestOptions')); return $request->send()->__toString(); }
public function buildForm(FormBuilderInterface $builder, array $options) { $attributesConfig = $this->janusConfiguration->getArray('attributes'); /** * Symfony doesn't allow form names with a . in them, so we transform the names of the fields on the model * but we also have to transform the submitted data to _. */ $builder->addModelTransformer(new DotToUnderscoreTransformer()); $builder->addViewTransformer(new DotToUnderscoreTransformer(true)); $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { $submittedData = $event->getData(); if (empty($submittedData)) { return; } $newData = array(); foreach ($submittedData as $attributeName => $attributeValues) { $newData[str_replace('.', '_', $attributeName)] = $attributeValues; } $event->setData($newData); }); /** * ARP Attribute semantics do not match that of a form... * If an attribute is present it MUST have values, unfortunately Symfony adds them as empty arrays by default. * So we strip out the empty values after Symfony is done adding them. Yay Symfony Forms. */ $builder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event) { $cleanedData = array(); $data = $event->getData(); foreach ($data as $arpAttributeName => $arpAttributeValues) { // Skip attributes with no values. if (empty($arpAttributeValues)) { continue; } $cleanedData[$arpAttributeName] = $arpAttributeValues; } $event->setData($cleanedData); }); /** * Add the actual attributes as collections. */ foreach ($attributesConfig as $attributeConfig) { if (isset($attributeConfig['specify_values']) && $attributeConfig['specify_values']) { $builder->add(str_replace('.', '_', $attributeConfig['name']), 'collection', array('type' => 'text', 'options' => array('data' => '*'), 'allow_add' => true, 'allow_delete' => true)); } else { $builder->add(str_replace('.', '_', $attributeConfig['name']), 'collection', array('type' => 'text', 'options' => array('data' => '*'), 'constraints' => array(new Count(array('min' => 0, 'max' => 1))), 'allow_add' => true, 'allow_delete' => true)); } } }
public function getPrettyname() { if (isset($this->_prettyname)) { return $this->_prettyname; } /** @var string $fieldName */ $fieldName = $this->_config->getString('entity.prettyname', NULL); $mb = new sspmod_janus_MetadataFieldBuilder($this->_config->getArray('metadatafields.' . $this->_type)); $metadataFields = $mb->getMetadataFields(); if (!is_null($fieldName)) { $rows = $this->loadPrettyNameFromCache($fieldName); if (empty($rows)) { $this->_prettyname = $this->_entityid; } else { if (isset($metadataFields[$fieldName]->default) && $metadataFields[$fieldName]->default == $rows[0]['value']) { $this->_prettyname = $this->_entityid; } else { $this->_prettyname = $rows[0]['value']; } } } else { $this->_prettyname = $this->_entityid; } return $this->_prettyname; }
/** * Collect the id of the configured attributes we allow in an ARP. * * @return array<string> * @throws Exception */ private function getAllowedArpAttributes() { $configured_attributes = $this->_config->getValue('attributes'); $arp_attributes = array(); foreach ($configured_attributes as $label => $config) { $arp_attributes[] = $config['name']; } return $arp_attributes; }
function getUser(SimpleSAML_Session $session, ConfigProxy $janus_config) { // Get data from config /** @var string $useridattr */ $useridattr = $janus_config->getValue('useridattr', 'eduPersonPrincipalName'); // Validate user $attributes = $session->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; }
/** * Retrieve all entities from database * * The method retrieves all entities from the database together with the * newest revision id. * * @param array|string $state States requesting * @param array|string $type Types requesting * * @return bool|array All entities from the database */ public function getEntitiesByStateType($state = null, $type = null, $active = 'yes') { $state = (array) $state; $type = (array) $type; $whereClauses = array('`active` = ?'); $queryData = array($active); if (!empty($state)) { $placeHolders = array_fill(0, count($state), '?'); $whereClauses[] = 'CONNECTION_REVISION.state IN (' . implode(',', $placeHolders) . ')'; $queryData = array_merge($queryData, $state); } if (!empty($type)) { $placeHolders = array_fill(0, count($type), '?'); $whereClauses[] = 'CONNECTION_REVISION.type IN (' . implode(',', $placeHolders) . ')'; $queryData = array_merge($queryData, $type); } // Select entity (only last revision) $selectFields = array('DISTINCT CONNECTION_REVISION.eid', 'CONNECTION_REVISION.revisionid', 'CONNECTION_REVISION.created', 'CONNECTION_REVISION.state', 'CONNECTION_REVISION.type'); $fromTable = $this->getTablePrefix() . "connection AS CONNECTION"; $joins = array("\n INNER JOIN " . $this->getTablePrefix() . "connectionRevision AS CONNECTION_REVISION\n ON CONNECTION_REVISION.eid = CONNECTION.id\n AND CONNECTION_REVISION.revisionid = CONNECTION.revisionNr\n "); $orderFields = array('created ASC'); // Find default value for sort field so it can be excluded /** @var $sortFieldName string */ $sortFieldName = $this->_config->getString('entity.prettyname', NULL); // Try to sort results by pretty name from metadata if ($sortFieldName) { $fieldDefaultValue = ''; if ($sortFieldDefaultValue = $this->_config->getArray('metadatafields.saml20-idp', FALSE)) { if (isset($sortFieldDefaultValue[$sortFieldName])) { $fieldDefaultValue = $sortFieldDefaultValue[$sortFieldName]['default']; } } else { if ($sortFieldDefaultValue = $this->_config->getArray('metadatafields.saml20-sp', FALSE)) { if (isset($sortFieldDefaultValue[$sortFieldName])) { $fieldDefaultValue = $sortFieldDefaultValue[$sortFieldName]['default']; } } } $joins[] = "\n LEFT JOIN " . $this->getTablePrefix() . "metadata AS METADATA\n ON METADATA.key = ?\n AND METADATA.connectionRevisionId = CONNECTION_REVISION.id\n AND METADATA.value != ?"; array_unshift($queryData, $fieldDefaultValue); array_unshift($queryData, $sortFieldName); $selectFields[] = 'IFNULL(METADATA.`value`, CONNECTION_REVISION.`entityid`) AS `orderfield`'; $orderFields = array("orderfield ASC"); } $query = 'SELECT ' . implode(', ', $selectFields); $query .= "\nFROM " . $fromTable; $query .= implode("\n", $joins); $query .= "\nWHERE " . implode(' AND ', $whereClauses); $query .= "\nORDER BY " . implode(', ', $orderFields); $st = self::execute($query, $queryData); if ($st === false) { SimpleSAML_Logger::error('JANUS: Error fetching all entities'); return false; } $rs = $st->fetchAll(PDO::FETCH_ASSOC); return $rs; }
public function authenticate(TokenInterface $token) { /** @var string $authenticationType */ $authenticationType = $this->config->getValue('auth', 'login-admin'); if (php_sapi_name() === 'cli') { return $this->getTokenForUsername($authenticationType); } $session = \SimpleSAML_Session::getInstance(); if (!$session->isValid($authenticationType)) { throw new AuthenticationException("Authsource '{$authenticationType}' is invalid"); } /** @var string $userIdAttributeName */ $userIdAttributeName = $this->config->getValue('useridattr', 'eduPersonPrincipalName'); // Check if userid exists $attributes = $session->getAttributes(); if (!isset($attributes[$userIdAttributeName])) { throw new AuthenticationException("Attribute '{$userIdAttributeName}' with User ID is missing."); } return $this->getTokenForUsername($attributes[$userIdAttributeName][0]); }
public function findDescriptorsForFilters($filter, $sortBy, $sortOrder) { /** @var $sortFieldDefaultValue string */ $sortFieldName = $this->config->getString('entity.prettyname', NULL); $revisions = $this->connectionRepository->findLatestRevisionsWithFilters($filter, $sortBy, $sortOrder, $sortFieldName); $connectionDescriptors = array(); foreach ($revisions as $revision) { $connectionDescriptors[] = $revision->toDescriptorDto(); } return new ConnectionDtoCollection($connectionDescriptors); }
/** * @return string * @throws RuntimeException */ public function getLoggedInUsername() { if (static::$allowNoAuthenticatedUser) { return null; } /** @var string $authenticationType */ $authenticationType = $this->config->getValue('auth', 'login-admin'); if (php_sapi_name() === 'cli') { return $authenticationType; } $session = SimpleSAML_Session::getInstance(); if (!$session->isValid($authenticationType)) { throw new RuntimeException("Authsource '{$authenticationType}' is invalid"); } /** @var string $userIdAttributeName */ $userIdAttributeName = $this->config->getValue('useridattr', 'eduPersonPrincipalName'); // Check if userid exists $attributes = $session->getAttributes(); if (!isset($attributes[$userIdAttributeName])) { throw new RuntimeException("Attribute '{$userIdAttributeName}' with User ID is missing."); } return $attributes[$userIdAttributeName][0]; }
/** * Add metadata. * * Add a new matadata entry to the entity. * * @param string $key The metadata key * @param string $value The metadata value * * @return sspmod_janus_Metadata The metadata. * @todo Make independent of type (make generic, support for more types than * sp and idp) */ public function addMetadata($key, $value) { if ($value === null || $value === '') { return false; } assert('is_string($key);'); assert('$this->_entity instanceof Sspmod_Janus_Entity'); $mb = new sspmod_janus_MetadataFieldBuilder($this->_config->getArray('metadatafields.' . $this->_entity->getType())); $fieldDefinitions = $mb->getMetadataFields(); // Check if metadata is allowed if (!array_key_exists($key, $fieldDefinitions)) { SimpleSAML_Logger::info(__CLASS__ . ':addMetadata - Metadata key \'' . $key . ' not allowed'); return false; } $fieldDefinition = $fieldDefinitions[$key]; if (empty($this->_metadata)) { if (!$this->loadEntity()) { return false; } } $st = $this->execute('SELECT count(*) AS count FROM ' . $this->getTablePrefix() . 'metadata WHERE `connectionRevisionId` = ? AND `key` = ?;', array($this->_entity->getId(), $key)); if ($st === false) { SimpleSAML_Logger::error(__CLASS__ . ':addMetadata - Count check failed'); return false; } $row = $st->fetchAll(PDO::FETCH_ASSOC); if ($row[0]['count'] > 0) { SimpleSAML_Logger::error(__CLASS__ . ':addMetadata - Metadata already exists'); return false; } if ($fieldDefinition->getType() === 'select') { $allowedSelectValues = $fieldDefinition->getSelectValues(); if (!in_array($value, $allowedSelectValues)) { SimpleSAML_Logger::error(__CLASS__ . ':addMetadata - Value: ' . $value . ' not allowed for field ' . $key); return false; } } $metadata = new sspmod_janus_Metadata($fieldDefinition, $key, $value); $metadata->setConnectionRevisionId($this->_entity->getId()); $this->_metadata[] = $metadata; $this->_modified = true; // The metadata is not saved, since it is not part of the current // entity with current revision id return $metadata; }
/** * @param string $connectionType * @return array * @throws \Exception */ private function getMetadataFieldsForType($connectionType) { $metadataFields = $this->janusConfig->getArray('metadatafields.' . $connectionType); // Inline 'supported' $inlineMetadataFields = array(); foreach ($metadataFields as $fieldName => $fieldConfig) { if (empty($fieldConfig['supported'])) { $inlineMetadataFields[$fieldName] = $fieldConfig; continue; } foreach ($fieldConfig['supported'] as $supportedValue) { $inlineFieldName = str_replace('#', $supportedValue, $fieldName); $inlineMetadataFields[$inlineFieldName] = $fieldConfig; } } return $inlineMetadataFields; }
/** * Get all addresses in JANUS * * @return array All addresses in JANUS */ public function getSubscriptionList() { // Predifined subscriptions $subscriptionList = array('ENTITYUPDATE', 'USER', 'USER-NEW', 'ENTITYCREATE'); // Get all existing subscriptions $st = self::execute('SELECT DISTINCT(`subscription`) AS `subscription` FROM `' . $this->getTablePrefix() . 'subscription`;'); if ($st === false) { SimpleSAML_Logger::error('JANUS: Error fetching subscriptions'); return false; } while ($row = $st->fetch(PDO::FETCH_ASSOC)) { $subscriptionList[] = $row['subscription']; } $st = null; // Get subscription to all active users $st = self::execute('SELECT `uid` FROM `' . $this->getTablePrefix() . 'user` WHERE `active` = ?;', array('yes')); if ($st === false) { SimpleSAML_Logger::error('JANUS: Error fetching subscriptions'); return false; } while ($row = $st->fetch(PDO::FETCH_ASSOC)) { $subscriptionList[] = 'USER-' . $row['uid']; } $st = null; // Get subscription to all active users $st = self::execute('SELECT `eid` FROM `' . $this->getTablePrefix() . 'connectionRevision`;'); if ($st === false) { SimpleSAML_Logger::error('JANUS: Error fetching subscriptions'); return false; } while ($row = $st->fetch(PDO::FETCH_ASSOC)) { $subscriptionList[] = 'ENTITYUPDATE-' . $row['eid']; } $workflowstates = $this->_config->getArray('workflowstates'); foreach ($workflowstates as $key => $value) { $subscriptionList[] = 'ENTITYUPDATE-#-CHANGESTATE-' . $key; } $subscriptionList[] = 'ENTITYUPDATE-#-CHANGESTATE'; // Remove dublicates $sl = array_unique($subscriptionList); asort($sl); return $sl; }
/** * Loads deployable workflow states from config * * @return array $deployableStateList */ private function _loadDeployableWorkflowStates() { static $deployableStateList = array(); if (empty($deployableStateList)) { $stateList = $this->_config->getValue('workflowstates'); foreach ($stateList as $stateName => $stateConfig) { $isDeployable = array_key_exists('isDeployable', $stateConfig) && true === $stateConfig['isDeployable']; if ($isDeployable) { $deployableStateList[] = $stateName; } } // Backwards compatibility, if no states are marked as deployable, all states are used $noStatesMarkedAsDeployable = empty($deployableStateList); if ($noStatesMarkedAsDeployable) { $deployableStateList = array_keys($stateList); } } return $deployableStateList; }
/** * @param ConfigProxy $janusConfig * @param $connectionType * @return mixed * @throws \Exception */ protected function findJanusMetadataConfig(ConfigProxy $janusConfig, $connectionType) { $configKey = "metadatafields.{$connectionType}"; if (!$janusConfig->hasValue($configKey)) { throw new \Exception("No metadatafields config found for type {$connectionType}"); } $metadataFieldsConfig = $janusConfig->getArray($configKey); return $metadataFieldsConfig; }
/** * @param ConfigProxy $configuration */ public function __construct(ConfigProxy $configuration) { $this->configuration = $configuration; $this->access = $configuration->getArray(self::CONFIG_ACCESS); }