123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- <?php
- namespace Base\OAuthClientBundle\EventListener;
- use Symfony\Component\HttpFoundation\RedirectResponse;
- use Symfony\Component\HttpKernel\Event\GetResponseEvent;
- use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
- class RequestListener
- {
- /**
- * @var TokenStorage
- */
- protected $securityTokenStorage;
- /**
- * @var string
- */
- protected $client_id;
-
- /**
- * @var string
- */
- protected $client_secret;
-
- /**
- * @var string
- */
- protected $access_token_url;
- /**
- * @param ContainerInterface $serviceContainer
- * @param string $client_id
- * @param string $client_secret
- * @param string $access_token_url
- */
- public function __construct($serviceContainer, $client_id, $client_secret, $access_token_url)
- {
- $this->container = $serviceContainer;
- $this->securityTokenStorage = $serviceContainer->get('security.token_storage');
- $this->client_id = $client_id;
- $this->client_secret = $client_secret;
- $this->access_token_url = $access_token_url;
- }
- /**
- * @param GetResponseEvent $event
- *
- * @return type
- */
- public function onKernelRequest(GetResponseEvent $event)
- {
- if (!$event->isMasterRequest()) {
- return;
- }
-
- try {
- // Autologin por GET parameters
- $request = $event->getRequest();
- $authorizationUrl = $this->container->get('hwi_oauth.security.oauth_utils')->getAuthorizationUrl($request, 'login');
- $username = $request->query->get('username');
- $plainPassword = $request->query->get('password');
- if ($username && $plainPassword) {
- $event->setResponse(new RedirectResponse($authorizationUrl . "&username={$username}&password={$plainPassword}"));
-
- return;
- }
- } catch(\Exception $ex) {
-
- }
-
- $token = $this->securityTokenStorage->getToken();
- if ($token && method_exists($token, 'isExpired') && $token->isExpired()) {
- $parameters = array(
- 'refresh_token' => $token->getRefreshToken(),
- 'grant_type' => 'refresh_token',
- 'client_id' => $this->client_id,
- 'client_secret' => $this->client_secret
- );
-
- $curl = curl_init();
- curl_setopt_array($curl, array(
- CURLOPT_RETURNTRANSFER => 1,
- CURLOPT_URL => $this->access_token_url . '?' . http_build_query($parameters, '', '&')
- ));
- $response = curl_exec($curl);
- curl_close($curl);
- $newToken = json_decode($response, true);
-
- if (isset($newToken['access_token']) && isset($newToken['refresh_token']) && isset($newToken['expires_in'])) {
- $token->setAccessToken($newToken['access_token']);
- $token->setRefreshToken($newToken['refresh_token']);
- $token->setExpiresIn($newToken['expires_in']);
-
- $this->securityTokenStorage->setToken($token);
- }
- }
-
- return;
- }
- }
|