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

2022-01-16 00:00:00 php symfony doctrine fosuserbundle

我正在尝试使用一些用户对象预填充数据库,但是当我调用 $user->setPassword('some-password'); 然后保存用户对象时,字符串some-password"直接存储在数据库中,而不是散列+加盐密码.

I'm trying to pre-populate a database with some User objects, but when I call $user->setPassword('some-password'); and then save the user object, the string 'some-password' is stored directly in the database, instead of the hashed+salted password.

我的 DataFixture 类:

My DataFixture class:

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

namespace AcmeSecurityBundleDataFixturesORM;

use DoctrineCommonDataFixturesFixtureInterface;
use DoctrineCommonPersistenceObjectManager;

use AcmeSecurityBundleEntityUser;

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();
    }
}

以及相关的数据库输出:

And the relevant database output:

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

推荐答案

由于你使用的是 FOSUserBundle,你可以使用 UserManager 来做到这一点.我会使用这段代码(假设你设置了 $this->container):

Since you are using FOSUserBundle, you can use UserManager to do this. I would use this code (assuming you have $this->container set):

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);
}

相关文章