我正在尝试在创建用户时使用Sonata Admin对plainPassword
字段进行编码。我使用的不是issue中的FOSUserBundle
。这是我的UserAdmin
课:
<?php
// src/Admin/UserAdmin.php
namespace App\Admin;
use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Sonata\AdminBundle\Form\Type\ModelType;
use App\Entity\Image;
class UserAdmin extends AbstractAdmin
{
protected function configureFormFields(FormMapper $formMapper) {
$formMapper
->add('username', TextType::class)
->add('email', EmailType::class)
->add('plainPassword', TextType::class)
->add('avatar', ModelType::class, [
'class' => Image::class,
'property' => 'image',
])
;
}
protected function configureDatagridFilters(DatagridMapper $datagridMapper) {
$datagridMapper->add('username')
->add('avatar', null, [], EntityType::class, [
'class' => Image::class,
'choice_label' => 'image',
])
;
}
protected function configureListFields(ListMapper $listMapper) {
$listMapper
->addIdentifier('username')
;
}
我的services.yaml
包含以下内容:
admin.user:
class: App\Admin\UserAdmin
arguments: [~, App\Entity\User, ~]
tags:
- { name: sonata.admin, manager_type: orm, label: User }
public: true
我不知道是否必须像这种example和preUpdate
方法那样重写prePersist
方法。
我的security.yaml
像这样开始:
security:
encoders:
App\Entity\User:
algorithm: bcrypt
# https://symfony.com/doc/current/book/security.html#where-do-users-come-from-user-providers
providers:
#in_memory: { memory: ~ }
my_db_provider:
entity:
class: App\Entity\User
答案 0 :(得分:1)
我找到了一个解决方案:用prePersist
方法编写一些代码。我的configureFormFields
方法有所更改,但没有任何后果:
protected function configureFormFields(FormMapper $formMapper) {
$formMapper
->add('username', TextType::class)
->add('email', EmailType::class)
->add('plainPassword', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Password confirmation')
))
->add('avatar', ModelType::class, [
'class' => Image::class,
'property' => 'image',
])
;
}
最后是我的prePersist
方法:
public function prePersist($object) { // $object is an instance of App\Entity\User as specified in services.yaml
$plainPassword = $object->getPlainPassword();
$container = $this->getConfigurationPool()->getContainer();
$encoder = $container->get('security.password_encoder');
$encoded = $encoder->encodePassword($object, $plainPassword);
$object->setPassword($encoded);
}
答案 1 :(得分:0)
通常,密码编码是在提交(和验证)表格后立即进行的。也许您必须在用户控制器类的new和update方法中为加密本身重复两行代码,但这应该是全部。