简体   繁体   中英

Symfony dynamic database credentials

Is it possible to make a input to set database user/password in Symfony at start-up of the application (like phpMyAdmin)?

I want that my application do like this:

  • Welcome page (only html, no database connection with just input for db username/password (like phpMyAdmin))
  • User set username/password on inputs and click ok button => the values can be set into Request/post or Session in the controller by example
  • Symfony connect database to all application and redirect user to 'app_index' route

Is it possible to do it with Symfony 5?

Here my controller action:

public function database_login(Request $request, Connection $connection): Response
  {
    if ($request->isMethod('POST') && $request->request->has('dbpass')) {
      $dbpass = $request->request->get('dbpass');
      $params = $connection->getParams();
      $params['password'] = $dbpass;

      $connection->__construct($params, $connection->getDriver(), $connection->getConfiguration(), $connection->getEventManager());
      $connection->connect();
      return $this->redirectToRoute('app_index');
    }
    return new Response(
      '<form method="post">
        <input type="password" name="dbpass">
        <button type="submit">OK</button>
      </form>'
    );
  }

The new connection work's fine but it lost after redirecToRoute() function.

Can you help me?

@barbuslex, you can save variables to the session.

$request->getSession()->set('db_login', 'login');
$request->getSession()->set('db_password', 'password');

Also, to avoid passing these parameters manually every request, you could use EventListener, for example: https://symfony.com/doc/current/event_dispatcher.html#request-events-checking-types

However, maybe you need another event, that is triggered earlier. Or play around with "priority" of listener.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM