Merge branch 'fix-oauth' into 'develop'

Logout fix

See merge request !114
parents 15e2b726 ecddb9e3
......@@ -128,116 +128,111 @@ class CBController extends ControllerBase
public function authenticatePhase2($request, $authToken, $authVerifier)
{
$taxis_userid = null;
$trx = $this->connection->startTransaction();
try {
$oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$oauth->setToken($authToken, $this->requestTokenSecret);
$accessToken = $oauth->getAccessToken($this->access_token_url, '', $authVerifier);
$oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
$oauth->fetch($this->api_url);
$this->logger->warning($oauth->getLastResponse());
$taxis_userid = $this->xmlParse($oauth->getLastResponse(), 'messageText');
$currentTime = time();
$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('taxis_userid' => $taxis_userid));
$epalUser = reset($epalUsers);
$epalToken = md5(uniqid(mt_rand(), true));
if ($epalUser) {
$user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
if ($user) {
// $user->setPassword('harispass');
// $user->setUsername('harisp');
$user->setPassword($epalToken);
$user->setUsername($epalToken);
$user->save();
$epalUser->set('authtoken', $epalToken);
$epalUser->set('accesstoken', $accessToken['oauth_token']);
$epalUser->set('accesstoken_secret', $accessToken['oauth_token_secret']);
$epalUser->set('requesttoken',$this->requestToken);
$epalUser->set('requesttoken_secret', $this->requestTokenSecret);
$epalUser->set('timelogin', $currentTime);
$epalUser->set('userip', $request->getClientIp());
$epalUser->save();
$taxis_userid = null;
$trx = $this->connection->startTransaction();
try {
$oauth = new OAuth($this->consumer_key, $this->consumer_secret, OAUTH_SIG_METHOD_PLAINTEXT, OAUTH_AUTH_TYPE_URI);
$oauth->enableDebug();
$oauth->setToken($authToken, $this->requestTokenSecret);
$accessToken = $oauth->getAccessToken($this->access_token_url, '', $authVerifier);
$oauth->setToken($accessToken['oauth_token'], $accessToken['oauth_token_secret']);
$oauth->fetch($this->api_url);
$this->logger->warning($oauth->getLastResponse());
$taxis_userid = $this->xmlParse($oauth->getLastResponse(), 'messageText');
$currentTime = time();
$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('taxis_userid' => $taxis_userid));
$epalUser = reset($epalUsers);
$epalToken = md5(uniqid(mt_rand(), true));
if ($epalUser) {
$user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
if ($user) {
$user->setPassword($epalToken);
$user->setUsername($epalToken);
$user->save();
$epalUser->set('authtoken', $epalToken);
$epalUser->set('accesstoken', $accessToken['oauth_token']);
$epalUser->set('accesstoken_secret', $accessToken['oauth_token_secret']);
$epalUser->set('requesttoken',$this->requestToken);
$epalUser->set('requesttoken_secret', $this->requestTokenSecret);
$epalUser->set('timelogin', $currentTime);
$epalUser->set('userip', $request->getClientIp());
$epalUser->save();
}
}
}
if ($epalUser === null || !$epalUser) {
//Create a User
$user = User::create();
//Mandatory settings
$unique_id = uniqid('####');
$user->setPassword($epalToken);
$user->enforceIsNew();
$user->setEmail($unique_id);
$user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
$user->activate();
$user->set('init', $unique_id);
//Set Language
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$user->set('langcode', $language_interface->getId());
$user->set('preferred_langcode', $language_interface->getId());
$user->set('preferred_admin_langcode', $language_interface->getId());
//Adding default user role
$user->addRole('applicant');
$user->save();
$users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('mail' => $unique_id));
$user = reset($users);
if ($user) {
$this->logger->warning('userid 190='.$user->id().'*** name='.$user->name->value);
$epalUser = $this->entityTypeManager()->getStorage('epal_users')->create(array(
// 'langcode' => $language_interface->getId(),
'langcode' => 'el',
'user_id' => $user->id(),
'drupaluser_id' => $user->id(),
'taxis_userid' => $taxis_userid,
'taxis_taxid' => $unique_id,
'name' => $unique_id,
'surname' => $unique_id,
'fathername' => $unique_id,
'mothername' => $unique_id,
'accesstoken' => $accessToken['oauth_token'],
'accesstoken_secret' => $accessToken['oauth_token_secret'],
'authtoken' => $epalToken,
'requesttoken' => $this->requestToken,
'requesttoken_secret' => $this->requestTokenSecret,
'timelogin' => $currentTime,
'timeregistration' => $currentTime,
'timetokeninvalid' => 0,
'userip' => $request->getClientIp(),
'status' => 1
));
$epalUser->save();
} else {
return false;
}
if ($epalUser === null || !$epalUser) {
}
$this->oauthostSession->set('authtoken', $epalToken);
$this->oauthostSession->save();
// $this->oauthostSession->delete();
//Create a User
$user = User::create();
//Mandatory settings
$unique_id = uniqid('####');
$user->setPassword($epalToken);
$user->enforceIsNew();
$user->setEmail($unique_id);
$user->setUsername($epalToken); //This username must be unique and accept only a-Z,0-9, - _ @ .
$user->activate();
$user->set('init', $unique_id);
//Set Language
$language_interface = \Drupal::languageManager()->getCurrentLanguage();
$user->set('langcode', $language_interface->getId());
$user->set('preferred_langcode', $language_interface->getId());
$user->set('preferred_admin_langcode', $language_interface->getId());
//Adding default user role
$user->addRole('applicant');
$user->save();
$users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('mail' => $unique_id));
$user = reset($users);
if ($user) {
$this->logger->warning('userid 190='.$user->id().'*** name='.$user->name->value);
$epalUser = $this->entityTypeManager()->getStorage('epal_users')->create(array(
'langcode' => 'el',
'user_id' => $user->id(),
'drupaluser_id' => $user->id(),
'taxis_userid' => $taxis_userid,
'taxis_taxid' => $unique_id,
'name' => $unique_id,
'surname' => $unique_id,
'fathername' => $unique_id,
'mothername' => $unique_id,
'accesstoken' => $accessToken['oauth_token'],
'accesstoken_secret' => $accessToken['oauth_token_secret'],
'authtoken' => $epalToken,
'requesttoken' => $this->requestToken,
'requesttoken_secret' => $this->requestTokenSecret,
'timelogin' => $currentTime,
'timeregistration' => $currentTime,
'timetokeninvalid' => 0,
'userip' => $request->getClientIp(),
'status' => 1
));
$epalUser->save();
} else {
return false;
}
return $epalToken;
} catch (OAuthException $e) {
$this->logger->warning($e->getMessage());
$trx->rollback();
return false;
} catch (\Exception $ee) {
$this->logger->warning($ee->getMessage());
$trx->rollback();
return false;
}
}
$this->oauthostSession->set('authtoken', $epalToken);
$this->oauthostSession->save();
// $this->oauthostSession->delete();
return $epalToken;
} catch (OAuthException $e) {
$this->logger->warning($e->getMessage());
$trx->rollback();
return false;
} catch (\Exception $ee) {
$this->logger->warning($ee->getMessage());
$trx->rollback();
return false;
}
return false;
}
......
<?php
namespace Drupal\oauthost\Controller;
<?php namespace Drupal\oauthost\Controller;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
......@@ -16,11 +14,11 @@ use Symfony\Component\HttpFoundation\RedirectResponse;
class OAuthLogout extends ControllerBase
{
protected $entity_query;
protected $entityTypeManager;
protected $logger;
protected $connection;
protected $consumer_key = '';
protected $consumer_secret = '';
protected $request_token_url;
......@@ -33,10 +31,7 @@ class OAuthLogout extends ControllerBase
protected $redirect_url;
public function __construct(
EntityTypeManagerInterface $entityTypeManager,
QueryFactory $entity_query,
Connection $connection,
LoggerChannelFactoryInterface $loggerChannel)
EntityTypeManagerInterface $entityTypeManager, QueryFactory $entity_query, Connection $connection, LoggerChannelFactoryInterface $loggerChannel)
{
$this->entityTypeManager = $entityTypeManager;
$this->entity_query = $entity_query;
......@@ -47,17 +42,14 @@ class OAuthLogout extends ControllerBase
public static function create(ContainerInterface $container)
{
return new static(
$container->get('entity.manager'),
$container->get('entity.query'),
$container->get('database'),
$container->get('logger.factory')
);
$container->get('entity.manager'), $container->get('entity.query'), $container->get('database'), $container->get('logger.factory')
);
}
public function logoutGo(Request $request)
{
$trx = $this->connection->startTransaction();
try {
$user = null;
$username = $request->headers->get('PHP_AUTH_USER');
......@@ -67,85 +59,98 @@ class OAuthLogout extends ControllerBase
if ($this->oauthostSession) {
$configRowName = $this->oauthostSession->configrowname->value;
} else {
$trx->rollback();
$this->logger->warning("oauthostSession for [{$username}] not set");
$response = new Response();
$response->setContent('forbidden');
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$ostauthConfigs = $this->entityTypeManager->getStorage('oauthost_config')->loadByProperties(array('name' => $configRowName));
$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;
$this->redirect_url = $ostauthConfig->redirect_url->value;
} else {
$response = new Response();
$response->setContent('forbidden');
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('authtoken' => $username));
$epalUser = reset($epalUsers);
$foundUser = true;
if ($epalUser) {
$user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
if ($user) {
$res = \Drupal::httpClient()->get($this->logout_url . $username, array('headers' => array('Accept' => 'text/plain')));
/* $resData = (string) $res->getBody();
if (empty($resData)) {
return FALSE;
} */
// if ($res->getStatusCode() === "200")
$ostauthConfigs = $this->entityTypeManager->getStorage('oauthost_config')->loadByProperties(array('name' => $configRowName));
$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;
$this->redirect_url = $ostauthConfig->redirect_url->value;
} else {
$trx->rollback();
$this->logger->warning("ostauthConfig [{$configRowName}]not found");
$response = new Response();
$response->setContent('forbidden');
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
$user->setPassword(uniqid('pw'));
$user->save();
$epalUser->set('accesstoken', '-');
$epalUser->set('accesstoken_secret', '-');
$epalUser->set('authtoken','-');
$epalUser->set('requesttoken','-');
$epalUser->set('requesttoken_secret', '-');
$epalUser->save();
$epalUsers = $this->entityTypeManager
->getStorage('epal_users')
->loadByProperties(array('authtoken' => $username));
$epalUser = reset($epalUsers);
$foundUser = false;
if ($epalUser) {
$user = $this->entityTypeManager
->getStorage('user')
->load($epalUser->user_id->target_id);
$logout_token = $epalUser->getRequesttoken();
if ($user) {
$res = \Drupal::httpClient()->get($this->logout_url . $username, array('headers' => array('Accept' => 'text/plain')));
$user->setPassword(uniqid('pw'));
$user->save();
$epalUser->set('accesstoken', '-');
$epalUser->set('accesstoken_secret', '-');
$epalUser->set('authtoken', '-');
$epalUser->set('requesttoken', '-');
$epalUser->set('requesttoken_secret', '-');
$epalUser->save();
$foundUser = true;
}
}
if (!$foundUser) {
$trx->rollback();
$this->logger->warning("user not found");
$response = new Response();
$response->setContent('forbidden');
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
// logout from remote host
$logout_call_url = "{$this->logout_url}{$logout_token}";
if (($ch = curl_init()) !== false) {
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $logout_call_url);
$remote_logout_result = curl_exec($ch);
if ($remote_logout_result === false) {
// record failure
$this->logger->warning("OAUTH remote logout call to [{$logout_call_url}] fail: " . curl_error($ch));
}
curl_close($ch);
} else {
$foundUser = false;
$this->logger->warning("OAUTH remote logout to [{$logout_call_url}] not called");
}
} else {
$foundUser = false;
}
if (!$foundUser) {
$this->logger->warning("user not found");
session_unset();
session_destroy();
\Drupal::service('page_cache_kill_switch')->trigger();
$this->oauthostSession->delete();
$this->logger->info("OAUTH remote logout success for [{$username}]");
$response = new Response();
$response->setContent('forbidden');
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->setContent("{\"message\": \"Server logout successful\",\"next\": \"{$this->redirect_url}\"}");
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'application/json');
return $response;
}
session_unset();
session_destroy();
\Drupal::service('page_cache_kill_switch')->trigger();
$response = new Response();
$response->setContent('logout successful');
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'application/json');
$this->oauthostSession->delete();
return $response;
// return new RedirectResponse($this->redirect_url . '&auth_role=', 302, []);
return $response;
} catch (Exception $e) {
$this->logger->warning($e->getMessage());
$response = new Response();
......@@ -156,5 +161,4 @@ class OAuthLogout extends ControllerBase
return $response;
}
}
}
<?php
namespace Drupal\oauthost\Entity;
<?php namespace Drupal\oauthost\Entity;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Field\BaseFieldDefinition;
......@@ -55,374 +53,375 @@ use Drupal\user\UserInterface;
*/
class OAuthOSTConfig extends ContentEntityBase implements OAuthOSTConfigInterface
{
use EntityChangedTrait;
/**
* {@inheritdoc}
*/
public static function preCreate(EntityStorageInterface $storage_controller, array &$values)
{
parent::preCreate($storage_controller, $values);
$values += array(
'user_id' => \Drupal::currentUser()->id(),
);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->get('name')->value;
}
/**
* {@inheritdoc}
*/
public function setName($name)
{
$this->set('name', $name);
return $this;
}
/**
* {@inheritdoc}
*/
public function getCreatedTime()
{
return $this->get('created')->value;
}
/**
* {@inheritdoc}
*/
public function setCreatedTime($timestamp)
{
$this->set('created', $timestamp);
return $this;
}
/**
* {@inheritdoc}
*/
public function getOwner()
{
return $this->get('user_id')->entity;
}
/**
* {@inheritdoc}
*/
public function getOwnerId()
{
return $this->get('user_id')->target_id;
}
/**
* {@inheritdoc}
*/
public function setOwnerId($uid)
{
$this->set('user_id', $uid);
return $this;
}
/**
* {@inheritdoc}
*/
public function setOwner(UserInterface $account)
{
$this->set('user_id', $account->id());
return $this;
}
/**
* {@inheritdoc}
*/
public function isPublished()
{
return (bool) $this->getEntityKey('status');
}
/**
* {@inheritdoc}
*/
public function setPublished($published)
{
$this->set('status', $published ? true : false);
return $this;
}
/**
* {@inheritdoc}
*/
public static function baseFieldDefinitions(EntityTypeInterface $entity_type)
{
$fields = parent::baseFieldDefinitions($entity_type);
$fields['user_id'] = BaseFieldDefinition::create('entity_reference')
->setLabel(t('Authored by'))
->setDescription(t('The user ID of author of the OAuthOST Config entity.'))
->setRevisionable(true)
->setSetting('target_type', 'user')
->setSetting('handler', 'default')
->setTranslatable(true)
->setDisplayOptions('view', array(
'label' => 'hidden',
'type' => 'author',
'weight' => 0,
))
->setDisplayOptions('form', array(
'type' => 'entity_reference_autocomplete',
'weight' => 5,
'settings' => array(
'match_operator' => 'CONTAINS',
'size' => '60',
'autocomplete_type' => 'tags',
'placeholder' => '',
),
))
->setDisplayConfigurable('form', true)
->setDisplayConfigurable('view', true);
$fields['name'] = BaseFieldDefinition::create('string')
->setLabel(t('Name'))
->setDescription(t('The name of the OAuthOST Config entity.'))
->setSettings(array(
'max_length' => 50,
'text_processing' => 0,
))
->setDefaultValue('oauthost_taxisnet_config')
->setDisplayOptions('view', array(
'label' => 'above',
'type' => 'string',
'weight' => -4,
))
->setDisplayOptions('form', array(
'type' => 'string_textfield',
'weight' => -4,
))
->setDisplayConfigurable('form', true)
->setDisplayConfigurable('view', true);
$fields['consumer_key'] = BaseFieldDefinition::create('string')
->setLabel(t('Consumer Key'))
->setDescription(t('The Consumer Key'))
->setSettings(array(
'max_length' => 200,
'text_processing' => 0,
))
->setDefaultValue('')
->setDisplayOptions('view', array(
'label' => 'above',
'type' => 'string',
'weight' => -4,
))
->setDisplayOptions('form', array(
'type' => 'string_textfield',
'weight' => -4,
))
->setDisplayConfigurable('form', true)
->setDisplayConfigurable('view', true);
$fields['consumer_secret'] = BaseFieldDefinition::create('string')
/**
* {@inheritdoc}
*/
public static function preCreate(EntityStorageInterface $storage_controller, array &$values)
{
parent::preCreate($storage_controller, $values);
$values += array(
'user_id' => \Drupal::currentUser()->id(),
);
}
/**
* {@inheritdoc}
*/
public function getName()
{
return $this->get('name')->value;
}
/**
* {@inheritdoc}
*/