I have a simple login form:
public function loginAction(Request $request)
{
$authenticationUtils = $this->get('security.authentication_utils');
// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();
// last username entered by the user
$lastUsername = $authenticationUtils->getLastUsername();
return $this->render(
'users/login.html.twig',
[
'page' => 'login',
'last_username' => $lastUsername,
'error' => $error,
]
);
}
security.yml:
secured_area:
form_login:
provider: user_db_provider
login_path: /login
check_path: /login
csrf_token_generator: security.csrf.token_manager
And I'm trying to set the user's last login time.
Do I really have to create a new listener and write an entire class, like this answer, just for this single instruction: $user->setLastLogin(new \DateTime());
? Or is there something simpler, like putting it in the controller?
Yes, you must create a login success listener, as described in this answer, and use the onAuthenticationSuccess
method to store your user information.
The code you posted is for generating the login page itself. Any login action is handled by the firewall, which calls either a success or failure listener. You can execute your code (for example setting the last successful login timestsamp) in your custom listener.
The reason for that is that it is better to create classes that perform a single task, rather than putting a lot of code together in one class. This maintains your modularity, extensibility and maintanability of your code.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments