How can I write a service provider for the HWIOAuthBundle
I want to write a social media login function.
if the user is not registered, it is saved in the database, if the user exists, login. What should I write to my ISP? Status of documents:
The bundle requires a service that can load users based on a custom response from an oauth endpoint. If you have a custom service, must implement the interface: HWI \ Bundle \ OAuthBundle \ Security \ Basic \ User \ OAuthAwareUserProviderInterface.
So this is what I wrote and then I got stuck
<?php
namespace ng\MyBundle\Controller\Listeners;
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;
class OAuthUserProvider implements OAuthAwareUserProviderInterface
{
}
Can you tell me which methods should I use?
Can anyone give me an example of a provider without using FOSuserBundle?
thank
source to share
If you open the OAuthAwareUserProviderInterface, you can see that it only has one method:
/**
* Loads the user by a given UserResponseInterface object.
*
* @param UserResponseInterface $response
*
* @return UserInterface
*
* @throws UsernameNotFoundException if the user is not found
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response);
Below is an example on how to implement it, of course in your case, you should call the entity managers and access the users the way you designed it.
/**
* {@inheritdoc}
*/
public function loadUserByOAuthUserResponse(UserResponseInterface $response)
{
$username = $response->getUsername();
$user = $this->userManager->findUserBy(array($this->getProperty($response) => $username));
//when the user is registrating
if (null === $user) {
$service = $response->getResourceOwner()->getName();
$setter = 'set'.ucfirst($service);
$setter_id = $setter.'Id';
$setter_token = $setter.'AccessToken';
// create new user here
$user = $this->userManager->createUser();
$user->$setter_id($username);
$user->$setter_token($response->getAccessToken());
//I have set all requested data with the user username
//modify here with relevant data
$user->setUsername($username);
$user->setEmail($username);
$user->setPassword($username);
$user->setEnabled(true);
$this->userManager->updateUser($user);
return $user;
}
//if user exists - go with the HWIOAuth way
$user = parent::loadUserByOAuthUserResponse($response);
$serviceName = $response->getResourceOwner()->getName();
$setter = 'set' . ucfirst($serviceName) . 'AccessToken';
//update access token
$user->$setter($response->getAccessToken());
return $user;
}
source to share