我使用FOSUserBundle和Facebook API。我想允许我的用户使用此API在我的网站上注册。然后我希望他们可以登录我的网站。
我不知道如何自动生成密码的哈希值以匹配FOSUserBundle。
我在互联网上找到了这个下一个代码,我不明白我是如何将它与FOSUserBundle相匹配的......
如果sombebody可以帮助我......提前致谢并抱歉我的英语。
/**
* Loading and ad-hoc creation of a user by an OAuth sign-in provider account.
*
* @author Fabian Kiss <fabian.kiss@ymc.ch>
*/
class UserProvider extends FOSUBUserProvider{
/**
* {@inheritDoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response){
try {
return parent::loadUserByOAuthUserResponse($response);
} catch (UsernameNotFoundException $e) {
if (null === $user = $this->userManager->findUserByEmail($response->getEmail())) {
return $this->createUserByOAuthUserResponse($response);
}
return $this->updateUserByOAuthUserResponse($user, $response);
}
}
/**
* {@inheritDoc}
*/
public function connect(UserInterface $user, UserResponseInterface $response){
$providerName = $response->getResourceOwner()->getName();
$uniqueId = $response->getUsername();
$user->addOAuthAccount($providerName, $uniqueId);
$this->userManager->updateUser($user);
}
/**
* Ad-hoc creation of user
*
* @param UserResponseInterface $response
*
* @return User
*/
protected function createUserByOAuthUserResponse(UserResponseInterface $response){
$user = $this->userManager->createUser();
$this->updateUserByOAuthUserResponse($user, $response);
// set default values taken from OAuth sign-in provider account
if (null !== $email = $response->getEmail()) {
$user->setEmail($email);
}
if (null === $this->userManager->findUserByUsername($response->getNickname())) {
$user->setUsername($response->getNickname());
}
$user->setUsername(strtolower(str_replace(' ','',$response->getRealName()).''.rand(0,199)));
$user->setUsernameCanonical(strtolower(str_replace(' ','',$response->getRealName()).''.rand(0,199)));
$user->setEnabled(false);
return $user;
}
/**
* Attach OAuth sign-in provider account to existing user
*
* @param FOSUserInterface $user
* @param UserResponseInterface $response
*
* @return FOSUserInterface
*/
protected function updateUserByOAuthUserResponse(FOSUserInterface $user, UserResponseInterface $response){
$providerName = $response->getResourceOwner()->getName();
$providerNameSetter = 'set'.ucfirst($providerName).'Id';
$user->$providerNameSetter($response->getUsername());
if(!$user->getPassword()) {
// generate unique token
$secret = md5(uniqid(rand(),true));
$user->setPassword($secret);
}
return $user;
}
}
答案 0 :(得分:0)
您可以使用encoder_factory和用户的salt对密码进行编码。 (我使用容器获取服务,将服务用于Provider类的构造函数中)
$user = $userManager->createUser();
$encoder = $this->container->get('security.encoder_factory')->getEncoder($user);
$user->setPlainPassword(
$encoder->encodePassword(
$this->container->get('fos_user.util.token_generator')->generateToken(),
$user->getSalt()
)
);