0

Using Symfony 4, we are building a multi-customer application where each customer has a dedicated database. Customer databases are created automatically on-demand when new Customer is created. During this process, we create unique extra .env file (customer specific) which holds the database connection credentials.

We have 2x database connection & 2x entity managers - common & customer. customer entity manager is the default one in fact. Obviously, customer entity manager does not have the correct connection params at first. We load the extra .env file accordingly (e.g. based on the domain) on kernel request and set the customer connection and entity manager accordingly:

$connection = $this->entityManager->getConnection();
$connection->close();

$reflectionConn   = new \ReflectionObject($connection);
$reflectionParams = $reflectionConn->getProperty('params');
$reflectionParams->setAccessible(true);

$params             = $reflectionParams->getValue($connection);
$params['dbname']   = $database; // read from the customer specific .env
$params['user']     = $username; // read from the customer specific .env
$params['password'] = $password; // read from the customer specific .env

$reflectionParams->setValue($connection, $params);
$reflectionParams->setAccessible(false);

$this->entityManager = $this->entityManager->create(
    $this->entityManager->getConnection(),
    $this->entityManager->getConfiguration()
);

This works fine!

The problem is the security context (?) - we are using FosUserBundle which is not able to authorize the users. I'm guessing the code above is not enough to affect security context.

What would be the proper way to achieve the goal of having dynamic database connection + user authorization using standard FosUserBundle?

werd
  • 648
  • 4
  • 13
  • 23

1 Answers1

0

The problem was not related to security context at all. The issue (silly) was that my kernel request listener had the default priority (0) which made the whole customer config loading and connection setting after the login listener takes place.

Setting it to 512 (should be enough) to kick-in before SessionListener

werd
  • 648
  • 4
  • 13
  • 23