protected function _getAccessToken($conf, $subjectId, $requireNew)
 {
     $cache = EngineBlock_ApplicationSingleton::getInstance()->getDiContainer()->getApplicationCache();
     if (!$requireNew && $cache instanceof Zend_Cache_Backend_Apc) {
         $accessToken = $cache->load(self::ACCESS_TOKEN_KEY);
         if ($accessToken) {
             return $accessToken;
         }
     }
     // for example https://api.dev.surfconext.nl/v1/oauth2/token
     $baseUrl = $this->_ensureTrailingSlash($conf->baseUrl) . 'v1/oauth2/token';
     $client = new Zend_Http_Client($baseUrl);
     try {
         $response = $client->setConfig(array('timeout' => 15))->setHeaders(Zend_Http_Client::CONTENT_TYPE, Zend_Http_Client::ENC_URLENCODED)->setAuth($conf->key, $conf->secret)->setParameterPost('grant_type', 'client_credentials')->request(Zend_Http_Client::POST);
         $result = json_decode($response->getBody(), true);
         if (isset($result['access_token'])) {
             $accessToken = $result['access_token'];
             if ($cache instanceof Zend_Cache_Backend_Apc) {
                 $cache->save($accessToken, self::ACCESS_TOKEN_KEY);
             }
             return $accessToken;
         }
         throw new EngineBlock_VirtualOrganization_AccessTokenNotGrantedException('AccessToken not granted for EB as SP. Check SR and the Group Provider endpoint log.');
     } catch (Exception $exception) {
         $additionalInfo = EngineBlock_Log_Message_AdditionalInfo::create()->setUserId($subjectId)->setDetails($exception->getTraceAsString());
         EngineBlock_ApplicationSingleton::getLog()->error("Error in connecting to API(s) for access token grant" . $exception->getMessage(), array('additional_info' => $additionalInfo->toArray()));
         throw new EngineBlock_VirtualOrganization_AccessTokenNotGrantedException('AccessToken not granted for EB as SP. Check SR and the Group Provider endpoint log', EngineBlock_Exception::CODE_ALERT, $exception);
     }
 }
 /**
  * @return array|Zend_Rest_Client_Result
  */
 public function get($args = array())
 {
     if (!isset($args[0])) {
         $args[0] = $this->_uri->getPath();
     }
     $this->_data['rest'] = 1;
     $data = array_slice($args, 1) + $this->_data;
     $response = $this->restGet($args[0], $data);
     /**
      * @var Zend_Http_Client $httpClient
      */
     $httpClient = $this->getHttpClient();
     EngineBlock_ApplicationSingleton::getLog()->debug("REST Request: " . $httpClient->getLastRequest());
     EngineBlock_ApplicationSingleton::getLog()->debug("REST Response: " . $httpClient->getLastResponse()->getBody());
     $this->_data = array();
     //Initializes for next Rest method.
     if ($response->getStatus() !== 200) {
         throw new EngineBlock_Exception("Response status !== 200: " . var_export($httpClient->getLastRequest(), true) . var_export($response, true) . var_export($response->getBody(), true));
     }
     if (strpos($response->getHeader("Content-Type"), "application/json") !== false) {
         return json_decode($response->getBody(), true);
     } else {
         try {
             return new Zend_Rest_Client_Result($response->getBody());
         } catch (Zend_Rest_Client_Result_Exception $e) {
             throw new EngineBlock_Exception('Error parsing response' . var_export($httpClient->getLastRequest(), true) . var_export($response, true) . var_export($response->getBody(), true), null, $e);
         }
     }
 }
 /**
  * Send a mail based on the configuration in the emails table
  *
  * @throws EngineBlock_Exception in case there is no EmailConfiguration in emails table
  * @param $emailAddress the email address of the recipient
  * @param $emailType the pointer to the emails configuration
  * @param $replacements array where the key is a variable (e.g. {user}) and the value the string where the variable should be replaced
  * @return void
  */
 public function sendMail($emailAddress, $emailType, $replacements)
 {
     $dbh = $this->_getDatabaseConnection();
     $query = "SELECT email_text, email_from, email_subject, is_html FROM emails where email_type = ?";
     $parameters = array($emailType);
     $statement = $dbh->prepare($query);
     $statement->execute($parameters);
     $rows = $statement->fetchAll();
     if (count($rows) !== 1) {
         EngineBlock_ApplicationSingleton::getLog()->err("Unable to send mail because of missing email configuration: " . $emailType);
         return;
     }
     $emailText = $rows[0]['email_text'];
     foreach ($replacements as $key => $value) {
         // Single value replacement
         if (!is_array($value)) {
             $emailText = str_ireplace($key, $value, $emailText);
         } else {
             $replacement = '<ul>';
             foreach ($value as $valElem) {
                 $replacement .= '<li>' . $valElem . '</li>';
             }
             $replacement .= '</ul>';
             $emailText = str_ireplace($key, $replacement, $emailText);
         }
     }
     $emailFrom = $rows[0]['email_from'];
     $emailSubject = $rows[0]['email_subject'];
     $mail = new Zend_Mail('UTF-8');
     $mail->setBodyHtml($emailText, 'utf-8', 'utf-8');
     $mail->setFrom($emailFrom, "SURFconext Support");
     $mail->addTo($emailAddress);
     $mail->setSubject($emailSubject);
     $mail->send();
 }
 /**
  * Validate the license information
  *
  * @param string $userId
  * @param array $spMetadata
  * @param array $idpMetadata
  * @return string
  */
 public function validate($userId, array $spMetadata, array $idpMetadata)
 {
     if (!$this->_active) {
         return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN;
     }
     $client = new Zend_Http_Client($this->_url);
     $client->setConfig(array('timeout' => 15));
     try {
         $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json; charset=utf-8')->setParameterGet('userId', urlencode($userId))->setParameterGet('serviceProviderEntityId', urlencode($spMetadata['EntityId']))->setParameterGet('identityProviderEntityId', urlencode($idpMetadata['EntityId']))->request('GET');
         $body = $client->getLastResponse()->getBody();
         $response = json_decode($body, true);
         $status = $response['status'];
     } catch (Exception $exception) {
         $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($userId, $idpMetadata['EntityId'], $spMetadata['EntityId'], $exception->getTraceAsString());
         EngineBlock_ApplicationSingleton::getLog()->error("Could not connect to License Manager" . $exception->getMessage(), $additionalInfo);
         return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN;
     }
     if ($status['returnUrl']) {
         $currentResponse = EngineBlock_ApplicationSingleton::getInstance()->getHttpResponse();
         $currentResponse->setRedirectUrl($status['returnUrl']);
         $currentResponse->send();
         exit;
     } else {
         if ($status['licenseStatus']) {
             return $status['licenseStatus'];
         } else {
             return EngineBlock_LicenseEngine_ValidationManager::LICENSE_UNKNOWN;
         }
     }
 }
 public function metadataAction()
 {
     $this->setNoRender();
     $request = EngineBlock_ApplicationSingleton::getInstance()->getHttpRequest();
     $entityId = $request->getQueryParameter("entityid");
     $gadgetUrl = $request->getQueryParameter('gadgeturl');
     // If we were only handed a gadget url, no entity id, lookup the Service Provider entity id
     if ($gadgetUrl && !$entityId) {
         $identifiers = $this->_getRegistry()->findIdentifiersByMetadata('coin:gadgetbaseurl', $gadgetUrl);
         if (count($identifiers) > 1) {
             EngineBlock_ApplicationSingleton::getLog()->warn("Multiple identifiers found for gadgetbaseurl: '{$gadgetUrl}'");
             throw new EngineBlock_Exception('Multiple identifiers found for gadgetbaseurl');
         }
         if (count($identifiers) === 0) {
             EngineBlock_ApplicationSingleton::getInstance()->getLog()->warn("No Entity Id found for gadgetbaseurl '{$gadgetUrl}'");
             $this->_getResponse()->setHeader('Content-Type', 'application/json');
             $this->_getResponse()->setBody(json_encode(new stdClass()));
             return;
         }
         $entityId = $identifiers[0];
     }
     if (!$entityId) {
         throw new EngineBlock_Exception('No entity id provided to get metadata for?!');
     }
     if (isset($_REQUEST["keys"])) {
         $result = $this->_getRegistry()->getMetaDataForKeys($entityId, explode(",", $_REQUEST["keys"]));
     } else {
         $result = $this->_getRegistry()->getMetadata($entityId);
     }
     $result['entityId'] = $entityId;
     $this->_getResponse()->setHeader('Content-Type', 'application/json');
     $this->_getResponse()->setBody(json_encode($result));
 }
 public function saml2AttributesToLdapAttributes($attributes)
 {
     $log = EngineBlock_ApplicationSingleton::getLog();
     $required = $this->_saml2Required;
     $ldapAttributes = array();
     foreach ($attributes as $saml2Name => $values) {
         // Map it to an LDAP attribute
         if (isset($this->_s2lMap[$saml2Name])) {
             if (count($values) > 1) {
                 $log->notice("Ignoring everything but first value of {$saml2Name}", array('attribute_values' => $values));
             }
             $ldapAttributes[$this->_s2lMap[$saml2Name]] = $values[0];
         }
         // Check off against required attribute list
         $requiredAttributeKey = array_search($saml2Name, $required);
         if ($requiredAttributeKey !== false) {
             unset($required[$requiredAttributeKey]);
         }
     }
     if (!empty($required)) {
         $log->error('Missing required SAML2 fields in attributes', array('required_fields' => $required, 'attributes' => $attributes));
         throw new EngineBlock_Exception_MissingRequiredFields('Missing required SAML2 fields in attributes');
     }
     return $ldapAttributes;
 }
 /**
  *
  * @example /profile/group-oauth/consume/provider2?oauth_token=request-token
  *
  * @param string $providerId
  * @return void
  */
 public function consumeAction($providerId)
 {
     $this->setNoRender();
     $providerConfig = $this->_getProviderConfiguration($providerId);
     $consumer = new Zend_Oauth_Consumer($providerConfig->auth);
     $queryParameters = $this->_getRequest()->getQueryParameters();
     if (empty($queryParameters)) {
         throw new EngineBlock_Exception('Unable to consume access token, no query parameters given');
     }
     if (!isset($_SESSION['request_token'][$providerId])) {
         throw new EngineBlock_Exception("Unable to consume access token, no request token (session lost?)");
     }
     $requestToken = unserialize($_SESSION['request_token'][$providerId]);
     $token = $consumer->getAccessToken($queryParameters, $requestToken);
     $userId = $this->attributes['nameid'][0];
     $provider = EngineBlock_Group_Provider_OpenSocial_Oauth_ThreeLegged::createFromConfigs($providerConfig, $userId);
     $provider->setAccessToken($token);
     if (!$provider->validatePreconditions()) {
         EngineBlock_ApplicationSingleton::getLog()->err("Unable to test OpenSocial 3-legged Oauth provider because not all preconditions have been matched?", new EngineBlock_Log_Message_AdditionalInfo($userId, null, null, null));
         $this->providerId = $providerId;
         $this->renderAction("Error");
     } else {
         // Now that we have an Access Token, we can discard the Request Token
         $_SESSION['request_token'][$providerId] = null;
         $this->_redirectToUrl($_SESSION['return_url']);
     }
 }
 /**
  * Add the 'urn:collab:org:surf.nl' value to the isMemberOf attribute in case a user
  * is considered a 'full member' of the SURFfederation.
  *
  * @return array Response Attributes
  */
 protected function _addIsMemberOfSurfNlAttribute()
 {
     if ($this->_identityProvider->guestQualifier === IdentityProvider::GUEST_QUALIFIER_ALL) {
         // All users from this IdP are guests, so no need to add the isMemberOf
         return;
     }
     if ($this->_identityProvider->guestQualifier === IdentityProvider::GUEST_QUALIFIER_NONE) {
         $this->_setIsMember();
         return;
     }
     $log = EngineBlock_ApplicationSingleton::getLog();
     if ($this->_identityProvider->guestQualifier === IdentityProvider::GUEST_QUALIFIER_SOME) {
         if (isset($this->_responseAttributes[static::URN_SURF_PERSON_AFFILIATION][0])) {
             if ($this->_responseAttributes[static::URN_SURF_PERSON_AFFILIATION][0] === 'member') {
                 $this->_setIsMember();
             } else {
                 $log->notice("Idp guestQualifier is set to 'Some', surfPersonAffiliation attribute does not contain " . 'the value "member", so not adding isMemberOf for surf.nl');
             }
         } else {
             $log->warning("Idp guestQualifier is set to 'Some' however, " . "the surfPersonAffiliation attribute was not provided, " . "not adding the isMemberOf for surf.nl", array('idp' => $this->_identityProvider, 'response_attributes' => $this->_responseAttributes));
         }
         return;
     }
     // Unknown policy for handling guests? Treat the user as a guest, but issue a warning in the logs
     $log->warning("Idp guestQualifier is set to unknown value '{$this->_identityProvider['GuestQualifier']}", array('idp' => $this->_identityProvider, 'response_attributes' => $this->_responseAttributes));
 }
 public function execute()
 {
     $spEntityId = $this->_spMetadata['EntityId'];
     $serviceRegistryAdapter = $this->_getServiceRegistryAdapter();
     $arp = $serviceRegistryAdapter->getArp($spEntityId);
     if ($arp) {
         EngineBlock_ApplicationSingleton::getLog()->info("Applying attribute release policy {$arp['name']} for {$spEntityId}");
         $newAttributes = array();
         foreach ($this->_responseAttributes as $attribute => $attributeValues) {
             if (!isset($arp['attributes'][$attribute])) {
                 EngineBlock_ApplicationSingleton::getLog()->info("ARP: Removing attribute {$attribute}");
                 continue;
             }
             $allowedValues = $arp['attributes'][$attribute];
             if (in_array('*', $allowedValues)) {
                 // Passthrough all values
                 $newAttributes[$attribute] = $attributeValues;
                 continue;
             }
             foreach ($attributeValues as $attributeValue) {
                 if (in_array($attributeValue, $allowedValues)) {
                     if (!isset($newAttributes[$attribute])) {
                         $newAttributes[$attribute] = array();
                     }
                     $newAttributes[$attribute][] = $attributeValue;
                 }
             }
         }
         $this->_responseAttributes = $newAttributes;
     }
 }
 public function dispatch($uri = "")
 {
     try {
         $application = EngineBlock_ApplicationSingleton::getInstance();
         if (!$uri) {
             $uri = $application->getHttpRequest()->getUri();
         }
         if (!$this->_dispatch($uri)) {
             EngineBlock_ApplicationSingleton::getLog()->notice("[404]Unroutable URI: '{$uri}'");
             $this->_getControllerInstance('default', 'error')->handleAction('NotFound');
         }
     } catch (Exception $e) {
         $this->_handleDispatchException($e);
     }
 }
 public function execute()
 {
     if (!isset($this->_responseAttributes[self::URN_IS_MEMBER_OF])) {
         return;
     }
     $groups =& $this->_responseAttributes[self::URN_IS_MEMBER_OF];
     for ($i = 0; $i < count($groups); $i++) {
         $hasVoPrefix = strpos($groups[$i], self::URN_COLLAB_ORG_PREFIX) === 0;
         if (!$hasVoPrefix) {
             continue;
         }
         unset($groups[$i]);
         EngineBlock_ApplicationSingleton::getLog()->notice(sprintf('FilterReservedMemberOfValue: Removed "%s" value from %s attribute by %s', $groups[$i], self::URN_IS_MEMBER_OF, $this->_identityProvider->entityId));
     }
 }
 /**
  * 
  *
  * @param  $userId
  * @param  $attributes
  * @param  $spMetadata
  * @param  $idpMetadata
  * @return void
  */
 public function provisionUser($userId, $attributes, $spMetadata, $idpMetadata)
 {
     if (!$spMetadata['MustProvisionExternally']) {
         return;
     }
     // https://os.XXX.surfconext.nl/provisioning-manager/provisioning/jit.shtml?
     // provisionDomain=apps.surfnet.nl&provisionAdmin=admin%40apps.surfnet.nl&
     // provisionPassword=xxxxx&provisionType=GOOGLE&provisionGroups=true
     $client = new Zend_Http_Client($this->_url);
     $client->setHeaders(Zend_Http_Client::CONTENT_TYPE, 'application/json; charset=utf-8')->setParameterGet('provisionType', $spMetadata['ExternalProvisionType'])->setParameterGet('provisionDomain', $spMetadata['ExternalProvisionDomain'])->setParameterGet('provisionAdmin', $spMetadata['ExternalProvisionAdmin'])->setParameterGet('provisionPassword', $spMetadata['ExternalProvisionPassword'])->setParameterGet('provisionGroups', $spMetadata['ExternalProvisionGroups'])->setRawData(json_encode($this->_getData($userId, $attributes)))->request('POST');
     $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($userId, $idpMetadata['EntityId'], $spMetadata['EntityId'], null);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: Sent HTTP request to provision user using " . __CLASS__, $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: URI: " . $client->getUri(true), $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: REQUEST: " . $client->getLastRequest(), $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug("PROVISIONING: RESPONSE: " . $client->getLastResponse(), $additionalInfo);
 }
 public function indexAction()
 {
     $this->metadata = new EngineBlock_AttributeMetadata();
     $this->aggregator = EngineBlock_Group_Provider_Aggregator_MemoryCacheProxy::createFromDatabaseFor($this->attributes['nameid'][0]);
     $this->groupOauth = $this->user->getUserOauth();
     $serviceRegistryClient = new Janus_Client_CacheProxy();
     $this->spList = $serviceRegistryClient->getSpList();
     $this->consent = $this->user->getConsent();
     $this->spAttributesList = $this->_getSpAttributeList($this->spList);
     try {
         $this->spOauthList = $this->_getSpOauthList($this->spList);
     } catch (Exception $e) {
         $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($this->user->getUid(), null, null, $e->getTraceAsString());
         EngineBlock_ApplicationSingleton::getLog()->critical($e->getMessage(), $additionalInfo);
     }
 }
 protected function _isMemberOfGroups(EngineBlock_VirtualOrganization $virtualOrganization, $subjectId)
 {
     $groupProvider = $this->_getGroupProvider($subjectId);
     try {
         $groups = $virtualOrganization->getGroups();
         foreach ($groups as $group) {
             if ($groupProvider->isMember($group->id)) {
                 return true;
             }
         }
     } catch (EngineBlock_VirtualOrganization_VoIdentifierNotFoundException $e) {
         $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($subjectId, null, null, $virtualOrganization);
         EngineBlock_ApplicationSingleton::getLog()->warn($e->getMessage(), $additionalInfo);
     }
     return false;
 }
Esempio n. 15
0
 /**
  * Ask PDP for access.
  *
  * @return \Pdp_PolicyResponse
  * @throws \EngineBlock_Exception
  */
 protected function requestAccess()
 {
     $httpClient = new Zend_Http_Client($this->baseUrl);
     try {
         $result = $httpClient->setConfig(array('timeout' => 15))->setAuth($this->username, $this->password, Zend_Http_Client::AUTH_BASIC)->setRawData($this->policyRequest->toJson())->setEncType('application/json')->request('POST');
         if ($result->getStatus() != '200') {
             $error = "Received invalid HTTP " . $result->getStatus() . "response from PDP";
             EngineBlock_ApplicationSingleton::getLog()->error($error);
             throw new EngineBlock_Exception($error);
         }
     } catch (Zend_Http_Client_Exception $e) {
         EngineBlock_ApplicationSingleton::getLog()->error($e->getMessage());
         throw new EngineBlock_Exception($e->getMessage());
     }
     $this->policyResponse = new Pdp_PolicyResponse($result->getBody());
     return $this->policyResponse;
 }
 protected function _doManipulation($manipulationCode, $entityId, &$subjectId, array &$attributes, array &$response, EngineBlock_Saml2_ResponseAnnotationDecorator $responseObj, array $idpMetadata, array $spMetadata)
 {
     $entityType = $this->_entityType;
     EngineBlock_ApplicationSingleton::getInstance()->getErrorHandler()->withExitHandler(function () use($manipulationCode, $entityId, &$subjectId, &$attributes, &$response, $responseObj, $idpMetadata, $spMetadata) {
         eval($manipulationCode);
     }, function (EngineBlock_Exception $exception) use($entityType, $manipulationCode, $entityId, $subjectId, $attributes, $response, $responseObj, $idpMetadata, $spMetadata) {
         EngineBlock_ApplicationSingleton::getLog()->error('An error occurred while running service registry manipulation code', array('manipulation_code' => array('EntityID' => $entityId, 'Manipulation code' => $manipulationCode, 'Subject NameID' => $subjectId, 'Attributes' => $attributes, 'Response' => $response, 'IdPMetadata' => $idpMetadata, 'SPMetadata' => $spMetadata)));
         if ($entityType === 'sp') {
             $exception->spEntityId = $entityId;
         } else {
             if ($entityType === 'idp') {
                 $exception->idpEntityId = $entityId;
             }
         }
         $exception->userId = $subjectId;
         $exception->description = $entityType;
     });
 }
 public function execute()
 {
     if (!$this->_collabPersonId) {
         throw new EngineBlock_Corto_Filter_Command_Exception_PreconditionFailed('Missing collabPersonId');
     }
     // In filter stage we need to take a look at the VO context
     $vo = $this->_request->getVoContext();
     if (!$vo) {
         return;
     }
     // If in VO context, validate the user's membership
     EngineBlock_ApplicationSingleton::getLog()->debug("VO {$vo} membership required");
     $validator = $this->_getValidator();
     $isMember = $validator->isMember($vo, $this->_collabPersonId, $this->_identityProvider->entityId);
     if (!$isMember) {
         throw new EngineBlock_Corto_Exception_UserNotMember("User not a member of VO {$vo}");
     }
     $this->_responseAttributes[self::VO_NAME_ATTRIBUTE] = array($vo);
 }
 protected function _getNameIdFormat($request, $spEntityMetadata)
 {
     // Persistent is our default
     $defaultNameIdFormat = 'urn:oasis:names:tc:SAML:2.0:nameid-format:persistent';
     // If a NameIDFormat was explicitly set in the ServiceRegistry, use that...
     if (isset($spEntityMetadata['NameIDFormat'])) {
         return $spEntityMetadata['NameIDFormat'];
     } else {
         if (isset($request['samlp:NameIDPolicy']['_Format'])) {
             $requestedNameIdFormat = $request['samlp:NameIDPolicy']['_Format'];
             if (in_array($requestedNameIdFormat, $this->SUPPORTED_NAMEID_FORMATS)) {
                 return $request['samlp:NameIDPolicy']['_Format'];
             } else {
                 EngineBlock_ApplicationSingleton::getLog()->warn("Whoa, SP '{$spEntityMetadata['EntityID']}' requested '{$requestedNameIdFormat}' " . "however we don't support that format, opting to try '{$defaultNameIdFormat}' " . "instead of sending an error. SP might not be happy with that...");
                 return $defaultNameIdFormat;
             }
         }
     }
     return $defaultNameIdFormat;
 }
 public function execute()
 {
     $logger = EngineBlock_ApplicationSingleton::getLog();
     $enforcer = new EngineBlock_Arp_AttributeReleasePolicyEnforcer();
     $attributes = $this->_responseAttributes;
     // Get the Requester chain, which starts at the oldest (farthest away from us SP) and ends with our next hop.
     $requesterChain = EngineBlock_SamlHelper::getSpRequesterChain($this->_serviceProvider, $this->_request, $this->_server->getRepository());
     // Note that though we should traverse in reverse ordering, it doesn't make a difference.
     // A then B filter or B then A filter are equivalent.
     foreach ($requesterChain as $spMetadata) {
         $spEntityId = $spMetadata->entityId;
         $arp = $this->getMetadataRepository()->fetchServiceProviderArp($spMetadata);
         if (!$arp) {
             continue;
         }
         $logger->info("Applying attribute release policy for {$spEntityId}");
         $attributes = $enforcer->enforceArp($arp, $attributes);
     }
     $this->_responseAttributes = $attributes;
 }
Esempio n. 20
0
 /**
  * @param string $message
  */
 protected function _logRequest($message)
 {
     /**
      * @var Zend_Http_Client $httpClient
      */
     $httpClient = $this->getHttpClient();
     $logContext = array('http_request' => $httpClient->getLastRequest());
     $response = $httpClient->getLastResponse();
     $originalBody = $response->getBody();
     $body = substr($originalBody, 0, 1024);
     if ($body !== $originalBody) {
         $body .= '...';
     }
     // If able to decode as JSON, show parsed result
     $decoded = json_decode($body);
     if ($decoded) {
         $logContext['json_response'] = $decoded;
     }
     $logContext['http_response'] = $response->getHeadersAsString() . PHP_EOL . $response->getBody();
     EngineBlock_ApplicationSingleton::getLog()->error($message, $logContext);
 }
 /**
  * Create a new Database connection, for a given mode self::MODE_READ and self::MODE_WRITE,
  * defaults to write mode.
  *
  * @static
  * @throws EngineBlock_Exception
  * @param  $mode
  * @return PDO
  */
 public function create($mode = null)
 {
     if ($mode === null) {
         $mode = self::MODE_WRITE;
     }
     $databaseSettings = $this->_getDatabaseSettings();
     if ($mode === self::MODE_READ) {
         try {
             return $this->_createReadConnection($databaseSettings);
         } catch (Exception $e) {
             $additionalInfo = EngineBlock_Log_Message_AdditionalInfo::create()->setDetails($e->getTraceAsString());
             EngineBlock_ApplicationSingleton::getLog()->error("Unable to create a Read connection, trying to create a write connection, exception: " . print_r($e, true), array('additional_info' => $additionalInfo->toArray()));
             return $this->_createWriteConnection($databaseSettings);
         }
     } else {
         if ($mode === self::MODE_WRITE) {
             return $this->_createWriteConnection($databaseSettings);
         } else {
             throw new EngineBlock_Database_Exception("Requested database connection with unknown mode '{$mode}'");
         }
     }
 }
 public function execute()
 {
     $serviceProvider = EngineBlock_SamlHelper::findRequesterServiceProvider($this->_serviceProvider, $this->_request, $this->_server->getRepository());
     if (!$serviceProvider) {
         $serviceProvider = $this->_serviceProvider;
     }
     if (!$serviceProvider->policyEnforcementDecisionRequired) {
         return;
     }
     EngineBlock_ApplicationSingleton::getLog()->debug("Policy Enforcement Point consult");
     $validator = $this->_getValidator();
     $hasAccess = $validator->hasAccess($this->_collabPersonId, $this->_identityProvider->entityId, $serviceProvider->entityId, $this->_responseAttributes);
     if ($hasAccess) {
         return;
     }
     $message = "Policy Decision Point: access denied.";
     if ($validator->getMessage()) {
         $message = $validator->getMessage();
     }
     EngineBlock_ApplicationSingleton::getLog()->debug("Policy Enforcement Point access denied: " . $message);
     throw new EngineBlock_Corto_Exception_PEPNoAccess($message);
 }
 public function enforceArp(AttributeReleasePolicy $arp = null, $responseAttributes)
 {
     if (!$arp) {
         return $responseAttributes;
     }
     $newAttributes = array();
     foreach ($responseAttributes as $attributeName => $attributeValues) {
         if (!$arp->hasAttribute($attributeName)) {
             continue;
         }
         foreach ($attributeValues as $attributeValue) {
             if (!$arp->isAllowed($attributeName, $attributeValue)) {
                 EngineBlock_ApplicationSingleton::getLog()->info("ARP: non allowed attribute value '{$attributeValue}' for attribute '{$attributeName}'");
                 continue;
             }
             if (!isset($newAttributes[$attributeName])) {
                 $newAttributes[$attributeName] = array();
             }
             $newAttributes[$attributeName][] = $attributeValue;
         }
     }
     return $newAttributes;
 }
 public function getMembersWithPrivileges($groupName)
 {
     $members = $this->getMembers($groupName);
     $membersWithPrivileges = array();
     foreach ($members as $member) {
         try {
             $member->privileges = $this->getMemberPrivileges($member->id, $groupName);
             $membersWithPrivileges[] = $member;
         } catch (Exception $e) {
             $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo($member->id, null, null, $e->getTraceAsString());
             EngineBlock_ApplicationSingleton::getLog()->warn("Something wrong with user: " . var_export($member, true) . 'Received Exception: ' . var_export($e, true), $additionalInfo);
         }
     }
     return $membersWithPrivileges;
 }
 protected function _setFileLocation()
 {
     $location = $this->_getFileLocationFromConfiguration();
     if (substr($location, 0, 1) !== '/') {
         $realLocation = realpath(ENGINEBLOCK_FOLDER_ROOT . $location);
         if ($realLocation === FALSE) {
             EngineBlock_ApplicationSingleton::getLog()->warn("Location '{$location}' does not exist, " . "relative from the EngineBlock root: " . ENGINEBLOCK_FOLDER_ROOT);
             return false;
         }
         $location = $realLocation;
     }
     $this->_fileLocation = $location;
     return $this;
 }
 private function getNameEn(IdentityProvider $identityProvider, EngineBlock_Log_Message_AdditionalInfo $additionalInfo)
 {
     if ($identityProvider->displayNameEn) {
         return $identityProvider->displayNameEn;
     }
     if ($identityProvider->nameEn) {
         return $identityProvider->nameEn;
     }
     EngineBlock_ApplicationSingleton::getLog()->warning('No EN displayName and name found for idp: ' . $identityProvider->entityId, array('additional_info' => $additionalInfo->toArray()));
     return $identityProvider->entityId;
 }
 protected static function _logErrorMessage($providerId, Exception $e)
 {
     $additionalInfo = new EngineBlock_Log_Message_AdditionalInfo(null, null, null, $e->getTraceAsString());
     EngineBlock_ApplicationSingleton::getLog()->err("Unable to use provider {$providerId}, received Exception: " . $e->getMessage(), $additionalInfo);
     EngineBlock_ApplicationSingleton::getLog()->debug($e->getTraceAsString());
 }
 /**
  * The dummy logger ignores any call to warn()
  * @param EngineBlock_Log_Message_AdditionalInfo $additionalInfo Some extra information
  * that can be supplied with the log message
  * @param String $message
  */
 public function warn($message, EngineBlock_Log_Message_AdditionalInfo $additionalInfo = null)
 {
     EngineBlock_ApplicationSingleton::getLog()->warn($this->_getPrefix() . $message, $additionalInfo);
 }
 /**
  * Add the 'urn:collab:org:surf.nl' value to the isMemberOf attribute in case a user
  * is considered a 'full member' of the SURFfederation.
  *
  * @return array Response Attributes
  */
 protected function _addIsMemberOfSurfNlAttribute()
 {
     if (!isset($this->_idpMetadata['GuestQualifier'])) {
         EngineBlock_ApplicationSingleton::getLog()->warn('No GuestQualifier for IdP: ' . var_export($this->_idpMetadata, true) . 'Setting it to "All" and continuing.');
         $this->_idpMetadata['GuestQualifier'] = 'All';
     }
     if ($this->_idpMetadata['GuestQualifier'] === 'None') {
         $this->_setIsMember();
     } else {
         if ($this->_idpMetadata['GuestQualifier'] === 'Some') {
             if (isset($this->_responseAttributes[static::URN_SURF_PERSON_AFFILIATION][0])) {
                 if ($this->_responseAttributes[static::URN_SURF_PERSON_AFFILIATION][0] === 'member') {
                     $this->_setIsMember();
                 } else {
                     EngineBlock_ApplicationSingleton::getLog()->notice("Idp guestQualifier is set to 'Some', surfPersonAffiliation attribute does not contain " . 'the value "member", so not adding isMemberOf for surf.nl');
                 }
             } else {
                 EngineBlock_ApplicationSingleton::getLog()->warn("Idp guestQualifier is set to 'Some' however, " . "the surfPersonAffiliation attribute was not provided, " . "not adding the isMemberOf for surf.nl" . var_export($this->_idpMetadata, true) . var_export($this->_responseAttributes, true));
             }
         } else {
             if ($this->_idpMetadata['GuestQualifier'] === 'All') {
                 // All users from this IdP are guests, so no need to add the isMemberOf
             } else {
                 // Unknown policy for handling guests? Treat the user as a guest, but issue a warning in the logs
                 EngineBlock_ApplicationSingleton::getLog()->warn("Idp guestQualifier is set to unknown value '{$this->_idpMetadata['GuestQualifier']}, idp metadata: " . var_export($this->_idpMetadata, true) . var_export($this->_responseAttributes, true));
             }
         }
     }
 }
Esempio n. 30
0
 /**
  * @return Psr\Log\LoggerInterface
  */
 protected function _getSessionLog()
 {
     return EngineBlock_ApplicationSingleton::getLog();
 }