First draft of oauthost module. It works for tests. The auth token and role...

First draft of oauthost module. It works for tests. The auth token and role are saved in Redux store
parent c77beea9
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\OSTAuthenticationProvider
arguments: ['@config.factory', '@entity_type.manager']
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']
......@@ -5,20 +5,28 @@ 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 \OAuthProvider;
use \OAuthException;
use OAuth;
use OAuthException;
/**
* Class OSTAuthenticationProvider.
*
* @package Drupal\oauthost\Authentication\Provider
*/
class OSTAuthenticationProvider implements AuthenticationProviderInterface {
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.
......@@ -59,82 +67,82 @@ class OSTAuthenticationProvider implements AuthenticationProviderInterface {
* Constructor.
*
* @param \Drupal\user\UserDataInterface
* The user data service.
* The user data service
* @param \Psr\Log\LoggerInterface $logger
* The logger service for OAuth.
* 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.
* The config factory
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* The entity type manager service
*/
public function __construct(ConfigFactoryInterface $config_factory, EntityTypeManagerInterface $entity_type_manager) {
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.
* The request object
*
* @return bool
* TRUE if authentication credentials suitable for this provider are on the
* request, FALSE otherwise.
* request, FALSE otherwise
*/
public function applies(Request $request) {
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");
return getHeader($request, 'OAuthEnabled');
// 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) {
/* private function checkAuthToken($authToken)
{
if (!$authToken) {
return TRUE;
}
else if ($authToken === 'bourboutsala') {
return FALSE;
}
else {
return TRUE;
}
}
private function getLoginToken($request) {
$loginToken = $request->headers->get('X-Login-Token');
if (isset($loginToken) && $loginToken !== "") {
return TRUE;
}
else {
return FALSE;
}
return false;
} elseif ($authToken === 'testAuthToken') {
return $authToken;
} else {
return false;
}
} */
private function getHeader($request, $headerName) {
private function getHeader($request, $headerName)
{
$headerValue = $request->headers->get($headerName);
if (isset($headerValue) && $headerValue !== "") {
if (isset($headerValue) && $headerValue !== '') {
return $headerValue;
}
else {
return FALSE;
} else {
return false;
}
}
......@@ -158,56 +166,69 @@ class OSTAuthenticationProvider implements AuthenticationProviderInterface {
}
} */
public function authenticate(Request $request) {
/* $code = filter_input(INPUT_GET, 'code');
if (empty($code) || !$this->client) {
return new RedirectResponse('/');
}
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 {
$this->client->authenticate($code);
}
catch (\Exception $e) {
return new RedirectResponse('/');
}
$plus = new Google_Service_Oauth2($this->client);
$userinfo = $plus->userinfo->get();
$user_email = $userinfo['email']; */
drupal_set_message("hello");
$user_email = 'haris.rnd@gmail.com';
$user = user_load_by_mail($user_email);
/* if (!$user) {
$user_name = $userinfo['name'];
$user_picture = $userinfo['picture'];
try {
$user = User::create([
'name' => $user_name,
'mail' => $user_email,
'status' => 1,
'picture' => $user_picture,
]);
// hook_google_oauth_create_user_alter($user, $userinfo);
\Drupal::moduleHandler()->alter('google_oauth_create_user', $user, $userinfo);
$user->save();
}
catch (\Exception $e) {
return new RedirectResponse('/');
}
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;
} */
user_login_finalize($user);
// return new RedirectResponse('http://example.com');
return($user);
// return $this->redirect('<front>');
}
// return null;
}
/**
* {@inheritdoc}
*/
public function cleanup(Request $request) {}
public function cleanup(Request $request)
{
}
/**
/*
* {@inheritdoc}
*/
/* public function handleException(GetResponseForExceptionEvent $event) {
......@@ -220,6 +241,4 @@ class OSTAuthenticationProvider implements AuthenticationProviderInterface {
}
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,[]);
}
}
......@@ -5,7 +5,8 @@ import { SectorCoursesActions } from './sectorcourses.actions';
import { StudentDataFieldsActions } from './studentdatafields.actions';
import { EpalClassesActions } from './epalclass.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 {
CourseFieldsActions,
......@@ -15,5 +16,6 @@ export {
StudentDataFieldsActions,
EpalClassesActions,
AmkaFillsActions,
LoginInfoActions,
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
}
});
};
}
import {Component} from '@angular/core';
import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, Component} from '@angular/core';
import { LoginInfoActions } from '../actions/logininfo.actions';
import {
FormBuilder,
FormGroup,
FormControl,
FormArray
} from '@angular/forms';
import { AppSettings } from '../app.settings';
@Component({
selector: 'home',
template: `
<div>
<h4>Στοιχεία Σύνδεσης</h4>
<form [formGroup]="formGroup">
<div class="form-group">
<label for="UserName">Όνομα Χρήστη</label><input class="form-control" type="text" formControlName="Username">
</div>
<div class="form-group">
<label for="Paswd">Κωδικός Ασφαλείας</label><input class="form-control" type="password" formControlName="Paswd">
</div>
<form [formGroup]="formGroup" method = "POST" action="http://eepal.dev/drupal/oauth/login" #form>
<input type="hidden" name="X-oauth-enabled" value="true">
<div class="row">
<div class="col-md-2 col-md-offset-5">
<button type="button" class="btn-primary btn-lg pull-center" (click)="checkvalidation()">
Συνέχεια<span class="glyphicon glyphicon-menu-right"></span>
<button type="submit" class="btn-primary btn-lg pull-center" (click)="form.submit()">
Είσοδος μέσω TaxisNet<span class="glyphicon glyphicon-menu-right"></span>
</button>
</div>
<div *ngIf="emptyselection==true">
Παρακαλώ συμπληρώστε το ΑΜΚΑ του μαθητή
</div>
</div>
</form>
</div>
`
})
export default class Home {
export default class Home implements OnInit{
public formGroup: FormGroup;
constructor(private fb: FormBuilder) {
constructor(private fb: FormBuilder,
private _ata: LoginInfoActions,
private activatedRoute: ActivatedRoute) {
this.formGroup = this.fb.group({
Username: [],
Paswd : []
});
};
ngOnInit() {
// subscribe to router event
this.activatedRoute.queryParams.subscribe((params: Params) => {
let authToken = params['auth_token'];
let authRole = params['auth_role'];
this._ata.saveLoginInfo({auth_token: authToken, auth_role: authRole});
console.log(authToken);
});
}
checkvalidation() {
......
......@@ -16,6 +16,8 @@ export const STUDENTDATAFIELDS_SAVE = 'STUDENTDATAFIELDS_SAVE';
export const EPALCLASSES_SAVE = 'EPALCLASSES_SAVE';
export const AMKAFILL_SAVE = 'AMKAFILL_SAVE';
export const LOGININFO_SAVE = 'LOGININFO_SAVE';
//export const VALID_NAMES_PATTERN = '[Α-ΩΆΈΉΊΎΌΏα-ωάέήίύόώ ]*$';
export const VALID_NAMES_PATTERN = '[A-Za-zΑ-ΩΆΈΉΊΎΌΏα-ωάέήίύόώ ]*$';
export const VALID_ADDRESS_PATTERN = '[0-9A-Za-zΑ-ΩΆΈΉΊΎΌΏα-ωάέήίύόώ ]*$';
......
......@@ -24,6 +24,7 @@ export class HelperDataService {
//"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
//"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
"X-CSRF-Token": "LU92FaWYfImfZxfldkF5eVnssdHoV7Aa9fg8K1bWYUc",
"X-oauth-enabled": "true",
"X-Auth-Token": "bourboutsala"
});
let options = new RequestOptions({ headers: headers });
......@@ -65,7 +66,8 @@ export class HelperDataService {
//"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
//"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
"X-CSRF-Token": "LU92FaWYfImfZxfldkF5eVnssdHoV7Aa9fg8K1bWYUc",
"X-Auth-Token": "bourboutsal"
"X-oauth-enabled": "true",
"X-Auth-Token": "bourboutsala"
});
let options = new RequestOptions({ headers: headers });
return new Promise((resolve, reject) => {
......
......@@ -7,6 +7,7 @@ import { IRegions, IRegion, IRegionSchool } from './regionschools/regionschools.
import { ISectors, ISector, ISectorCourse } from './sectorcourses/sectorcourses.types';
import { IStudentDataField, IStudentDataFields } from './studentdatafields/studentdatafields.types';
import { IEpalClass, IEpalClasses } from './epalclasses/epalclasses.types';
import { ILoginInfoToken, ILoginInfo } from './logininfo/logininfo.types';
export {
IAppState,
......@@ -25,6 +26,7 @@ export {
IStudentDataFields,
IEpalClass,
IEpalClasses,
ILoginInfo,
};
......
import { ILoginInfoToken, ILoginInfo } from './logininfo.types';
import { loginInfoReducer } from './logininfo.reducer';
import { deimmutifyLoginInfo } from './logininfo.transformers';
export {
ILoginInfoToken,
ILoginInfo,
loginInfoReducer,
deimmutifyLoginInfo,
};
import { List } from 'immutable';
import { ILoginInfoToken } from './logininfo.types';
// export const INITIAL_STATE = List<ICourseField>([new CourseFieldRecord({})]);
export const INITIAL_STATE = List<ILoginInfoToken>();
import { ILoginInfo, ILoginInfoToken } from './logininfo.types';
import { INITIAL_STATE } from './logininfo.initial-state';
import { Seq } from 'immutable';
import {
LOGININFO_SAVE
} from '../../constants';
export function loginInfoReducer(state: ILoginInfo = INITIAL_STATE, action): ILoginInfo {
switch (action.type) {
case LOGININFO_SAVE:
let loginInfoTokens = Array<ILoginInfoToken>();
let ind=0;
state.forEach(loginInfoToken => {
loginInfoTokens.push(<ILoginInfoToken>{auth_token: action.payload.loginInfo.auth_token, auth_role: action.payload.loginInfo.auth_role});
ind++;
});
return Seq(loginInfoTokens).map(n => n).toList();
default: return state;
}
};
import { ILoginInfo, ILoginInfoToken } from './logininfo.types';
export function deimmutifyLoginInfo(state: ILoginInfo): ILoginInfoToken[] {
let fetchedLoginInfoTokens = new Array();
state.forEach(loginInfoToken => {
fetchedLoginInfoTokens.push(<ILoginInfoToken>{auth_token: loginInfoToken.auth_token, auth_role: loginInfoToken.auth_role});
});
return fetchedLoginInfoTokens;
};
import { List } from 'immutable';
export interface ILoginInfoToken {
auth_token: string;
auth_role: string;
}
export type ILoginInfo = List<ILoginInfoToken>;
......@@ -6,6 +6,7 @@ import * as sectors from './sectorcourses';
import * as studentDataFields from './studentdatafields';
import * as epalclasses from './epalclasses';
import * as amkafills from './amkafill';
import * as loginInfo from './logininfo';
/*
* This is where we 'assemble' the full store out of its modules.
......@@ -19,6 +20,7 @@ export interface IAppState {
studentDataFields?: studentDataFields.IStudentDataFields;
epalclasses?: epalclasses.IEpalClasses;
amkafills?: amkafills.IAmkaFills;
loginInfo?: loginInfo.ILoginInfo;
};
export const rootReducer = combineReducers<IAppState>({
......@@ -29,6 +31,7 @@ export const rootReducer = combineReducers<IAppState>({
studentDataFields: studentDataFields.studentDataFieldsReducer,
epalclasses: epalclasses.epalclassesReducer,
amkafills: amkafills.amkafillReducer,
loginInfo: loginInfo.loginInfoReducer,
});
export function deimmutify(state: IAppState): Object {
......@@ -40,5 +43,6 @@ export function deimmutify(state: IAppState): Object {
studentdataFields: studentDataFields.deimmutifyStudentDataFields(state.studentDataFields),
epalclasses: epalclasses.deimmutifyEpalClasses(state.epalclasses),
amkafills: amkafills.deimmutifyAmkaFills(state.amkafills),
loginInfo: loginInfo.deimmutifyLoginInfo(state.loginInfo),
};
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment