|
<?php |
|
|
|
namespace Acme\Security\Provider; |
|
|
|
use HWI\Bundle\OAuthBundle\Connect\AccountConnectorInterface; |
|
use HWI\Bundle\OAuthBundle\OAuth\Response\UserResponseInterface; |
|
use HWI\Bundle\OAuthBundle\Security\Core\User\OAuthAwareUserProviderInterface; |
|
use Symfony\Component\Messenger\MessageBusInterface; |
|
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; |
|
use Symfony\Component\Security\Core\User\UserInterface; |
|
use Symfony\Component\Security\Core\User\UserProviderInterface; |
|
use Acme\Domain\Model\Account; |
|
use Acme\Domain\Repository\AccountRepositoryInterface; |
|
|
|
// We implement the AccountConnectorInterface on our user provider, but |
|
// you can define a separate service as well. |
|
final class UserProvider implements |
|
UserProviderInterface, |
|
OAuthAwareUserProviderInterface, |
|
AccountConnectorInterface |
|
{ |
|
private AccountRepositoryInterface $accountRepository; |
|
|
|
public function __construct(AccountRepositoryInterface $accountRepository) |
|
{ |
|
$this->accountRepository = $accountRepository; |
|
} |
|
|
|
/** user provider methods are ommitted **/ |
|
|
|
// This method is used when logging in, and is already documented in the bundle itself. |
|
public function loadUserByOAuthUserResponse(UserResponseInterface $response): UserInterface |
|
{ |
|
$account = $this->accountRepository->findOneByResourceOwnerAndIdentifier( |
|
$response->getResourceOwner()->getName(), |
|
$response->getData()['id'] |
|
); |
|
|
|
if ($account === null) { |
|
throw new UsernameNotFoundException('No account associated'); |
|
} |
|
|
|
return $account; |
|
} |
|
|
|
// This method is called when the connect is succesful. You should store |
|
// the association in the database here. |
|
public function connect( |
|
UserInterface $user, |
|
UserResponseInterface $response |
|
) { |
|
if (!$user instanceof Account) { |
|
throw new \Exception('Invalid user'); |
|
} |
|
|
|
// How you store the association is application specific, |
|
// this is just an example |
|
$account->addConnection( |
|
$response->getResourceOwner()->getName(), |
|
$response->getData()['id'] |
|
); |
|
$this->accountRepository->persist($account); |
|
} |
|
|
|
} |
Can't thank you enough for this gist. It's pretty much translated perfectly to the latest version of HWI OAuth. The bundle is great but stuff like this isn't super clear until you have a dig in. Much appreciated 🙏