Search code examples
passwordssymfonymd5database-migrationfosuserbundle

FOSUserBundle: Custom password / Migration from old DB structure


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?


Solution

  • 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.