Skip to content

Instantly share code, notes, and snippets.

@jakzal
Last active May 2, 2022 10:18
Show Gist options
  • Save jakzal/8254962 to your computer and use it in GitHub Desktop.
Save jakzal/8254962 to your computer and use it in GitHub Desktop.
Logging user into a Symfony app in Behat
<?php
namespace Acme\Context;
use Acme\MyApp\User;
use Behat\MinkExtension\Context\RawMinkContext;
use Behat\Symfony2Extension\Context\KernelAwareInterface;
use Doctrine\ORM\EntityManager;
use HWI\Bundle\OAuthBundle\Security\Core\Authentication\Token\OAuthToken;
use Symfony\Component\HttpKernel\KernelInterface;
class LeaveRequestContext extends RawMinkContext implements KernelAwareInterface
{
/**
* @var KernelInterface
*/
private $kernel;
/**
* @var User
*/
private $user;
/**
* @param KernelInterface $kernel
*/
public function setKernel(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
/**
* @Given /^I am logged in$/
*/
public function iAmLoggedIn()
{
$this->user = $this->createUser();
$token = $this->createOAuthToken($this->user, array('ROLE_USER'));
$firewall = 'secured_area';
$session = $this->kernel->getContainer()->get('session');
$session->set('_security_'.$firewall, serialize($token));
$session->save();
$this->getSession()->setCookie($session->getName(), $session->getId());
}
/**
* @return User
*/
private function createUser()
{
$user = new User();
$user->setName('Kuba');
$em = $this->getEntityManager();
$em->persist($user);
$em->flush();
return $user;
}
/**
* @param User $user
* @param array $roles
*
* @return OAuthToken
*/
private function createOAuthToken(User $user, array $roles)
{
$accessToken = array (
'access_token' => 'ya29.1.AADtN_VkmddcBXq1eg-0fleRxahbSkIYb7CCY1sKLCyTzcqDa_xMMzA--dwL6QQAKh6Bmg',
'token_type' => 'Bearer',
'expires_in' => 3600,
'id_token' => 'eyJhbGciOiJSUzI1NiIsImtpZCI6IjFkYjcxNzc4ZjkyOTBlNmVjOWQ5ZjFkYTQzMDA4NjE4MDllYzk2NGUifQ'
);
$token = new OAuthToken($accessToken, $roles);
$token->setResourceOwnerName('google');
$token->setUser($user);
return $token;
}
/**
* @return EntityManager
*/
private function getEntityManager()
{
return $this->kernel->getContainer()->get('doctrine')->getManager();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment