Merge branch 'login_procedure' into 'develop'

Login procedure

See merge request !18
parents 98cb60a0 bba5be41
...@@ -112,4 +112,4 @@ scripts: ...@@ -112,4 +112,4 @@ scripts:
scrollspy: true scrollspy: true
tab: true tab: true
tooltip: true tooltip: true
util: true util: true
\ No newline at end of file
...@@ -6,6 +6,7 @@ drupal/* ...@@ -6,6 +6,7 @@ drupal/*
drupal/modules/* drupal/modules/*
!drupal/modules/epal/ !drupal/modules/epal/
!drupal/modules/epalreadydata/ !drupal/modules/epalreadydata/
!drupal/modules/oauthost/
# Logs # Logs
*.log *.log
......
epal_is_logged_in:
path: '/epal/login/check'
defaults:
_controller: '\Drupal\epal\Controller\Login::helloWorld'
requirements:
_access: 'TRUE'
epal_auth_test:
path: 'epal/auth/test'
options:
_auth: [ 'oauthost' ]
defaults:
_controller: '\Drupal\epal\Controller\Login::helloWorld'
_title: 'Greeting'
requirements:
_permission: 'access content'
_user_is_logged_in: 'TRUE'
<?php
/**
* @file
* Contains \Drupal\query_example\Controller\QueryExampleController.
*/
namespace Drupal\epal\Controller;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Controller\ControllerBase;
/**
* Controller routines for page example routes.
*/
class Login extends ControllerBase {
protected $query_factory;
public function __construct(EntityTypeManagerInterface $entityTypeManager, QueryFactory $query_factory) {
// public function __construct(QueryFactory $query_factory) {
$this->entityTypeManager = $entityTypeManager;
$this->query_factory = $query_factory;
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager'),
$container->get('entity.query')
);
}
public function helloWorld() {
$name = \Drupal::request()->query->get('name');
$authToken = "no authToken";
$accessKey = "no accessKey";
if (\Drupal::request()->headers->has('X-AUTH-TOKEN')) {
$authToken = \Drupal::request()->headers->get( 'X-AUTH-TOKEN' );
}
if (\Drupal::request()->headers->has('X-ACCESS-KEY')) {
$accessKey = \Drupal::request()->headers->get( 'X-ACCESS-KEY' );
}
$response = new JsonResponse(['hello' => 'world', 'name' => $name, 'authToken' => $authToken, 'accessKey' => $accessKey]);
$response->headers->set('X-AUTH-TOKEN', 'HELLOTOKEN');
return $response;
}
protected function simpleQuery() {
$query = $this->query_factory->get('student_class');
// ->condition('status', 1);
$scids = $query->execute();
$studentClass_storage = $this->entityTypeManager->getStorage('student_class');
$studentClasses = $studentClass_storage->loadMultiple($scids);
$arrayToReturn = array();
foreach ($studentClasses as $studentClass) {
array_push($arrayToReturn,
array(
array('data' => $studentClass->get('name')->value, 'class' => 'not-editable'),
array('data' => "hello")
));
}
return array_values($arrayToReturn);
}
public function basicQuery() {
return [
'#title' => 'All student class ids',
'studentclasses' => array(
'#attributes' => ['id' => 'studentclasses', 'name' => 'studentclasses'],
'#theme' => 'table',
'#caption' => t('Student Classes'),
'#header' => array(t('Name'), t('Max No')),
'#rows' => $this->simpleQuery(),
),
'#attached' => [
'library' => [
'eepal/eepal-styles', //include our custom module library for this response
'eepal/data-tables' //include data tables libraries with this response
]
]
];
}
protected function intermediateQuery() {
$query = $this->query_factory->get('node')
->condition('status', 1)
->condition('changed', REQUEST_TIME, '<')
->condition('title', 'ipsum lorem', 'CONTAINS')
->condition('field_tags.entity.name', 'test');
$nids = $query->execute();
return array_values($nids);
}
public function conditionalQuery() {
return [
'#title' => 'Published Nodes Called "ipsum lorem" That Have a Tag "test"',
'content' => [
'#theme' => 'item_list',
'#items' => $this->intermediateQuery()
]
];
}
protected function advancedQuery() {
$query = $this->query_factory->get('node')
->condition('status', 1)
->condition('changed', REQUEST_TIME, '<');
$group = $query->orConditionGroup()
->condition('title', 'ipsum lorem', 'CONTAINS')
->condition('field_tags.entity.name', 'test');
$nids = $query->condition($group)->execute();
return array_values($nids);
}
public function conditionalGroupQuery() {
return [
'#title' => 'Published Nodes That Are Called "ipsum lorem" Or Have a Tag "test"',
'content' => [
'#theme' => 'item_list',
'#items' => $this->advancedQuery()
]
];
}
}
{
"name": "drupal/oauthost",
"type": "drupal-module",
"description": "Authentication Provider OST",
"keywords": ["Drupal"],
"license": "GPL-2.0+",
"homepage": "https://www.drupal.org/project/oauthost",
"minimum-stability": "dev",
"support": {
"issues": "https://www.drupal.org/project/issues/oauthost",
"source": "http://cgit.drupalcode.org/oauthost"
},
"require": { }
}
name: oauthost
type: module
description: Authentication Provider OST
core: 8.x
package: oauthost
<?php
/**
* @file
* Contains oauthost.module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function oauthost_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
// Main module help for the oauthost module.
case 'help.page.oauthost':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Authentication Provider OST') . '</p>';
return $output;
default:
}
}
/**
* Implements hook_theme().
*/
function oauthost_theme() {
return [
'oauthost' => [
'template' => 'oauthost',
'render element' => 'children',
],
];
}
oauthost.callback_log_in:
path: /oauth/cb
defaults:
_controller: '\Drupal\oauthost\Controller\CBController::loginCB'
requirements:
_permission: 'access content'
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
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://eepal.dev/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']);
if (($authToken == null || !$authToken) && !$_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']);
exit;
} else if ($_SESSION['state']==1) {
$oauth->setToken($authToken, $_SESSION['secret']);
$this->logger->warning("oauthToken=" . $authToken . "***" . $_SESSION['secret']);
$accessToken = $oauth->getAccessToken($this->access_token_url, '', $authVerifier);
$this->logger->warning("accessToken=" . $accessToken['oauth_token'] . "***" . $accessToken['oauth_token_secret']);
$_SESSION['state'] = 2;
$_SESSION['token'] = $accessToken['oauth_token'];
$_SESSION['secret'] = $accessToken['oauth_token_secret'];
// $_SESSION['token'] = serialize($access_token);
}
$this->logger->warning("about to call web service");
$oauth->setToken($_SESSION['token'],$_SESSION['secret']);
$oauth->fetch($this->api_url);
} 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 Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
class CBController extends ControllerBase {
protected $query_factory;
protected $entityTypeManager;
protected $request;
protected $logger;
public function __construct(EntityTypeManagerInterface $entityTypeManager, QueryFactory $query_factory) {
$this->entityTypeManager = $entityTypeManager;
$this->query_factory = $query_factory;
$this->request = \Drupal::request();
$this->logger = \Drupal::logger('oauthost');
}
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.manager'),
$container->get('entity.query')
);
}
public function loginCB() {
$authToken = $this->request->query->get('oauth_token');
$authVerifier = $this->request->query->get('oauth_verifier');
$this->logger->notice("authToken=".$authToken."***authVerifier=".$authVerifier);
/* $response = new JsonResponse(['hello' => 'world', 'name' => $name, 'authToken' => $authToken, 'accessKey' => $accessKey]);
$response->headers->set('X-AUTH-TOKEN', 'HELLOTOKEN'); */
return new RedirectResponse('/dist/#/?auth_token=' . $authToken . '&auth_role=student',302,[]);
}
}
<?php
namespace Drupal\oauthost\Tests;
use Drupal\Core\Url;
use Drupal\simpletest\WebTestBase;
/**
* Simple test to ensure that main page loads with module enabled.
*
* @group oauthost
*/
class LoadTest extends WebTestBase{
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['oauthost'];
/**
* A user with permission to administer site configuration.
*
* @var \Drupal\user\UserInterface
*/
protected $user;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->user = $this->drupalCreateUser(['administer site configuration']);
$this->drupalLogin($this->user);
}
/**
* Tests that the home page loads with a 200 response.
*/
public function testLoad() {
$this->drupalGet(Url::fromRoute('<front>'));
$this->assertResponse(200);
}
}
<!-- Add you custom twig html here -->
\ No newline at end of file
...@@ -5,7 +5,8 @@ import { SectorCoursesActions } from './sectorcourses.actions'; ...@@ -5,7 +5,8 @@ import { SectorCoursesActions } from './sectorcourses.actions';
import { StudentDataFieldsActions } from './studentdatafields.actions'; import { StudentDataFieldsActions } from './studentdatafields.actions';
import { EpalClassesActions } from './epalclass.actions'; import { EpalClassesActions } from './epalclass.actions';
import { AmkaFillsActions} from './amkafill.actions'; import { AmkaFillsActions} from './amkafill.actions';
const ACTION_PROVIDERS = [ CourseFieldsActions, SectorFieldsActions, RegionSchoolsActions, SectorCoursesActions, StudentDataFieldsActions, EpalClassesActions, AmkaFillsActions ]; import { LoginInfoActions} from './logininfo.actions';
const ACTION_PROVIDERS = [ CourseFieldsActions, SectorFieldsActions, RegionSchoolsActions, SectorCoursesActions, StudentDataFieldsActions, EpalClassesActions, AmkaFillsActions, LoginInfoActions ];
export { export {
CourseFieldsActions, CourseFieldsActions,
...@@ -15,5 +16,6 @@ export { ...@@ -15,5 +16,6 @@ export {
StudentDataFieldsActions, StudentDataFieldsActions,
EpalClassesActions, EpalClassesActions,
AmkaFillsActions, AmkaFillsActions,
LoginInfoActions,
ACTION_PROVIDERS, ACTION_PROVIDERS,
}; };
import { LOGININFO_SAVE } from '../constants';
import { Injectable } from '@angular/core';
import { NgRedux } from 'ng2-redux';
import { IAppState } from '../store';
import { HelperDataService } from '../services/helper-data-service';
@Injectable()
export class LoginInfoActions {
constructor(
private _ngRedux: NgRedux<IAppState>,
private _hds: HelperDataService) {}
saveLoginInfo = (loginInfo) => {
return this._ngRedux.dispatch({
type: LOGININFO_SAVE,
payload: {
loginInfo
}
});
};
}
export class AppSettings { export class AppSettings {
public static get API_ENDPOINT(): string { public static get API_ENDPOINT(): string {
return 'http://localhost/angular/eepal-front/drupal'; // return 'http://localhost/drupal';
// return 'http://localhost/drupal-8.2.5'; return 'http://eepal.dev/drupal';
// return 'http://eepal.dev/drupal';
// return 'http://eduslim2.minedu.gov.gr/drupal'; // return 'http://eduslim2.minedu.gov.gr/drupal';