Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\LocaleConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\MoneyConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\NumberConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\PasswordConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\PercentConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\SlugConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\TelephoneConfigurator;
Expand Down Expand Up @@ -418,6 +419,7 @@
->arg(1, service('property_accessor'))

->set(NumberConfigurator::class)
->set(PasswordConfigurator::class)
->arg(0, service(IntlFormatter::class))

->set(PercentConfigurator::class)
Expand Down
1 change: 1 addition & 0 deletions doc/fields.rst
Original file line number Diff line number Diff line change
Expand Up @@ -711,6 +711,7 @@ These are all the built-in fields provided by EasyAdmin:
* :doc:`LocaleField </fields/LocaleField>`
* :doc:`MoneyField </fields/MoneyField>`
* :doc:`NumberField </fields/NumberField>`
* :doc:`PasswordField </fields/PasswordField>`
* :doc:`PercentField </fields/PercentField>`
* :doc:`SlugField </fields/SlugField>`
* :doc:`TelephoneField </fields/TelephoneField>`
Expand Down
62 changes: 62 additions & 0 deletions doc/fields/PasswordField.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
PasswordField
=============

This field is used to represent a user password in forms. On index and detail
pages, the password value is hidden and displayed as a sequence of bullets for
security purposes.

Basic Information
-----------------

* **PHP Class**: ``EasyCorp\Bundle\EasyAdminBundle\Field\PasswordField``
* **Doctrine DBAL Type**: ``string``
* **Symfony Form Type**: ``Symfony\Component\Form\Extension\Core\Type\PasswordType``
* **Rendered as**: ``<input type="password">``

Usage
-----

Basic usage::

use EasyCorp\Bundle\EasyAdminBundle\Field\PasswordField;

public function configureFields(string $pageName): iterable
{
return [
// ...
PasswordField::new('password', 'User password'),
];
}

Password Hashing
----------------

In most modern applications, plain text passwords should never be stored in the database.
You can use the ``hashPassword()`` method to define a callable that processes the plain
password submitted in the form before it is saved into the entity::

use EasyCorp\Bundle\EasyAdminBundle\Field\PasswordField;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class UserCrudController extends AbstractCrudController
{
public function __construct(
private UserPasswordHasherInterface $userPasswordHasher
) {}

public function configureFields(string $pageName): iterable
{
$hashPassword = function ($plainPassword) {
// you can get the user entity from the current context or create a dummy one
// based on your Symfony configuration
return $this->userPasswordHasher->hashPassword($this->getUser(), $plainPassword);
};

return [
PasswordField::new('password')
->hashPassword($hashPassword),
];
}
}

Alternatively, you could use Doctrine Entity Listeners to hash the password right before the entity is strictly persisted. Either way works natively with this field.
50 changes: 50 additions & 0 deletions src/Field/Configurator/PasswordConfigurator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Field\Configurator;

use EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext;
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldConfiguratorInterface;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto;
use EasyCorp\Bundle\EasyAdminBundle\Field\PasswordField;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;

final class PasswordConfigurator implements FieldConfiguratorInterface
{
public function supports(FieldDto $field, EntityDto $entityDto): bool
{
return PasswordField::class === $field->getFieldFqcn();
}

public function configure(FieldDto $field, EntityDto $entityDto, AdminContext $context): void
{
$hashPasswordCallable = $field->getCustomOption(PasswordField::OPTION_HASH_PASSWORD);

if (null !== $hashPasswordCallable) {
$field->setFormTypeOption('mapped', false);

$builderDecorator = function (FormBuilderInterface $formBuilder) use ($hashPasswordCallable, $field) {
$formBuilder->addEventListener(FormEvents::POST_SUBMIT, function (FormEvent $event) use ($hashPasswordCallable, $field) {
$plainPassword = $event->getData();

if (null !== $plainPassword && '' !== $plainPassword) {
$hashedPassword = $hashPasswordCallable($plainPassword);

$entity = $event->getForm()->getParent()->getData();
$propertyName = $field->getProperty();

$propertyAccessor = \Symfony\Component\PropertyAccess\PropertyAccess::createPropertyAccessorBuilder()
->enableExceptionOnInvalidIndex()
->getPropertyAccessor();

$propertyAccessor->setValue($entity, $propertyName, $hashedPassword);
}
});
};

$field->setFormTypeOption('builder_callable', $builderDecorator);
}
}
}
31 changes: 31 additions & 0 deletions src/Field/PasswordField.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Field;

use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Contracts\Translation\TranslatableInterface;

final class PasswordField implements FieldInterface
{
use FieldTrait;

public const OPTION_HASH_PASSWORD = 'hashPassword';

public static function new(string $propertyName, TranslatableInterface|string|bool|null $label = null): self
{
return (new self())
->setProperty($propertyName)
->setLabel($label)
->setTemplateName('crud/field/password')
->setFormType(PasswordType::class)
->addCssClass('field-password');
}

public function hashPassword(callable $passwordHasher): self
{
$this->setCustomOption(self::OPTION_HASH_PASSWORD, $passwordHasher);

return $this;
}
}
8 changes: 8 additions & 0 deletions templates/crud/field/password.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{# @var ea \EasyCorp\Bundle\EasyAdminBundle\Context\AdminContext #}
{# @var field \EasyCorp\Bundle\EasyAdminBundle\Dto\FieldDto #}
{# @var entity \EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto #}
{% if field.value is null %}
<span class="badge badge-secondary">{{ 'label.empty'|trans(domain: 'EasyAdminBundle') }}</span>
{% else %}
<span title="{{ 'label.password'|trans(domain: 'EasyAdminBundle') }}">••••••</span>
{% endif %}
56 changes: 56 additions & 0 deletions tests/Unit/Field/PasswordFieldTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php

namespace EasyCorp\Bundle\EasyAdminBundle\Tests\Unit\Field;

use EasyCorp\Bundle\EasyAdminBundle\Field\Configurator\PasswordConfigurator;
use EasyCorp\Bundle\EasyAdminBundle\Field\PasswordField;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;

class PasswordFieldTest extends AbstractFieldTest
{
protected function setUp(): void
{
parent::setUp();
$this->configurator = new PasswordConfigurator();
}

public function testDefaultOptions(): void
{
$field = PasswordField::new('foo');
$fieldDto = $this->configure($field);

self::assertSame(PasswordType::class, $fieldDto->getFormType());
self::assertStringContainsString('field-password', $fieldDto->getCssClass());
self::assertSame('crud/field/password', $fieldDto->getTemplateName());
self::assertNull($fieldDto->getCustomOption(PasswordField::OPTION_HASH_PASSWORD));
}

public function testFieldWithNullValue(): void
{
$field = PasswordField::new('foo');
$field->setValue(null);
$fieldDto = $this->configure($field);

self::assertNull($fieldDto->getValue());
}

public function testFieldWithStringValue(): void
{
$field = PasswordField::new('foo');
$field->setValue('my_secret_password');
$fieldDto = $this->configure($field);

self::assertSame('my_secret_password', $fieldDto->getValue());
}

public function testHashPasswordOption(): void
{
$hashFunction = static fn (string $password) => md5($password);
$field = PasswordField::new('foo')->hashPassword($hashFunction);
$fieldDto = $this->configure($field);

self::assertSame($hashFunction, $fieldDto->getCustomOption(PasswordField::OPTION_HASH_PASSWORD));
self::assertFalse($fieldDto->getFormTypeOption('mapped'));
self::assertNotNull($fieldDto->getFormTypeOption('builder_callable'));
}
}
Loading