Exemplo n.º 1
0
 /**
  * Execute the rolesQuery against the dsJndiName to obtain the roles for the authenticated user.
  *
  * @param \AppserverIo\Lang\String                  $username   The username to load the roles for
  * @param \AppserverIo\Lang\String                  $lookupName The lookup name for the datasource
  * @param \AppserverIo\Lang\String                  $rolesQuery The query to load the roles
  * @param \AppserverIo\Psr\Spi\LoginModuleInterface $aslm       The login module to add the roles to
  *
  * @return array An array of groups containing the sets of roles
  * @throws \AppserverIo\Appserver\ServletEngine\Security\Logi\LoginException Is thrown if an error during login occured
  */
 public static function getRoleSets(string $username, string $lookupName, string $rolesQuery, LoginModuleInterface $aslm)
 {
     try {
         // initialize the map for the groups
         $setsMap = new HashMap();
         // load the application context
         $application = RequestHandler::getApplicationContext();
         /** @var \AppserverIo\Appserver\Core\Api\Node\DatabaseNode $databaseNode */
         $databaseNode = $application->getNamingDirectory()->search($lookupName)->getDatabase();
         // prepare the connection parameters and create the DBAL connection
         $connection = DriverManager::getConnection(ConnectionUtil::get($application)->fromDatabaseNode($databaseNode));
         // try to load the principal's roles from the database
         $statement = $connection->prepare($rolesQuery);
         $statement->bindParam(1, $username);
         $statement->execute();
         // query whether or not we've a password found or not
         $row = $statement->fetch(\PDO::FETCH_NUM);
         // query whether or not we've found at least one role
         if ($row == false) {
             // try load the unauthenticated identity
             if ($aslm->getUnauthenticatedIdentity() == null) {
                 throw new FailedLoginException('No matching username found in Roles');
             }
             // we're running with an unauthenticatedIdentity so create an empty roles set and return
             return array(new SimpleGroup(Util::DEFAULT_GROUP_NAME));
         }
         do {
             // load the found name and initialize the group name with a default value
             $name = $row[0];
             $groupName = Util::DEFAULT_GROUP_NAME;
             // query whether or not we've to initialize a default group
             if (isset($row[1])) {
                 $groupName = $row[1];
             }
             // query whether or not the group already exists in the set
             if ($setsMap->exists($groupName) === false) {
                 $group = new SimpleGroup(new String($groupName));
                 $setsMap->add($groupName, $group);
             } else {
                 $group = $setsMap->get($groupName);
             }
             try {
                 // add the user to the group
                 $group->addMember($aslm->createIdentity(new String($name)));
                 // log a message
                 $application->getNamingDirectory()->search(NamingDirectoryKeys::SYSTEM_LOGGER)->debug(sprintf('Assign user to role: %s', $name));
             } catch (\Exception $e) {
                 $application->getNamingDirectory()->search(NamingDirectoryKeys::SYSTEM_LOGGER)->error(sprintf('Failed to create principal: %s', $name));
             }
             // load one group after another
         } while ($row = $statement->fetch(\PDO::FETCH_OBJ));
     } catch (NamingException $ne) {
         throw new LoginException($ne->__toString());
     } catch (\PDOException $pdoe) {
         throw new LoginException($pdoe->__toString());
     }
     // close the prepared statement
     if ($statement != null) {
         try {
             $statement->closeCursor();
         } catch (\Exception $e) {
             $application->getNamingDirectory()->search(NamingDirectoryKeys::SYSTEM_LOGGER)->error($e->__toString());
         }
     }
     // close the DBAL connection
     if ($connection != null) {
         try {
             $connection->close();
         } catch (\Exception $e) {
             $application->getNamingDirectory()->search(NamingDirectoryKeys::SYSTEM_LOGGER)->error($e->__toString());
         }
     }
     // return the prepared groups
     return $setsMap->toArray();
 }
 /**
  * Creates a new entity manager instance based on the passed configuration.
  *
  * @param \AppserverIo\Psr\Application\ApplicationInterface                 $application         The application instance to create the entity manager for
  * @param \AppserverIo\Appserver\Core\Api\Node\PersistenceUnitNodeInterface $persistenceUnitNode The datasource configuration
  *
  * @return object The entity manager instance
  */
 public static function factory(ApplicationInterface $application, PersistenceUnitNodeInterface $persistenceUnitNode)
 {
     // register additional annotation libraries
     foreach ($persistenceUnitNode->getAnnotationRegistries() as $annotationRegistry) {
         AnnotationRegistry::registerAutoloadNamespace($annotationRegistry->getNamespace(), $annotationRegistry->getDirectoriesAsArray($application->getWebappPath()));
     }
     // globally ignore configured annotations to ignore
     foreach ($persistenceUnitNode->getIgnoredAnnotations() as $ignoredAnnotation) {
         AnnotationReader::addGlobalIgnoredName($ignoredAnnotation->getNodeValue()->__toString());
     }
     // load the metadata configuration
     $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration();
     // prepare the setup properties
     $absolutePaths = $metadataConfiguration->getDirectoriesAsArray($application->getWebappPath());
     $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_PROXY_DIR);
     $isDevMode = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_IS_DEV_MODE);
     $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_USE_SIMPLE_ANNOTATION_READER);
     // load the factory method from the available mappings
     $factoryMethod = EntityManagerFactory::$metadataMapping[$metadataConfiguration->getType()];
     // create the database configuration and initialize the entity manager
     $configuration = Setup::$factoryMethod($absolutePaths, $isDevMode, $proxyDir, null, $useSimpleAnnotationReader);
     // load the datasource node
     $datasourceNode = null;
     foreach ($application->getInitialContext()->getSystemConfiguration()->getDatasources() as $datasourceNode) {
         if ($datasourceNode->getName() === $persistenceUnitNode->getDatasource()->getName()) {
             break;
         }
     }
     // throw a exception if the configured datasource is NOT available
     if ($datasourceNode == null) {
         throw new \Exception(sprintf('Can\'t find a datasource node for persistence unit %s', $persistenceUnitNode->getName()));
     }
     // load the database node
     $databaseNode = $datasourceNode->getDatabase();
     // throw an exception if the configured database is NOT available
     if ($databaseNode == null) {
         throw new \Exception(sprintf('Can\'t find database node for persistence unit %s', $persistenceUnitNode->getName()));
     }
     // load the driver node
     $driverNode = $databaseNode->getDriver();
     // throw an exception if the configured driver is NOT available
     if ($driverNode == null) {
         throw new \Exception(sprintf('Can\'t find driver node for persistence unit %s', $persistenceUnitNode->getName()));
     }
     // initialize and return a entity manager decorator instance
     return new DoctrineEntityManagerDecorator(EntityManager::create(ConnectionUtil::get($application)->fromDatabaseNode($databaseNode), $configuration));
 }
 /**
  * Returns the password for the user from the sharedMap data.
  *
  * @return \AppserverIo\Lang\String The user's password
  * @throws \AppserverIo\Psr\Security\Auth\Login\LoginException Is thrown if password can't be loaded
  */
 protected function getUsersPassword()
 {
     // load the application context
     $application = RequestHandler::getApplicationContext();
     /** @var \AppserverIo\Appserver\Core\Api\Node\DatabaseNode $databaseNode */
     $databaseNode = $application->getNamingDirectory()->search($this->lookupName)->getDatabase();
     // prepare the connection parameters and create the DBAL connection
     $connection = DriverManager::getConnection(ConnectionUtil::get($application)->fromDatabaseNode($databaseNode));
     // try to load the principal's credential from the database
     $statement = $connection->prepare($this->principalsQuery);
     $statement->bindParam(1, $this->getUsername());
     $statement->execute();
     // close the PDO connection
     if ($connection != null) {
         try {
             $connection->close();
         } catch (\Exception $e) {
             $application->getNamingDirectory()->search(NamingDirectoryKeys::SYSTEM_LOGGER)->error($e->__toString());
         }
     }
     // query whether or not we've a password found or not
     if ($row = $statement->fetch(\PDO::FETCH_NUM)) {
         return new String($row[0]);
     } else {
         throw new LoginException('No matching username found in principals');
     }
 }
 /**
  * Creates a new entity manager instance based on the passed configuration.
  *
  * @param \AppserverIo\Psr\Application\ApplicationInterface                 $application         The application instance to create the entity manager for
  * @param \AppserverIo\Appserver\Core\Api\Node\PersistenceUnitNodeInterface $persistenceUnitNode The datasource configuration
  *
  * @return object The entity manager instance
  */
 public static function factory(ApplicationInterface $application, PersistenceUnitNodeInterface $persistenceUnitNode)
 {
     // register additional annotation libraries
     foreach ($persistenceUnitNode->getAnnotationRegistries() as $annotationRegistry) {
         // register the annotations specified by the annotation registery
         $annotationRegistryType = $annotationRegistry->getType();
         $registry = new $annotationRegistryType();
         $registry->register($annotationRegistry);
     }
     // query whether or not an initialize EM configuration is available
     if ($application->hasAttribute($persistenceUnitNode->getName()) === false) {
         // globally ignore configured annotations to ignore
         foreach ($persistenceUnitNode->getIgnoredAnnotations() as $ignoredAnnotation) {
             AnnotationReader::addGlobalIgnoredName($ignoredAnnotation->getNodeValue()->__toString());
         }
         // load the metadata configuration
         $metadataConfiguration = $persistenceUnitNode->getMetadataConfiguration();
         // prepare the setup properties
         $absolutePaths = $metadataConfiguration->getDirectoriesAsArray();
         $proxyDir = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_PROXY_DIR);
         $proxyNamespace = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_PROXY_NAMESPACE);
         $autoGenerateProxyClasses = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_AUTO_GENERATE_PROXY_CLASSES);
         $useSimpleAnnotationReader = $metadataConfiguration->getParam(MetadataConfigurationNode::PARAM_USE_SIMPLE_ANNOTATION_READER);
         // load the metadata driver factory class name
         $metadataDriverFactory = $metadataConfiguration->getFactory();
         // initialize the params to be passed to the factory
         $metadataDriverParams = array(DriverKeys::USE_SIMPLE_ANNOTATION_READER => $useSimpleAnnotationReader);
         // create the database configuration and initialize the entity manager
         /** @var \Doctrine\DBAL\Configuration $configuration */
         $configuration = new Configuration();
         $configuration->setMetadataDriverImpl($metadataDriverFactory::get($configuration, $absolutePaths, $metadataDriverParams));
         // initialize the metadata cache configuration
         $metadataCacheConfiguration = $persistenceUnitNode->getMetadataCacheConfiguration();
         $configuration->setMetadataCacheImpl(EntityManagerFactory::getCacheImpl($persistenceUnitNode, $metadataCacheConfiguration));
         // initialize the query cache configuration
         $queryCacheConfiguration = $persistenceUnitNode->getQueryCacheConfiguration();
         $configuration->setQueryCacheImpl(EntityManagerFactory::getCacheImpl($persistenceUnitNode, $queryCacheConfiguration));
         // initialize the result cache configuration
         $resultCacheConfiguration = $persistenceUnitNode->getResultCacheConfiguration();
         $configuration->setResultCacheImpl(EntityManagerFactory::getCacheImpl($persistenceUnitNode, $resultCacheConfiguration));
         // proxy configuration
         $configuration->setProxyDir($proxyDir = $proxyDir ?: sys_get_temp_dir());
         $configuration->setProxyNamespace($proxyNamespace = $proxyNamespace ?: 'Doctrine\\Proxy');
         $configuration->setAutoGenerateProxyClasses($autoGenerateProxyClasses = $autoGenerateProxyClasses ?: true);
         // load the datasource node
         $datasourceNode = null;
         foreach ($application->getInitialContext()->getSystemConfiguration()->getDatasources() as $datasourceNode) {
             if ($datasourceNode->getName() === $persistenceUnitNode->getDatasource()->getName()) {
                 break;
             }
         }
         // throw a exception if the configured datasource is NOT available
         if ($datasourceNode == null) {
             throw new \Exception(sprintf('Can\'t find a datasource node for persistence unit %s', $persistenceUnitNode->getName()));
         }
         // load the database node
         $databaseNode = $datasourceNode->getDatabase();
         // throw an exception if the configured database is NOT available
         if ($databaseNode == null) {
             throw new \Exception(sprintf('Can\'t find database node for persistence unit %s', $persistenceUnitNode->getName()));
         }
         // load the driver node
         $driverNode = $databaseNode->getDriver();
         // throw an exception if the configured driver is NOT available
         if ($driverNode == null) {
             throw new \Exception(sprintf('Can\'t find driver node for persistence unit %s', $persistenceUnitNode->getName()));
         }
         // load the connection parameters
         $connectionParameters = ConnectionUtil::get($application)->fromDatabaseNode($databaseNode);
         // append the initialized EM configuration to the application
         $application->setAttribute($persistenceUnitNode->getName(), array($connectionParameters, $configuration));
     }
     // load the initialized EM configuration from the application
     list($connectionParameters, $configuration) = $application->getAttribute($persistenceUnitNode->getName());
     // initialize and return a entity manager decorator instance
     return new DoctrineEntityManagerDecorator(EntityManager::create($connectionParameters, $configuration));
 }