FOSUserBundle: Custom password / Migration from ol

2019-02-02 01:21发布

问题:

I want to move to Symfony2, because I am totally impressed by its modernity and good programming.

Now I am taking a users table from my old system, with 10,000 users, and I don't want to anger them by making them set a new password....so I want them to be able to login with their old password

Here is pseudo-code of how my users table looks like with 3 major fields concerning login/signup:

id, int(10) unsigned NOT NULL
username varchar(40) NOT NULL
passhash varchar(32) NOT NULL
secret varchar(20) NOT NULL

on signup, the data gets generated this way:

$secret = mksecret ();
$passhash = md5 ($secret . $password_formfield . $secret);

on login, the data gets checked the following way:

if ($row['passhash'] != md5 ($row['secret'] . $password_formfield . $row['secret']))
{
//show login error
}

So how do I handle it best in FOSUserBundle, without having to edit too many files?

回答1:

You need to create a custom password encoder:

<?php

use Symfony\Component\Security\Core\Encoder\BasePasswordEncoder;

class MyPasswordEncoder extends BasePasswordEncoder
{
    public function encodePassword($raw, $salt)
    {
        return md5($salt.$raw.$salt);
    }

    public function isPasswordValid($encoded, $raw, $salt)
    {
        return $this->comparePasswords($encoded, $this->encodePassword($raw, $salt));
    }
}

And configure it in security.yml:

services:
    my_password_encoder:
        class: MyPasswordEncoder

security:
    encoders:
        FOS\UserBundle\Model\UserInterface: { id: my_password_encoder }

As long as User::getSalt() returns secret and User::getPassword() returns passhash you should be good to go.



回答2:

It is very easy to do with FOSUserBundle. This is the code for it:

$userManager = $this->get('fos_user.user_manager');

foreach ($items as $item) {
    $newItem = $userManager->createUser();

    //$newItem->setId($item->getObjId());
    // FOSUserBundle required fields
    $newItem->setUsername($item->getUsername());
    $newItem->setEmail($item->getEmail());
    $newItem->setPlainPassword($item->getPassword()); // get original password
    $newItem->setEnabled(true);

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