Reputation: 67
I'm doing a authentication with guard feature. Problem is than I have to put a password to my User, he don't have to know this password so I choose to generate a random password. Problem is than I'm not in a controller so I can't use UserPasswordEncoderInterface ... So I'm looking for some help here.
I give you some code :
public function getUser($credentials, UserProviderInterface $userProvider)
{
/**
* @var FacebookUser $facebookUser
*/
$facebookUser = $this->getFacebookClient()
->fetchUserFromToken($credentials);
$email = $facebookUser->getEmail();
$user = $this->em->getRepository('App:User')
->findOneBy(['email' => $email]);
if (!$user) {
$user = new User();
$user->setEmail($facebookUser->getEmail());
$user->setName($facebookUser->getFirstName());
$user->setLastName($facebookUser->getLastName());
$user->setRoles(["ROLE_USER"]);
//TODO HASH PASSWORD
$user->setPassword(bin2hex(random_bytes(80)));
$this->em->persist($user);
$this->em->flush();
}
return $user;
}
and the method from controller
/**
* After going to Facebook, you're redirected back here
* because this is the "redirect_route" you configured
* in config/packages/knpu_oauth2_client.yaml
* @Route("/connect/facebook/check", name="connect_facebook_check")
*
* @return JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
*/
public function connectCheckAction() {
if (!$this->getUser()) {
return new JsonResponse(array('status' => false, 'message' => "User not found!"));
} else {
// $em = $this->getDoctrine()->getManager();
//
// $user = $this->getUser();
// $password = bin2hex(random_bytes(80));
// $hash = $encoder->encodePassword($user, $password);
// $user->setPassword($hash);
//
// $em->persist($user);
// $em->flush();
return $this->redirectToRoute('default');
}
}
Upvotes: 0
Views: 144
Reputation: 1057
You can inject EncoderFactoryInterface by constructor:
/**
* @var EncoderFactoryInterface
*/
private $securityEncoderFactory;
public function __construct(EncoderFactoryInterface $securityEncoderFactory)
{
$this->securityEncoderFactory = $securityEncoderFactory;
}
And then use:
$encoder = $this->securityEncoderFactory->getEncoder($user);
$encoder->encodePassword($user, $password);
Upvotes: 2
Reputation: 1755
You can just use the PHP's function password_hash
to hash your randomly generated password. See the documentation here
Upvotes: 1