Symfony2 $user->setPassword() 将密码更新为纯文本 [DataFixtures + FOSUserBundle]

2022-08-30 11:24:27

我正在尝试用一些User对象预填充数据库,但是当我调用并保存用户对象时,字符串“some-password”直接存储在数据库中,而不是散列+salted密码。$user->setPassword('some-password');

我的 DataFixture 类:

// Acme/SecurityBundle/DataFixtures/ORM/LoadUserData.php
<?php

namespace Acme\SecurityBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

use Acme\SecurityBundle\Entity\User;

class LoadUserData implements FixtureInterface
{
    public function load(ObjectManager $manager)
    {
        $userAdmin = new User();
        $userAdmin->setUsername('System');
        $userAdmin->setEmail('system@example.com');
        $userAdmin->setPassword('test');

        $manager->persist($userAdmin);
        $manager->flush();
    }
}

以及相关的数据库输出:

id  username    email               salt                                password
1   System      system@example.com  3f92m2tqa2kg8cookg84s4sow80880g     test

答案 1

由于您正在使用FOSUserBundle,因此您可以使用它来执行此操作。我会使用这个代码(假设你已经设置):UserManager$this->container

public function load(ObjectManager $manager)
{
    $userManager = $this->container->get('fos_user.user_manager');

    $userAdmin = $userManager->createUser();

    $userAdmin->setUsername('System');
    $userAdmin->setEmail('system@example.com');
    $userAdmin->setPlainPassword('test');
    $userAdmin->setEnabled(true);

    $userManager->updateUser($userAdmin, true);
}

答案 2

改为调用 setPlainPassword。

<?php

namespace Acme\SecurityBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Doctrine\Common\Persistence\ObjectManager;

use Acme\SecurityBundle\Entity\User;

class LoadUserData implements FixtureInterface, ContainerAwareInterface
{
    private $container;

    public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;
    }

    public function load(ObjectManager $manager)
    {

        $userAdmin = new User();

        $userAdmin->setUsername('System');
        $userAdmin->setEmail('system@example.com');            
        $userAdmin->setPlainPassword('test');
        $userAdmin->setRoles(array('ROLE_SUPER_ADMIN'));

        $manager->persist($userAdmin);
        $manager->flush();
    }
}

推荐