New oauthost module. Beta Version for testing

parent 83f1145d
......@@ -4,6 +4,14 @@ epal_is_logged_in:
_controller: '\Drupal\epal\Controller\Login::helloWorld'
requirements:
_access: 'TRUE'
epal_entityapi_test:
path: '/epal/entityapi/test'
options:
_auth: [ 'basic_auth' ]
requirements:
_user_is_logged_in: 'TRUE'
defaults:
_controller: '\Drupal\epal\Controller\Login::testQuery'
epal_auth_test:
path: 'epal/auth/test'
options:
......
......@@ -11,6 +11,7 @@ use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityFieldManagerInterface;
/**
* Controller routines for page example routes.
......@@ -18,18 +19,22 @@ use Drupal\Core\Controller\ControllerBase;
class Login extends ControllerBase {
protected $query_factory;
protected $entityTypeManager;
protected $entityFieldManager;
public function __construct(EntityTypeManagerInterface $entityTypeManager, QueryFactory $query_factory) {
public function __construct(EntityTypeManagerInterface $entityTypeManager, QueryFactory $query_factory, EntityFieldManagerInterface $entityFieldManager) {
// public function __construct(QueryFactory $query_factory) {
$this->entityTypeManager = $entityTypeManager;
$this->query_factory = $query_factory;
$this->entityFieldManager = $entityFieldManager;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager'),
$container->get('entity.query')
$container->get('entity_type.manager'),
$container->get('entity.query'),
$container->get('entity_field.manager')
);
}
......@@ -67,7 +72,57 @@ public function helloWorld() {
}
return array_values($arrayToReturn);
}
public function object_2_array($result) {
$array = array();
foreach ($result as $key=>$value)
{
if (is_object($value))
{
$array[$key]=$this->object_2_array($value);
}
elseif (is_array($value))
{
$array[$key]=$this->object_2_array($value);
}
else
{
$array[$key]=$value;
}
}
return $array;
}
public function testQuery() {
$query = $this->query_factory->get('epal_users');
// ->condition('status', 1);
$scids = $query->execute();
$epalUsers_storage = $this->entityTypeManager->getStorage('epal_users');
$epalUsers = $epalUsers_storage->loadMultiple($scids);
$arrayToReturn = array();
$j=0;
foreach ($epalUsers as $epalUser) {
// print_r($epalUser);
// $arrayToReturn[$j] = implode(",", $this->object_2_array($epalUser->id) );
$arrayToReturn[$j] = $epalUser->user_id->target_id;
$j++;
/* foreach ($epalUser->name as $delta => $item) {
$arrayToReturn[$delta] = $item->value;
} */
/* array_push($arrayToReturn,
$epalUser->surname->getValue()); */
}
// return array_values($arrayToReturn);
$response = new JsonResponse($arrayToReturn);
return $response;
}
public function basicQuery() {
return [
......
entity.oauthost_config.add_form:
route_name: entity.oauthost_config.add_form
title: 'Add OAuthOST Config'
appears_on:
- entity.oauthost_config.collection
entity.oauthost_session.add_form:
route_name: entity.oauthost_session.add_form
title: 'Add OAuthOST Session'
appears_on:
- entity.oauthost_session.collection
# OAuthOST Config menu items definition
entity.oauthost_config.collection:
title: 'OAuthOST Config list'
route_name: entity.oauthost_config.collection
description: 'List OAuthOST Config entities'
parent: system.admin_structure
weight: 100
oauthost_config.admin.structure.settings:
title: OAuthOST Config settings
description: 'Configure OAuthOST Config entities'
route_name: oauthost_config.settings
parent: system.admin_structure
# OAuthOST Session menu items definition
entity.oauthost_session.collection:
title: 'OAuthOST Session list'
route_name: entity.oauthost_session.collection
description: 'List OAuthOST Session entities'
parent: system.admin_structure
weight: 100
oauthost_session.admin.structure.settings:
title: OAuthOST Session settings
description: 'Configure OAuthOST Session entities'
route_name: oauthost_session.settings
parent: system.admin_structure
# OAuthOST Config routing definition
oauthost_config.settings_tab:
route_name: oauthost_config.settings
title: 'Settings'
base_route: oauthost_config.settings
entity.oauthost_config.canonical:
route_name: entity.oauthost_config.canonical
base_route: entity.oauthost_config.canonical
title: 'View'
entity.oauthost_config.edit_form:
route_name: entity.oauthost_config.edit_form
base_route: entity.oauthost_config.canonical
title: 'Edit'
entity.oauthost_config.delete_form:
route_name: entity.oauthost_config.delete_form
base_route: entity.oauthost_config.canonical
title: Delete
weight: 10
# OAuthOST Session routing definition
oauthost_session.settings_tab:
route_name: oauthost_session.settings
title: 'Settings'
base_route: oauthost_session.settings
entity.oauthost_session.canonical:
route_name: entity.oauthost_session.canonical
base_route: entity.oauthost_session.canonical
title: 'View'
entity.oauthost_session.edit_form:
route_name: entity.oauthost_session.edit_form
base_route: entity.oauthost_session.canonical
title: 'Edit'
entity.oauthost_session.delete_form:
route_name: entity.oauthost_session.delete_form
base_route: entity.oauthost_session.canonical
title: Delete
weight: 10
add oauthost config entities:
title: 'Create new OAuthOST Config entities'
administer oauthost config entities:
title: 'Administer OAuthOST Config entities'
description: 'Allow to access the administration form to configure OAuthOST Config entities.'
restrict access: true
delete oauthost config entities:
title: 'Delete OAuthOST Config entities'
edit oauthost config entities:
title: 'Edit OAuthOST Config entities'
access oauthost config overview:
title: 'Access the OAuthOST Config overview page'
view published oauthost config entities:
title: 'View published OAuthOST Config entities'
view unpublished oauthost config entities:
title: 'View unpublished OAuthOST Config entities'
add oauthost session entities:
title: 'Create new OAuthOST Session entities'
administer oauthost session entities:
title: 'Administer OAuthOST Session entities'
description: 'Allow to access the administration form to configure OAuthOST Session entities.'
restrict access: true
delete oauthost session entities:
title: 'Delete OAuthOST Session entities'
edit oauthost session entities:
title: 'Edit OAuthOST Session entities'
access oauthost session overview:
title: 'Access the OAuthOST Session overview page'
view published oauthost session entities:
title: 'View published OAuthOST Session entities'
view unpublished oauthost session entities:
title: 'View unpublished OAuthOST Session entities'
oauthost.log_in_go:
path: /oauth/login
defaults:
_controller: '\Drupal\oauthost\Controller\OAuthLogin::loginGo'
requirements:
_access: 'TRUE'
oauthost.callback_log_in:
path: /oauth/cb
defaults:
......
services:
authentication.oauthost:
class: Drupal\oauthost\Authentication\Provider\OAuthOSTConsumer
arguments: ['@config.factory', '@entity_type.manager', '@logger.channel.oauth']
tags:
- { name: authentication_provider, provider_id: ostauthentication_provider, priority: 100 }
logger.channel.oauth:
parent: 'logger.channel_base'
arguments: ['oauthost']
<?php
/**
* @file
* Contains oauthost_config.page.inc.
*
* Page callback for OAuthOST Config entities.
*/
use Drupal\Core\Render\Element;
/**
* Prepares variables for OAuthOST Config templates.
*
* Default template: oauthost_config.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An associative array containing the user information and any
* - attributes: HTML attributes for the containing element.
*/
function template_preprocess_oauthost_config(array &$variables) {
// Fetch OAuthOSTConfig Entity Object.
$oauthost_config = $variables['elements']['#oauthost_config'];
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
<?php
/**
* @file
* Contains oauthost_session.page.inc.
*
* Page callback for OAuthOST Session entities.
*/
use Drupal\Core\Render\Element;
/**
* Prepares variables for OAuthOST Session templates.
*
* Default template: oauthost_session.html.twig.
*
* @param array $variables
* An associative array containing:
* - elements: An associative array containing the user information and any
* - attributes: HTML attributes for the containing element.
*/
function template_preprocess_oauthost_session(array &$variables) {
// Fetch OAuthOSTSession Entity Object.
$oauthost_session = $variables['elements']['#oauthost_session'];
// Helpful $content variable for templates.
foreach (Element::children($variables['elements']) as $key) {
$variables['content'][$key] = $variables['elements'][$key];
}
}
<?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';
protected $signature_method = 'PLAINTEXT';
protected $api_url = 'https://www1.gsis.gr/gsisapps/gsisdemo/gsisdemoservice/resource_one';
protected $callback_url = 'http://localhost/angular/eepal-front/drupal/oauth/cb';
protected $logout_url = 'https://www1.gsis.gr/testgsisapps/gsisdemo/logout.htm?logout_token=';
/**
* The config factory.
*
* @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');
$oauthEnabled = $this->getHeader($request, 'X-oauth-enabled');
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']);
$this->logger->warning("send request token");
$requestToken = $oauth->getRequestToken($this->request_token_url, $this->callback_url);
// store auth token
$this->logger->warning("requestToken=" . $requestToken['oauth_token_secret']);
$_SESSION['secret'] = $requestToken['oauth_token_secret'];
$_SESSION['state'] = 1;
// $_SESSION['secret'] = $request_token['oauth_token_secret'];
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;
} catch (OAuthException $e) {
$this->logger->warning($e->getMessage());
}
// Check if we found a user.
/* if (!empty($this->user)) {
return $this->user;
} */
// return null;
}
/**
* {@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;
} */
}
<?php
namespace Drupal\oauthost\Controller;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
use OAuth;
use OAuthException;
use Drupal\user\Entity\User;
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
class OAuthLogin extends ControllerBase
{
protected $entity_query;
protected $entityTypeManager;
protected $logger;
protected $connection;
protected $consumer_key = 'tc97t89';
protected $consumer_secret = 'xr7tgt9AbK3';
protected $request_token_url;
protected $user_authorization_url;
protected $access_token_url;
protected $signature_method;
protected $api_url;
protected $callback_url;
protected $logout_url;
public function __construct(
EntityTypeManagerInterface $entityTypeManager,
QueryFactory $entity_query,
Connection $connection,
LoggerChannelFactoryInterface $loggerChannel)
{
$this->entityTypeManager = $entityTypeManager;
$this->entity_query = $entity_query;
$this->connection = $connection;
$this->logger = $loggerChannel->get('oauthost');
}
public static function create(ContainerInterface $container)
{
return new static(
$container->get('entity.manager'),
$container->get('entity.query'),
$container->get('database'),
$container->get('logger.factory')
);
}
public function loginGo(Request $request)
{
$ostauthConfigs = $this->entityTypeManager->getStorage('oauthost_config')->loadByProperties(array('name' => 'oauthost_taxisnet_config'));
$ostauthConfig = reset($ostauthConfigs);
if ($ostauthConfig) {
$this->consumer_key = $ostauthConfig->consumer_key->value;
$this->consumer_secret = $ostauthConfig->consumer_secret->value;
$this->request_token_url = $ostauthConfig->request_token_url->value;
$this->user_authorization_url = $ostauthConfig->user_authorization_url->value;
$this->access_token_url = $ostauthConfig->access_token_url->value;
$this->signature_method = $ostauthConfig->signature_method->value;
$this->api_url = $ostauthConfig->api_url->value;
$this->callback_url = $ostauthConfig->callback_url->value;
$this->logout_url = $ostauthConfig->logout_url->value;
} else {
$response = new Response();
$response->setContent('forbidden');
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$customUser = null;
$customUsers = null;
$userId = null;
$user = null;
try {
$oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$uniqid = uniqid('sid');
$requestToken = $oauth->getRequestToken($this->request_token_url, $this->callback_url . '?sid_ost=' . $uniqid);
// store auth token
$oauthostSession = $this->entityTypeManager()->getStorage('oauthost_session')->create(array(
// 'langcode' => $language_interface->getId(),
'langcode' => 'el',
'user_id' => \Drupal::currentUser()->id(),
'name' => $uniqid,
'request_token' => $requestToken['oauth_token'],
'request_token_secret' => $requestToken['oauth_token_secret'],
'status' => 1
));
$oauthostSession->save();
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;
} catch (OAuthException $e) {
$this->logger->warning($e->getMessage());
$response = new Response();
$response->setContent('forbidden');
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
}
This diff is collapsed.
<?php
namespace Drupal\oauthost\Entity;
use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\user\EntityOwnerInterface;
/**
* Provides an interface for defining OAuthOST Config entities.
*
* @ingroup oauthost
*/
interface OAuthOSTConfigInterface extends ContentEntityInterface, EntityChangedInterface, EntityOwnerInterface {
// Add get/set methods for your configuration properties here.
/**
* Gets the OAuthOST Config name.
*
* @return string
* Name of the OAuthOST Config.