我正在使用防护功能进行身份验证。问题是我必须向用户输入密码,他不必知道此密码,因此我选择生成随机密码。问题是我不在控制器中,所以我不能使用UserPasswordEncoderInterface ...所以我在这里寻求帮助。
我给你一些代码:
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;
}
和控制器中的方法
/**
* 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');
}
}
答案 0 :(得分:2)
您可以通过构造函数注入EncoderFactoryInterface:
/**
* @var EncoderFactoryInterface
*/
private $securityEncoderFactory;
public function __construct(EncoderFactoryInterface $securityEncoderFactory)
{
$this->securityEncoderFactory = $securityEncoderFactory;
}
然后使用:
$encoder = $this->securityEncoderFactory->getEncoder($user);
$encoder->encodePassword($user, $password);
答案 1 :(得分:1)
您可以只使用PHP的函数password_hash
来哈希您随机生成的密码。请参阅文档here