OAuthOSTConsumer.php 7.32 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
<?php

namespace Drupal\oauthost\Authentication\Provider;

use Drupal\Core\Authentication\AuthenticationProviderInterface;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use OAuth;
use OAuthException;

/**
 * Class OSTAuthenticationProvider.
 */
class OAuthOSTConsumer implements AuthenticationProviderInterface
{
    protected $consumer_key = 'tc97t89';
    protected $consumer_secret = 'xr7tgt9AbK3';
    protected $request_token_url = 'https://www1.gsis.gr/gsisapps/gsisdemo/oauth/request_token';
    protected $user_authorization_url = 'https://www1.gsis.gr/gsisapps/gsisdemo/oauth/confirm_access';
    protected $access_token_url = 'https://www1.gsis.gr/gsisapps/gsisdemo/oauth/access_token';
Open Source Developer's avatar
commit  
Open Source Developer committed
26
    protected $signature_method = 'PLAINTEXT'; 
27
    protected $api_url = 'https://www1.gsis.gr/gsisapps/gsisdemo/gsisdemoservice/resource_one';
Open Source Developer's avatar
commit  
Open Source Developer committed
28
    protected $callback_url = 'http://localhost/angular/eepal-front/drupal/oauth/cb';
29 30 31
    protected $logout_url = 'https://www1.gsis.gr/testgsisapps/gsisdemo/logout.htm?logout_token=';

  /**
Open Source Developer's avatar
commit  
Open Source Developer committed
32
   * The config factory. 
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * The user data service.
   *
   * @var \Drupal\user\UserDataInterface
   */
  protected $user_data;

  /**
   * The logger service for OAuth.
   *
   * @var \Psr\Log\LoggerInterface
   */
  protected $logger;

  /**
   * An authenticated user object.
   *
   * @var \Drupal\user\UserBCDecorator
   */
  protected $user;

  /**
   * Constructor.
   *
   * @param \Drupal\user\UserDataInterface
   *  The user data service
   * @param \Psr\Log\LoggerInterface $logger
   *   The logger service for OAuth
   */
/*  public function __construct(UserDataInterface $user_data, LoggerInterface $logger) {
    $this->user_data = $user_data;
    $this->logger = $logger;
} */

  /**
   * Constructs a HTTP basic authentication provider object.
   *
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   The config factory
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager service
   */
  public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager, LoggerInterface $logger)
  {
      $this->configFactory = $config_factory;
      $this->entityTypeManager = $entity_type_manager;
      $this->logger = $logger;
  }

  /**
   * Checks whether suitable authentication credentials are on the request.
   *
   * @param \Symfony\Component\HttpFoundation\Request $request
   *   The request object
   *
   * @return bool
   *   TRUE if authentication credentials suitable for this provider are on the
   *   request, FALSE otherwise
   */
  public function applies(Request $request)
  {
      // If you return TRUE and the method Authentication logic fails,
    // you will get out from Drupal navigation if you are logged in.

    // Only check requests with the 'authorization' header starting with OAuth.
    // drupal_set_message('sdfsddgdg');
111
    $oauthEnabled = $this->getHeader($request, 'X-oauth-enabled');
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
    if (!$oauthEnabled && $request->getMethod() == 'POST') {
        $oauthEnabled = $request->request->get('X-oauth-enabled');
    }
//    $this->logger->warning("oauthEnabled=" . $oauthEnabled);
    if (!isset($oauthEnabled) || $oauthEnabled === false) {
        return false;
    }
    return true;


    //  return $this->getHeader($request, 'x-oauth-enabled');
//    return preg_match('/^OAuth/', $request->headers->get('authorization'));

//    return $this->checkAuthToken($this->getAuthToken($request));
  }

/*    private function checkAuthToken($authToken)
    {
        if (!$authToken) {
            return false;
        } elseif ($authToken === 'testAuthToken') {
            return $authToken;
        } else {
            return false;
        }
    } */

    private function getHeader($request, $headerName)
    {
        $headerValue = $request->headers->get($headerName);
        if (isset($headerValue) && $headerValue !== '') {
            return $headerValue;
        } else {
            return false;
        }
    }


  /**
   * {@inheritdoc}
   */
/*  public function authenticate(Request $request) {
    $consumer_ip = $request->getClientIp();
    $ips = ['192.168.0.59:80'];
//    if (in_array($consumer_ip, $ips)) {

    if ($request->query->get('name') === 'haris') {
      // Return Anonymous user.
      print_r($request->query->get('name'));
      return true;
//      return $this->entityTypeManager->getStorage('user')->load(1);
    }
    else {
      throw new AccessDeniedHttpException();
    }
} */

  public function authenticate(Request $request)
  {
      // if(!$this->getHeader($request, "x-oauth-token") && $_SESSION['state'] && $_SESSION['state']==1) $_SESSION['state'] = 0;
      $this->logger->warning("authenticate:" . "oauthToken=" . $request->query->get('oauth_token') . " state=" . $_SESSION['state']);
      if($request->query->get('oauth_token') == null && $_SESSION['state'] && $_SESSION['state']==1) $_SESSION['state'] = 0;
      try {
          if (isset($request->query)) {
             $authToken = $request->query->get('oauth_token');
             $authVerifier = $request->query->get('oauth_verifier');
         } else {
             $authToken = false;
             $authVerifier = false;
         }
          $oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
          $oauth->enableDebug();

          $this->logger->warning("i am here:" . "oauthToken=" . $authToken . " state=" . $_SESSION['state']);
186 187
          $this->logger->warning("send request token");
          $requestToken = $oauth->getRequestToken($this->request_token_url, $this->callback_url);
188
              // store auth token
189 190 191
          $this->logger->warning("requestToken=" . $requestToken['oauth_token_secret']);
          $_SESSION['secret'] = $requestToken['oauth_token_secret'];
          $_SESSION['state'] = 1;
192 193
//              $_SESSION['secret'] = $request_token['oauth_token_secret'];

194 195 196
          header('Location: '.$this->user_authorization_url.'?oauth_token='.$requestToken['oauth_token']);
          $this->logger->warning("redirected to:" . $this->user_authorization_url . '?oauth_token=' . $requestToken['oauth_token']);
          exit;
197 198 199 200 201 202 203 204 205 206 207 208 209

      } catch (OAuthException $e) {

          $this->logger->warning($e->getMessage());
      }
    // Check if we found a user.
/*    if (!empty($this->user)) {
        return $this->user;
    } */

//      return null;
  }

210

211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
  /**
   * {@inheritdoc}
   */
  public function cleanup(Request $request)
  {
  }

  /*
   * {@inheritdoc}
   */
/*  public function handleException(GetResponseForExceptionEvent $event) {
    $exception = $event->getException();
    if ($exception instanceof AccessDeniedHttpException) {
      $event->setException(
        new UnauthorizedHttpException('Invalid consumer origin.', $exception)
      );
      return TRUE;
    }
    return FALSE;
} */
}