How can I write a user provider for HWIOAuthBundle

蓝咒 提交于 2020-02-24 11:07:53

问题


I want to write a login feature via social networks.
if the user is not logged it persists it into the database, if the user exists, log the user in. What should I write into my provider? Docs state :

The bundle needs a service that is able to load users based on the user response of the oauth endpoint. If you have a custom service it should implement the interface: HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface.

So this is what I wrote and then got stuck

<?php
namespace ng\MyBundle\Controller\Listeners;

use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface;

class OAuthUserProvider implements OAuthAwareUserProviderInterface
{

}

Can you tell me what are the methods That I should use ?
Can anybody give me a provider example not using FOSuserBundle ?
Thanks


回答1:


If you open the OAuthAwareUserProviderInterface you can see it has only 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 there is an example on how to implement it, ofcourse in your case, you should call your entity managers, and access users the way you have 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's 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;
}


来源:https://stackoverflow.com/questions/26760059/how-can-i-write-a-user-provider-for-hwioauthbundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!