EasyAdmin & Symfony – Encode users passwords
In our previous article, we saw how to add an export button to your backend using EasyAdmin and Symfony, we will see now how just to encode password according to Symfony security system when you want to update or create an User in your backend.
Then, we suppose here you have EasyAdmin installed & configurated.
First, we will override the main controller to use our own controller, for this, edit the config file config/routes/easy_admin.yaml
:
easy_admin_bundle:
resource: 'App\Controller\AdminController'
prefix: /admin
type: annotation
Then, let’s build our controller, we are using Events to check if we are updating Users entity :
<?php
namespace App\Controller;
use App\Service\UserSecurityService;
use App\Entity\Users;
use EasyCorp\Bundle\EasyAdminBundle\Controller\EasyAdminController;
use EasyCorp\Bundle\EasyAdminBundle\Event\EasyAdminEvents;
class AdminController extends EasyAdminController
{
/**
* @var UserSecurityService
*/
private $userSecurityService;
/**
* AdminController constructor.
* @param UserSecurityService $userSecurityService
*/
public function __construct(UserSecurityService $userSecurityService)
{
$this->userSecurityService = $userSecurityService;
}
/**
*
*
* @param $eventName
* @param array $arguments
*/
protected function dispatch($eventName, array $arguments = array())
{
$subject = isset($arguments['entity']) ? $arguments['entity'] : null;
if ($subject instanceof Users
&& in_array($eventName, [EasyAdminEvents::PRE_PERSIST, EasyAdminEvents::PRE_UPDATE])
) {
$user = $this->request->request->get('user');
$password = $user['password'];
if (! empty(trim($password))) {
$this->userSecurityService->setupUser($subject);
}
}
parent::dispatch($eventName, $arguments);
}
}
We use a small service to encode password, just to explode our code and have reutilisable scripts :
<?php
namespace App\Service;
use App\Entity\Users;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
class UserSecurityService
{
/**
* @var UserPasswordEncoderInterface
*/
private $passwordEncoder;
public function __construct(UserPasswordEncoderInterface $passwordEncoder)
{
$this->passwordEncoder = $passwordEncoder;
}
public function setupUser(Users $user): void
{
try {
$user->setSalt(bin2hex(random_bytes(12)));
} catch(\Exception $e) {
$user->setSalt(uniqid(time()));
}
$password = $this->passwordEncoder->encodePassword($user, $user->getPassword());
$user->setPassword($password);
}
}
Here we are ! Now, when you will update your users using EasyAdmin backend, the password field will be encoded before being saved in your DB.