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 [
......
......@@ -49,6 +49,9 @@ use Drupal\user\UserInterface;
* "name" = "name",
* "surname" = "surname",
* "taxis_taxid" = "taxis_taxid",
* "requesttoken" = "requesttoken",
* "accesstoken" = "accesstoken",
* "authtoken" = "authtoken",
* },
* links = {
* "canonical" = "/admin/structure/epal_users/{epal_users}",
......@@ -208,34 +211,6 @@ class EpalUsers extends ContentEntityBase implements EpalUsersInterface {
return $this;
}
/*
public function getAddress() {
return $this->get('address')->value;
}
public function setAddress($name) {
$this->set('address', $name);
return $this;
}
public function getAddresstk() {
return $this->get('addresstk')->value;
}
public function setAddresstk($name) {
$this->set('addresstk', $name);
return $this;
}
public function getAddressarea() {
return $this->get('addressarea')->value;
}
public function setAddressarea($name) {
$this->set('addressarea', $name);
return $this;
}
*/
public function getAccesstoken() {
return $this->get('accesstoken')->value;
......@@ -291,6 +266,34 @@ class EpalUsers extends ContentEntityBase implements EpalUsersInterface {
return $this;
}
public function getRequestToken() {
return $this->get('requesttoken')->value;
}
public function setRequestToken($requestToken) {
$this->set('requesttoken', $requestToken);
return $this;
}
public function getRequestTokenSecret() {
return $this->get('requesttokensecret')->value;
}
public function setRequestTokenSecret($requestTokenSecret) {
$this->set('requesttokensecret', $requestTokenSecret);
return $this;
}
public function getAccessTokenSecret() {
return $this->get('accesstokensecret')->value;
}
public function setAccessTokenSecret($accessTokenSecret) {
$this->set('accesstokensecret', $accessTokenSecret);
return $this;
}
/**
* {@inheritdoc}
*/
......@@ -473,12 +476,11 @@ class EpalUsers extends ContentEntityBase implements EpalUsersInterface {
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
/*
$fields['address'] = BaseFieldDefinition::create('string')
->setLabel(t('Διεύθυνση κατοικίας'))
->setDescription(t('Δώσε τη διεύθυνση κατοικίας.'))
$fields['accesstoken'] = BaseFieldDefinition::create('string')
->setLabel(t('Access-Token από taxis'))
->setDescription(t('Access-Token από taxis.'))
->setSettings(array(
'max_length' => 50,
'max_length' => 1000,
'text_processing' => 0,
))
->setDefaultValue('')
......@@ -494,11 +496,11 @@ class EpalUsers extends ContentEntityBase implements EpalUsersInterface {
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['addresstk'] = BaseFieldDefinition::create('string')
->setLabel(t('ΤΚ'))
->setDescription(t('Δώσε τον ΤΚ κατοικίας.'))
$fields['accesstoken_secret'] = BaseFieldDefinition::create('string')
->setLabel(t('Access-Token Secret από taxis'))
->setDescription(t('Access-Token Secret από taxis.'))
->setSettings(array(
'max_length' => 20,
'max_length' => 1000,
'text_processing' => 0,
))
->setDefaultValue('')
......@@ -514,11 +516,11 @@ class EpalUsers extends ContentEntityBase implements EpalUsersInterface {
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['addressarea'] = BaseFieldDefinition::create('string')
->setLabel(t('Πόλη/Περιοχή διεύθυνσης κατοικίας'))
->setDescription(t('Δώσε την πόλη/περιοχή διεύθυνσης.'))
$fields['authtoken'] = BaseFieldDefinition::create('string')
->setLabel(t('Authorization Token'))
->setDescription(t('Authorization Token που δημιουργείται από την εφαρμογή.'))
->setSettings(array(
'max_length' => 50,
'max_length' => 1000,
'text_processing' => 0,
))
->setDefaultValue('')
......@@ -533,13 +535,12 @@ class EpalUsers extends ContentEntityBase implements EpalUsersInterface {
))
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
*/
$fields['accesstoken'] = BaseFieldDefinition::create('string')
->setLabel(t('Access-Token από taxis'))
->setDescription(t('Access-Token από taxis.'))
$fields['requesttoken'] = BaseFieldDefinition::create('string')
->setLabel(t('Oauth Request Token'))
->setDescription(t('Request Token received by service provider.'))
->setSettings(array(
'max_length' => 300,
'max_length' => 1000,
'text_processing' => 0,
))
->setDefaultValue('')
......@@ -555,11 +556,11 @@ class EpalUsers extends ContentEntityBase implements EpalUsersInterface {
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
$fields['authtoken'] = BaseFieldDefinition::create('string')
->setLabel(t('Authorization Token'))
->setDescription(t('Authorization Token που δημιουργείται από την εφαρμογή.'))
$fields['requesttoken_secret'] = BaseFieldDefinition::create('string')
->setLabel(t('Oauth Request Token Secret'))
->setDescription(t('Request Token Secret received by service provider.'))
->setSettings(array(
'max_length' => 300,
'max_length' => 1000,
'text_processing' => 0,
))
->setDefaultValue('')
......@@ -595,9 +596,11 @@ class EpalUsers extends ContentEntityBase implements EpalUsersInterface {
->setDisplayOptions('view', array(
'label' => 'above',
'type' => 'integer',
'weight' => -4,
))
->setDisplayOptions('form', array(
'type' => 'integer',
'weight' => -4,
))
->setDisplayConfigurable('form', TRUE)
->setDisplayConfigurable('view', TRUE);
......
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;