编码密码easyadmin v3



我有我的用户,我可以从管理面板管理,我可以更改密码,但问题是在数据库中它没有加密。它在数据库里很清楚,保存你我怎么能做到的,这样它就不再是了?我给你我的用户实体和crud用户,我使用easyadmin v3和symfony 5捆绑包。

我的实体用户

<?php
namespace AppEntity;
use AppRepositoryUserRepository;
use DoctrineCommonCollectionsArrayCollection;
use DoctrineCommonCollectionsCollection;
use DoctrineORMMapping as ORM;
use SymfonyComponentSecurityCoreUserUserInterface;

/**
* @ORMEntity(repositoryClass=UserRepository::class)
*/
class User implements UserInterface
{
/**
* @ORMId
* @ORMGeneratedValue
* @ORMColumn(type="integer")
*/
private $id;
/**
* @ORMColumn(type="string", length=180, unique=true)
*/
private $email;
/**
* @ORMColumn(type="json")
*/
private $roles = [];
/**
* @var string The hashed password
* @ORMColumn(type="string")
*/
private $password;
/**
* @ORMColumn(type="string", length=255)
*/
private $prenom;
/**
* @ORMColumn(type="string", length=255)
*/
private $nom;
/**
* @ORMColumn(type="string", length=255)
*/
private $telephone;
/**
* @ORMColumn(type="text", nullable=true)
*/
private $aPropos;
/**
* @ORMColumn(type="string", length=255, nullable=true)
*/
private $facebook;
/**
* @ORMOneToMany(targetEntity=Realisation::class, mappedBy="user", orphanRemoval=true)
*/
private $realisations;
public function __construct()
{
$this->realisations = new ArrayCollection();
}
public function getId(): ?int
{
return $this->id;
}
public function getEmail(): ?string
{
return $this->email;
}
public function setEmail(string $email): self
{
$this->email = $email;
return $this;
}
/**
* A visual identifier that represents this user.
*
* @see UserInterface
*/
public function getUsername(): string
{
return (string) $this->email;
}
/**
* @see UserInterface
*/
public function getRoles(): array
{
$roles = $this->roles;
// guarantee every user at least has ROLE_USER
$roles[] = 'ROLE_USER';
return array_unique($roles);
}
public function setRoles(array $roles): self
{
$this->roles = $roles;
return $this;
}
/**
* @see UserInterface
*/
public function getPassword(): string
{
return (string) $this->password;
}
public function setPassword(string $password): self
{
$this->password = $password;
return $this;
}
/**
* Returning a salt is only needed, if you are not using a modern
* hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
*
* @see UserInterface
*/
public function getSalt(): ?string
{
return null;
}
/**
* @see UserInterface
*/
public function eraseCredentials()
{
// If you store any temporary, sensitive data on the user, clear it here
// $this->plainPassword = null;
}
public function getPrenom(): ?string
{
return $this->prenom;
}
public function setPrenom(string $prenom): self
{
$this->prenom = $prenom;
return $this;
}
public function getNom(): ?string
{
return $this->nom;
}
public function setNom(string $nom): self
{
$this->nom = $nom;
return $this;
}
public function getTelephone(): ?string
{
return $this->telephone;
}
public function setTelephone(string $telephone): self
{
$this->telephone = $telephone;
return $this;
}
public function getAPropos(): ?string
{
return $this->aPropos;
}
public function setAPropos(?string $aPropos): self
{
$this->aPropos = $aPropos;
return $this;
}
public function getFacebook(): ?string
{
return $this->facebook;
}
public function setFacebook(?string $facebook): self
{
$this->facebook = $facebook;
return $this;
}
/**
* @return Collection|Realisation[]
*/
public function getRealisations(): Collection
{
return $this->realisations;
}
public function addRealisation(Realisation $realisation): self
{
if (!$this->realisations->contains($realisation)) {
$this->realisations[] = $realisation;
$realisation->setUser($this);
}
return $this;
}
public function removeRealisation(Realisation $realisation): self
{
if ($this->realisations->removeElement($realisation)) {
// set the owning side to null (unless already changed)
if ($realisation->getUser() === $this) {
$realisation->setUser(null);
}
}
return $this;
}
public function __toString()
{
return $this->nom;
}
/* public function __toString(){
return $this->nom;
}*/
}

<?php
namespace AppControllerAdmin;
use AppEntityUser;
use EasyCorpBundleEasyAdminBundleControllerAbstractCrudController;
use EasyCorpBundleEasyAdminBundleFieldIntegerField;
use EasyCorpBundleEasyAdminBundleFieldTextField;
class UserCrudController extends AbstractCrudController
{
public static function getEntityFqcn(): string
{
return User::class;
}

public function configureFields(string $pageName): iterable
{
return [
IntegerField::new('id','ID')->onlyOnIndex(),
TextField::new('email'),
TextField::new('password'),
TextField::new('nom'),
TextField::new('telephone'),
TextField::new('aPropos'),
TextField::new('facebook'),
];
}

}

这可能会有所帮助。。。

<?php
namespace AppEventSubscriber;
use AppEntityBackendUser;
use SymfonyComponentDependencyInjectionContainerInterface;
use SymfonyComponentEventDispatcherEventSubscriberInterface;
use SymfonyComponentSecurityCoreEncoderUserPasswordEncoderInterface;
use EasyCorpBundleEasyAdminBundleEventBeforeEntityUpdatedEvent;
class EasyAdminHooksSubscriber implements EventSubscriberInterface {
/**
* @var UserPasswordEncoderInterface
*/
private $passwordEncoder;
/**
* @var ContainerInterface
*/
private $container;
/**
* EasyAdminSubscriber constructor.
*
* @param UserPasswordEncoderInterface $passwordEncoder
* @param ContainerInterface $container
*/
public function __construct(UserPasswordEncoderInterface $passwordEncoder, ContainerInterface $container) {
$this->passwordEncoder = $passwordEncoder;
$this->container = $container;
}
public static function getSubscribedEvents(): array {
return array(
BeforeEntityUpdatedEvent::class => array('preUpdateEntity')
);
}
/**
* @param BeforeEntityUpdatedEvent $event
*
* @noinspection PhpUnused
*/
public function preUpdateEntity(BeforeEntityUpdatedEvent $event) {
$entity = $event->getEntityInstance();
if($entity instanceof BackendUser) {
$this->preUpdateBackendUser($entity);
}
}
/**
* @param BackendUser $be_user
*/
private function preUpdateBackendUser(BackendUser &$be_user) {
$plain_password = $be_user->getPlainPassword();
if(!empty($plain_password)) {
$new_password = $this->passwordEncoder->encodePassword($be_user, $plain_password);
$be_user->setPassword($new_password);
$be_user->setPlainPassword();
}
}
}

这是我在尝试从web应用程序的管理面板(Symfony 5.3和EasyAdmin v3(创建/编辑用户时发现的一个解决方案。我在Github上的EasyAdmin问题跟踪器中找到了它。

您需要向User类添加一个普通的密码字段,并设置适当的getter&setter方法。

/**
* @var string
*/
private $plainPassword;
/**
* @return string
*/
public function getPlainPassword(): string
{
return $this->plainPassword;
}

添加事件侦听器以侦听创建/编辑表单提交事件,从提交的表单数据中提取纯密码,然后对其进行哈希。

/** @var UserPasswordHasherInterface */
private $hasher;
public function createEditFormBuilder(EntityDto $entityDto, KeyValueStore $keyValueStore, AdminContext $context): FormBuilderInterface
{
$formBuilder = parent::createEditFormBuilder($entityDto, $keyValueStore, $context);
$this->addEncodePasswordEventListener($formBuilder);
return $formBuilder;
}
public function createNewFormBuilder(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormBuilderInterface
{
$formBuilder = parent::createNewFormBuilder($entityDto, $formOptions, $context);
$this->addEncodePasswordEventListener($formBuilder);
return $formBuilder;
}
/**
* @param FormBuilderInterface $formBuilder
*/
public function addEncodePasswordEventListener(FormBuilderInterface $formBuilder)
{
$formBuilder->addEventListener(FormEvents::SUBMIT, function (FormEvent $event){
/** @var User $user */
$user = $event->getData();
if ($user->getPlainPassword()) {
$user->setPassword($this->hasher->hashPassword($user, $user->getPlainPassword()));
}
});
}

最后,您需要呈现适当的表单字段。

public function configureFields(string $pageName): iterable
{
return [
# other fields
Field::new('plainPassword', 'New Password')->onlyOnForms()
->setFormType(RepeatedType::class)
->setFormTypeOptions([
'type' => PasswordType::class,
'first_options' => ['label' => 'New password'],
'second_options' => ['label' => 'Repeat Password']
])->setRequired(true)
];
}

希望有人觉得这个有用。

您可以在用户实体:中添加纯密码字段

private ?string $plainPassword= '';
public function getPlainPassword(): ?string
{
return $this->plainPassword;
}
public function setPlainPassword(?string $plainPassword): void
{
$this->plainPassword = $plainPassword;
}

在用户回购中添加密码更新程序:

public function setNewPassword(PasswordAuthenticatedUserInterface $user, string $plainPassword): void
{
$hashedPassword = $this->hasher->hashPassword($user, $plainPassword);
$user->setPassword($hashedPassword);
$this->_em->persist($user);
$this->_em->flush();
}

并覆盖UserCrudController:中的更新/持久化方法

public function updateEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$this->updatePassword($entityInstance);
parent::updateEntity($entityManager, $entityInstance);
}
public function persistEntity(EntityManagerInterface $entityManager, $entityInstance): void
{
$this->updatePassword($entityInstance);
parent::persistEntity($entityManager, $entityInstance);
}
private function updatePassword(User $user): void
{
if ($user->getPlainPassword() == '') return;
$this->userRepository->setNewPassword($user, $user->getPlainPassword());
}

它在Symfony 5.4.2/EasyAdmin 3.5.19 中的工作

最新更新