This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 15k traffic Daily!!!

Symfony 6 and EasyAdmin 4: Hashing password


* The duvet picture is initially by geralt and edited with nice appreciation.




Abstract

With EasyAdmin bundle, you possibly can create admin panel simply:

Effectively, as to Person entity, given it has password subject, you could need to hash it earlier than it saved for safety.

This put up exhibits the right way to implement it with EasyAdmin.



Atmosphere



Methods to hash password



The supply code

Right here is an instance.
Modify src/Controller/Admin/UserCrudController.php like this:

<?php

namespace AppControllerAdmin;

use AppEntityUser;
use EasyCorpBundleEasyAdminBundleConfig{Motion, Actions, Crud, KeyValueStore};
use EasyCorpBundleEasyAdminBundleContextAdminContext;
use EasyCorpBundleEasyAdminBundleControllerAbstractCrudController;
use EasyCorpBundleEasyAdminBundleDtoEntityDto;
use EasyCorpBundleEasyAdminBundleField{IdField, EmailField, TextField};
use SymfonyComponentFormExtensionCoreType{PasswordType, RepeatedType};
use SymfonyComponentForm{FormBuilderInterface, FormEvent, FormEvents};
use SymfonyComponentPasswordHasherHasherUserPasswordHasherInterface;

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

    public static perform getEntityFqcn(): string
    {
        return Person::class;
    }

    public perform configureActions(Actions $actions): Actions
    {
        return $actions
            ->add(Crud::PAGE_EDIT, Motion::INDEX)
            ->add(Crud::PAGE_INDEX, Motion::DETAIL)
            ->add(Crud::PAGE_EDIT, Motion::DETAIL)
            ;
    }

    public perform configureFields(string $pageName): iterable
    {
        $fields = [
            IdField::new('id')->hideOnForm(),
            EmailField::new('email'),
        ];

        $password = TextField::new('password')
            ->setFormType(RepeatedType::class)
            ->setFormTypeOptions([
                'type' => PasswordType::class,
                'first_options' => ['label' => 'Password'],
                'second_options' => ['label' => '(Repeat)'],
                'mapped' => false,
            ])
            ->setRequired($pageName === Crud::PAGE_NEW)
            ->onlyOnForms()
            ;
        $fields[] = $password;

        return $fields;
    }

    public perform createNewFormBuilder(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormBuilderInterface
    {
        $formBuilder = father or mother::createNewFormBuilder($entityDto, $formOptions, $context);
        return $this->addPasswordEventListener($formBuilder);
    }

    public perform createEditFormBuilder(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormBuilderInterface
    {
        $formBuilder = father or mother::createEditFormBuilder($entityDto, $formOptions, $context);
        return $this->addPasswordEventListener($formBuilder);
    }

    personal perform addPasswordEventListener(FormBuilderInterface $formBuilder): FormBuilderInterface
    {
        return $formBuilder->addEventListener(FormEvents::POST_SUBMIT, $this->hashPassword());
    }

    personal perform hashPassword() {
        return perform($occasion) {
            $type = $occasion->getForm();
            if (!$type->isValid()) {
                return;
            }
            $password = $type->get('password')->getData();
            if ($password === null) {
                return;
            }

            $hash = $this->userPasswordHasher->hashPassword($this->getUser(), $password);
            $type->getData()->setPassword($hash);
        };
    }
}
Enter fullscreen mode

Exit fullscreen mode




Description

I’ll break it down into a number of components.



Constructor Property Promotion

This model is legitimate since PHP 8.0.

    public perform __construct(
        public UserPasswordHasherInterface $userPasswordHasher
    ) {}
Enter fullscreen mode

Exit fullscreen mode

When your PHP model is previous to them, write like beneath as an alternative:

    personal $userPasswordHasher;

    public perform __construct(
        UserPasswordHasherInterface $userPasswordHasher
    ) {
        $this->userPasswordHasher = $userPasswordHasher;
    }
Enter fullscreen mode

Exit fullscreen mode



Add menus

That is optionally available. Menus are added to index web page and edit.

    public perform configureActions(Actions $actions): Actions
    {
        return $actions
            ->add(Crud::PAGE_EDIT, Motion::INDEX)
            ->add(Crud::PAGE_INDEX, Motion::DETAIL)
            ->add(Crud::PAGE_EDIT, Motion::DETAIL)
            ;
    }
Enter fullscreen mode

Exit fullscreen mode



Generate password subject

configureFields is one in all EasyAdmin’s capabilities to configure the fields to display.
Right here, password subject is outlined as PasswordType and RepeatedType. Additionally, it’s as an unmapped field to stop validation exception within the case when null is ready so as to not change password.

    public perform configureFields(string $pageName): iterable
    {
        $fields = [
            IdField::new('id')->hideOnForm(),
            EmailField::new('email'),
        ];

        $password = TextField::new('password')
            ->setFormType(RepeatedType::class)
            ->setFormTypeOptions([
                'type' => PasswordType::class,
                'first_options' => ['label' => 'Password'],
                'second_options' => ['label' => '(Repeat)'],
                'mapped' => false,
            ])
            ->setRequired($pageName === Crud::PAGE_NEW)
            ->onlyOnForms()
            ;
        $fields[] = $password;

        return $fields;
    }
Enter fullscreen mode

Exit fullscreen mode



Deal with occasions

Right here, Symfony type occasions are used with EasyAdmin occasion handlers. It is as a result of as of now EasyAdmin’s events do not help dealing with type validation.

    public perform createNewFormBuilder(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormBuilderInterface
    {
        $formBuilder = father or mother::createNewFormBuilder($entityDto, $formOptions, $context);
        return $this->addPasswordEventListener($formBuilder);
    }

    public perform createEditFormBuilder(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormBuilderInterface
    {
        $formBuilder = father or mother::createEditFormBuilder($entityDto, $formOptions, $context);
        return $this->addPasswordEventListener($formBuilder);
    }

    personal perform addPasswordEventListener(FormBuilderInterface $formBuilder): FormBuilderInterface
    {
        return $formBuilder->addEventListener(FormEvents::POST_SUBMIT, $this->hashPassword());
    }
Enter fullscreen mode

Exit fullscreen mode



Hash password

That is the important thing half on hashing password with Symfony’s PasswordHasher.
When password isn’t entered, skip the sector.
When it’s, hash it✨ and add the sector to the entity information🌟

    personal perform hashPassword() {
        return perform($occasion) {
            $type = $occasion->getForm();
            if (!$type->isValid()) {
                return;
            }
            $password = $type->get('password')->getData();
            if ($password === null) {
                return;
            }

            $hash = $this->userPasswordHasher->hashPassword($this->getUser(), $password);
            $type->getData()->setPassword($hash);
        };
    }
Enter fullscreen mode

Exit fullscreen mode


That is it.
I am blissful if the code and outline on this put up would make it easier to 🙂

The Article was Inspired from tech community site.
Contact us if this is inspired from your article and we will give you credit for it for serving the community.

This Banner is For Sale !!
Get your ad here for a week in 20$ only and get upto 10k Tech related traffic daily !!!

Leave a Reply

Your email address will not be published. Required fields are marked *

Want to Contribute to us or want to have 15k+ Audience read your Article ? Or Just want to make a strong Backlink?