开发者

Symfony2 code organization: where should logic for encrypting password before persisting to db go?

If you use a database to store users you could save user info as shown below: (from the Symfony security book.)

$factory = $this->get('security.encoder_factory');
$user = new Acme\UserBundle\Entity\User();

$encoder = $factory->getEncoder($user);
$password = $encoder->encodePassword('mypassword', $user->getSalt());
$user->setPassword($password);

However, I want to create reusable a User form:

namespace App\Bundle\WebBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class UserType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('username')
            ->add('password')
        ;
    }

    public function getName()
    {
        return 'app_bundle_webbundle_usertype';
    }
}

And use the form in a controller: (from here)

if ($request->getMethod() == 'POST') {
    $form->bindRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $em->persist($task);
        $em->flush();

        return $this->redirect($this->generateUrl('task_success'));
    }
}

Where should you put the code used to hash your 开发者_运维技巧password shown at the beginning of this post (and the code to generate the salt, for that matter) in order to make it reusable and compatible with the $form->bindRequest() approach, in case you need for both a user registration form and a user profile edit form, etc?


I recommend looking into: https://github.com/FriendsOfSymfony/FOSUserBundle . Even if you want to write your own solution, you can get very good ideas from that bundle.


Password encryption could be best placed in Doctrine's @PrePersist callback method.


In the model?

In the setter, you could add your encryption.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜