0
votes

So I am trying to create a website using symfony, which whill have users. These users need to be able to change their passwords from within their accounts (this shouldn't be difficult, a simple form which on submission changes the password of the current user ) However I am struggling to devise a method of implementing a "Reset Password" for users who have entirely forgotten their password.

My plan was for users to be sent an email with a unique link. When visiting that link, symfony (via the slug tag) checks to see if that link was sent out in the last 5 minutes. (perhaps a database somewhere with a list of links, usernames times will be needed). then the user will be given a simple form where they can input their new password, and then be redirected to the login page.

My issue is that I can't hope to run getUser when the user isn't actually authenticated. Even if my database of times, links and usernames can point to a specific user, as far as I can see, Symfony won't load a user class until they have been properly authenticated with a password. How do I get around this? Should I just write to the database manually without involving the securityBundle / user class? Thanks.

3

3 Answers

1
votes

You can load user anytime you want. When you are on reset page and time is valid you also know user ID use User Manager or what your service is and change the user password.

1
votes

Use your Repository/UserRepository class to get the User entity from the db. Modify the User object and persist it using the EntityManager class.

$userRepo = $doctrine->getRepository( 'User' );

$user = $userRepo->find( $userId );

if ( $user !== null ) {

    $encryptedPassword = someHowEncryptThePassword( $plainPassword );
    $user->setPassword( $encryptedPassword );

    $em = $doctrine->getManager();
    $em->persist( $user );
    $em->flush();

}
0
votes

In my opinion you should store the unique link with a relation on the user.

//Quick example
$user = $em->getRepository( 'App:User' )->findByEmail($email);

$lostPassword = new LostPassword();
$lostPassword->setUser($user);
$lostPassword->setHash(uniqid());
//Use hash to send the email to the user here

The previous code is when the user filled the form with his email. You save the user and the generated hash and send the email.

In the password reset route you just have to get the hash and do a find on it

 $lostPassword= $em->getRepository( 'App:LostPassword' )->findByHash($hash);
 $user = $lostPassword->getUser();
 //Your code managment to change the password

Hope this helps.