简体   繁体   中英

How to set MySQL session variable upon Symfony2 login

I need to do some comprehensive auditing on a MySQL database that will be accessed using a Symfony2 app.

As far as I'm aware, standard practice is to insert into the audit table the value returned by the built-in MySQL function USER() to log who is making the changes to the records. Since all changes to the database will be performed through the Symfony2 frontend with the database connection parameters specified in the parameters.ini file, USER() will always return the same value. To get around this, I am using a MySQL session variable, @sf_user. I can get the username from the Symfony session object and use it to set the value of @sf_user in my controllers eg

$em = $this->getDoctrine()->getEntityManager();
// set @sf_user session variable in the database
// so trigger can insert this in audit table after delete
$conn = $em->getConnection();
$username = $this->get('security.context')->getToken()->getUser()->getUsername();
$sql = 'SET @sf_user = \''.$username.'\'';
$stmt = $conn->prepare($sql);
$stmt->execute();

This is fine, but as I am auditing all my tables and can't predict which action the user will perform first, I would need to repeat this code in every controller to ensure @sf_user is set at the start of the session.

What I would really like to do is to set this variable when the user logs in. I have set up my login page as described in The Book . The problem is, my SecurityController only handles displaying the login form, while "the security system itself takes care of checking the submitted username and password and authenticating the user".

So, my question is, where can I insert the above code so that it is always executed at the start of the session, after the user has successfully logged in?

Many Thanks.

You can create a kernel.request event listener and execute your query there. Besides that you can take a look at EntityAudit bundle which inserts current author name automatically. It has some limitations though.

Thanks for all suggestions, I have just gone back to setting the variable @sf_user in each deleteAction controller. It's not pretty , but it works.

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