Jaeger
Jaeger

Reputation: 1754

Troubles with logging in with a newly created user

I created a CRUD that allows me to create users, societies and schools in a back office.

However, for an unknown reason, I can't log in with a created user with the password I gave him.

Here is my controller (the part where the user is created)

/**
 * Creates a new User entity.
 *
 * @Route("/new", name="user_new")
 * @Method({"GET", "POST"})
 */
public function newAction(Request $request)
{
    $user = new User();
    $form = $this->createForm('UserBundle\Form\UserType', $user);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();


        $password = $this->get('security.password_encoder')->encodePassword($user, $user->getPassword());

        $user->setPassword($password);
        $em->persist($user);
        $em->flush();

        return $this->redirectToRoute('user_show', array('id' => $user->getId()));
    }

    return $this->render('user/new.html.twig', array(
        'user' => $user,
        'form' => $form->createView(),
    ));
}

After registering a new user, when I check it in the fos_user table, I can see that the password has been encrypted. However, if I try to login with the password I used, I simply get "bad credential" from my login form.

I can't figure out why. Tell me if you need to see another file, I'll update my question

Any idea ?

Thank you in advance

Upvotes: 1

Views: 48

Answers (1)

CountZero
CountZero

Reputation: 196

The correct way to create user and set password in FOSUserBundle is the following:

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

$userAdmin = $userManager->createUser();

$userAdmin->setUsername('System');
$userAdmin->setEmail('[email protected]');
$userAdmin->setPlainPassword('test');
$userAdmin->setEnabled(true);

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

Password is kept encrypted in database. And to make it harder to bruteforce, database contains an additional field, named salt. You don't store it in your code, that's why it's impossible later to check password. But actually, you don't have to encrypt password and store it in database. User model contains a special method for it, setPlainPassword, which is intended to encrypt password populate both fields salt and password in database with correct values.

Upvotes: 2

Related Questions