Merge branch 'fix-cas-anauth-role' into 'develop'

Fix cas auth; Fix ministry login; Fix errorCode bh

See merge request !121
parents 3c04d310 74ab7f23
......@@ -12,3 +12,9 @@ casost.log_out_go:
_controller: '\Drupal\casost\Controller\CASLogout::logoutGo'
requirements:
_user_is_logged_in: 'TRUE'
casost.log_out_cas_go:
path: /cas/logoutcas
defaults:
_controller: '\Drupal\casost\Controller\CASLogout::logoutCasGo'
requirements:
_access: 'TRUE'
......@@ -10,6 +10,7 @@ use Drupal\user\Entity\User;
use Drupal\Core\Database\Connection;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Logger\LoggerChannelFactoryInterface;
use phpCAS;
......@@ -38,11 +39,12 @@ class CASLogout extends ControllerBase
protected $connection;
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;
$this->connection = $connection;
......@@ -56,14 +58,13 @@ class CASLogout extends ControllerBase
$container->get('entity.query'),
$container->get('database'),
$container->get('logger.factory')
);
);
}
public function logoutGo(Request $request)
{
$configRowName = 'casost_sch_sso_config';
try {
$configRowId = $request->query->get('config');
if ($configRowId) {
$configRowName = $configRowName.'_'.$configRowId;
......@@ -116,10 +117,15 @@ class CASLogout extends ControllerBase
$user->setPassword(uniqid('pw'));
$user->save();
$response = new Response();
$response->setContent("{\"message\": \"Server logout successful\",\"next\": \"{$this->logoutRedirectUrl}\"}");
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'application/json');
// $response = new Response();
// $response->setContent("{\"message\": \"Server logout successful\",\"next\": \"{$this->logoutRedirectUrl}\"}");
// $response->setStatusCode(Response::HTTP_OK);
// $response->headers->set('Content-Type', 'application/json');
$response = (new JsonResponse([
"message" => "Server logout successful",
"next" => "{$this->logoutRedirectUrl}"
]))->setStatusCode(Response::HTTP_OK);
session_unset();
session_destroy();
......@@ -136,7 +142,57 @@ class CASLogout extends ControllerBase
}
}
private function redirectForbidden($configRowName, $errorCode) {
public function logoutCasGo(Request $request)
{
$configRowName = 'casost_sch_sso_config';
try {
$configRowId = $request->query->get('config');
if ($configRowId) {
$configRowName = $configRowName.'_'.$configRowId;
}
$CASOSTConfigs = $this->entityTypeManager->getStorage('casost_config')->loadByProperties(array('name' => $configRowName));
$CASOSTConfig = reset($CASOSTConfigs);
if ($CASOSTConfig) {
$this->serverVersion = $CASOSTConfig->serverversion->value;
$this->serverHostname = $CASOSTConfig->serverhostname->value;
$this->serverPort = $CASOSTConfig->serverport->value;
$this->serverUri = $CASOSTConfig->serveruri->value === null ? '' : $CASOSTConfig->serveruri->value;
$this->redirectUrl = $CASOSTConfig->redirecturl->value;
$this->changeSessionId = $CASOSTConfig->changesessionid->value;
$this->logoutRedirectUrl = $CASOSTConfig->logoutredirecturl->value;
$this->CASServerCACert = $CASOSTConfig->casservercacert->value;
$this->CASServerCNValidate = $CASOSTConfig->casservercnvalidate->value;
$this->noCASServerValidation = $CASOSTConfig->nocasservervalidation->value;
$this->proxy = $CASOSTConfig->proxy->value;
$this->handleLogoutRequests = $CASOSTConfig->handlelogoutrequests->value;
$this->CASLang = $CASOSTConfig->caslang->value;
$this->allowed1 = $CASOSTConfig->allowed1->value;
$this->allowed1Value = $CASOSTConfig->allowed1value->value;
$this->allowed2 = $CASOSTConfig->allowed2->value;
$this->allowed2Value = $CASOSTConfig->allowed2value->value;
} else {
return $this->redirectForbidden($configRowName, '7001');
}
$response = new Response();
$response->setContent("{\"message\": \"Server logout continue\",\"next\": \"{$this->logoutRedirectUrl}\"}");
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'application/json');
session_unset();
session_destroy();
\Drupal::service('page_cache_kill_switch')->trigger();
session_start();
return $response;
} catch (\Exception $e) {
$this->logger->warning($e->getMessage());
return $this->redirectForbidden($configRowName, '8000');
}
}
private function redirectForbidden($configRowName, $errorCode)
{
session_unset();
session_destroy();
\Drupal::service('page_cache_kill_switch')->trigger();
......@@ -146,4 +202,4 @@ class CASLogout extends ControllerBase
return new RedirectResponseWithCookieExt($this->redirectUrl .'&error_code=' . $errorCode, 302, []);
}
}
}
\ No newline at end of file
}
......@@ -21,19 +21,18 @@ class MinistryLogin extends ControllerBase
//protected $connection;
public function __construct(
EntityTypeManagerInterface $entityTypeManager,
//QueryFactory $entity_query,
// $connection,
LoggerChannelFactoryInterface $loggerChannel)
{
EntityTypeManagerInterface $entityTypeManager,
//QueryFactory $entity_query,
// $connection,
LoggerChannelFactoryInterface $loggerChannel
) {
$this->entityTypeManager = $entityTypeManager;
//$this->entity_query = $entity_query;
//$this->connection = $connection;
$this->logger = $loggerChannel->get('epal');
}
public static function create(ContainerInterface $container)
{
return new static(
......@@ -41,142 +40,127 @@ class MinistryLogin extends ControllerBase
//$container->get('entity.query'),
//$container->get('database'),
$container->get('logger.factory')
);
);
}
public function loginGo(Request $request)
{
try {
if (!$request->isMethod('POST')) {
return $this->respondWithStatus([
"message" => t("Method Not Allowed")
], Response::HTTP_METHOD_NOT_ALLOWED);
}
try {
if (!$request->isMethod('POST')) {
return $this->respondWithStatus([
"message" => t("Method Not Allowed")
], Response::HTTP_METHOD_NOT_ALLOWED);
}
//user validation
//Note: $authToken = $postData->username
$authToken = $request->headers->get('PHP_AUTH_USER');
$users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
$user = reset($users);
if (!$user) {
return $this->respondWithStatus([
//user validation
//Note: $authToken = $postData->username
$authToken = $request->headers->get('PHP_AUTH_USER');
$users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
$user = reset($users);
if (!$user) {
return $this->respondWithStatus([
'message' => t("User not found"),
], Response::HTTP_FORBIDDEN);
}
}
//user role validation
//$user = \Drupal\user\Entity\User::load($user->id());
$roles = $user->getRoles();
$validRole = false;
foreach ($roles as $role)
if ($role === "ministry") {
$validRole = true;
break;
}
if (!$validRole) {
return $this->respondWithStatus([
//user role validation
//$user = \Drupal\user\Entity\User::load($user->id());
$roles = $user->getRoles();
$validRole = false;
foreach ($roles as $role) {
if ($role === "ministry") {
$validRole = true;
break;
}
}
if (!$validRole) {
return $this->respondWithStatus([
'message' => t("User Invalid Role"),
], Response::HTTP_FORBIDDEN);
}
$currentRoleName = "supervisor";
}
$currentRoleName = "supervisor";
$postData = null;
if ($content = $request->getContent()) {
$postData = json_decode($content);
//return new RedirectResponse("/drupal-8.2.6/eepal/dist/" . '?auth_token=' . $postData->username .'&auth_role=supervisor', 302, []);
return $this->respondWithStatus([
$postData = null;
if ($content = $request->getContent()) {
$postData = json_decode($content);
//return new RedirectResponse("/drupal-8.2.6/eepal/dist/" . '?auth_token=' . $postData->username .'&auth_role=supervisor', 302, []);
return $this->respondWithStatus([
//'auth_token' => $postData->username,
//'userpassword' => $postData->userpassword,
//'auth_role' => $currentRoleName,
], Response::HTTP_OK);
}
else {
return $this->respondWithStatus([
'message' => t("post with no data"),
], Response::HTTP_BAD_REQUEST);
}
], Response::HTTP_OK);
} else {
return $this->respondWithStatus([
'message' => t("post with no data"),
], Response::HTTP_BAD_REQUEST);
}
} //end try
catch (\Exception $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;
return $this->respondWithStatus([
'message' => 'forbidden',
], Response::HTTP_FORBIDDEN);
}
}
public function logoutGo(Request $request)
{
try {
if (!$request->isMethod('POST')) {
return $this->respondWithStatus([
"message" => t("Method Not Allowed")
try {
if (!$request->isMethod('POST')) {
return $this->respondWithStatus([
"message" => t("Method Not Allowed")
], Response::HTTP_METHOD_NOT_ALLOWED);
}
//user validation
//Note: $authToken = $postData->username
$authToken = $request->headers->get('PHP_AUTH_USER');
$users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
$user = reset($users);
if (!$user) {
return $this->respondWithStatus([
}
//user validation
//Note: $authToken = $postData->username
$authToken = $request->headers->get('PHP_AUTH_USER');
$users = $this->entityTypeManager->getStorage('user')->loadByProperties(array('name' => $authToken));
$user = reset($users);
if (!$user) {
return $this->respondWithStatus([
'message' => t("User not found"),
], Response::HTTP_FORBIDDEN);
}
//user role validation
//$user = \Drupal\user\Entity\User::load($user->id());
/*
$roles = $user->getRoles();
$validRole = false;
foreach ($roles as $role)
}
//user role validation
//$user = \Drupal\user\Entity\User::load($user->id());
/*
$roles = $user->getRoles();
$validRole = false;
foreach ($roles as $role)
if ($role === "ministry") {
$validRole = true;
break;
}
if (!$validRole) {
if (!$validRole) {
return $this->respondWithStatus([
'message' => t("User Invalid Role"),
], Response::HTTP_FORBIDDEN);
}
*/
session_unset();
session_destroy();
}
*/
$response = new Response();
$response->setContent('logout successful');
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'application/json');
return $response;
session_unset();
session_destroy();
return $this->respondWithStatus([
'message' => 'logout successful',
], Response::HTTP_OK);
} //end try
catch (\Exception $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;
return $this->respondWithStatus([
'message' => t("forbidden"),
], Response::HTTP_FORBIDDEN);
}
}
private function respondWithStatus($arr, $s) {
$res = new JsonResponse($arr);
$res->setStatusCode($s);
return $res;
private function respondWithStatus($arr, $s)
{
return (new JsonResponse($arr))
->setStatusCode($s);
}
}
......@@ -145,10 +145,10 @@ class OAuthLogout extends ControllerBase
$this->oauthostSession->delete();
$this->logger->info("OAUTH remote logout success for [{$username}]");
$response = new Response();
$response->setContent("{\"message\": \"Server logout successful\",\"next\": \"{$this->redirect_url}\"}");
$response->setStatusCode(Response::HTTP_OK);
$response->headers->set('Content-Type', 'application/json');
$response = (new JsonResponse([
"message" => "Server logout successful",
"next" => "{$this->redirect_url}"
]))->setStatusCode(Response::HTTP_OK);
return $response;
} catch (Exception $e) {
......
import {Router, ActivatedRoute, Params} from '@angular/router';
import {OnInit, OnDestroy, Component} from '@angular/core';
import { LoginInfoActions } from '../actions/logininfo.actions';
import { ILoginInfo } from '../store/logininfo/logininfo.types';
import { LOGININFO_INITIAL_STATE } from '../store/logininfo/logininfo.initial-state';
import { NgRedux, select } from 'ng2-redux';
import { BehaviorSubject, Subscription } from 'rxjs/Rx';
import { IAppState } from '../store/store';
import { HelperDataService } from '../services/helper-data-service';
import { CookieService } from 'ngx-cookie';
import {
FormBuilder,
FormGroup,
FormControl,
FormArray
} from '@angular/forms';
import { Router, ActivatedRoute, Params } from "@angular/router";
import { OnInit, OnDestroy, Component } from "@angular/core";
import { LoginInfoActions } from "../actions/logininfo.actions";
import { ILoginInfo } from "../store/logininfo/logininfo.types";
import { LOGININFO_INITIAL_STATE } from "../store/logininfo/logininfo.initial-state";
import { NgRedux, select } from "ng2-redux";
import { BehaviorSubject, Subscription } from "rxjs/Rx";
import { IAppState } from "../store/store";
import { HelperDataService } from "../services/helper-data-service";
import { CookieService } from "ngx-cookie";
import { FormBuilder, FormGroup, FormControl, FormArray } from "@angular/forms";
import { API_ENDPOINT, API_ENDPOINT_PARAMS } from "../app.settings";
import { API_ENDPOINT, API_ENDPOINT_PARAMS } from '../app.settings';
@Component({
selector: 'school-home',
selector: "school-home",
template: `
<div>
<form [formGroup]="formGroup" method = "POST" action="{{apiEndPoint}}/cas/login{{apiEndPointParams}}" #form>
<!-- <input type="hidden" name="X-oauth-enabled" value="true"> -->
<div *ngFor="let loginInfoToken$ of loginInfo$ | async; let i=index"></div>
<div class="row" style="min-height: 300px; margin-top: 100px;">
<div *ngIf="!authToken" class="col-md-8 offset-md-4">
<button type="submit" class="btn-primary btn-lg" (click)="form.submit()">
Είσοδος μέσω Π.Σ.Δ<span class="glyphicon glyphicon-menu-right"></span>
</button>
<div style="min-height: 300px; margin-top: 100px;">
<div *ngIf="(errorCode$ | async) != ''">
<div [ngSwitch]="errorCode$ | async">
<p class="text-danger" *ngSwitchCase="5001">Προέκυψε σφάλμα κατά την διαδικασία αυθεντικοποίησης σας.</p>
<p class="text-danger" *ngSwitchCase="5002">Πρέπει να συνδεθείτε με λογαριασμό του Πανελλήνιου Σχολικού Δικτύου, για να χρησιμοποιήσετε την εφαρμογή.</p>
<p class="text-danger" *ngSwitchCase="5003">Πρέπει να συνδεθείτε με τον επίσημο λογαριασμό μονάδας στο Πανελλήνιο Σχολικό Δίκτυο, για να χρησιμοποιήσετε την εφαρμογή.</p>
<p class="text-danger" *ngSwitchCase="5004">Ο ρόλος που αντιστοιχεί στον λογαριασμό σας στο Πανελλήνιο Σχολικό Δίκτυο δεν επιτρέπεται να χρησιμοποιήσετε την εφαρμογή.</p>
<p class="text-danger" *ngSwitchCase="5005">Προέκυψε σφάλμα κατά την διαδικασία αυθεντικοποίησης σας.</p>
<p class="text-danger" *ngSwitchCase="6000">Προέκυψε σφάλμα κατά την διαδικασία αυθεντικοποίησης σας. <br/>Παρακαλώ συνδεθείτε χρησιμοποιώντας τα στοιχεία του επίσημου λογαριασμού που διαθέτει η μονάδα στο Πανελλήνιο Σχολικό Δίκτυο.</p>
<p class="text-danger" *ngSwitchDefault>Προέκυψε σφάλμα {{ errorCode$ | async }}</p>
</div>
<div class="alert alert-danger" role="alert">Για να επαναλάβετε τη διαδικασία σύνδεσης πρέπει πρώτα να αποσυνδεθείτε.</div>
<div class="row">
<div class="col-sm-4">&nbsp;</div>
<div class="col-sm-4">
<button type="submit" class="btn btn-lg btn-block isclickable" (click)="casSignOut()">Αποσύνδεση</button>
</div>
</div>
</div>
<div *ngIf="(errorCode$ | async) == ''">
<form [formGroup]="formGroup" method = "POST" action="{{apiEndPoint}}/cas/login{{apiEndPointParams}}" #form>
<!-- <input type="hidden" name="X-oauth-enabled" value="true"> -->
<div *ngFor="let loginInfoToken$ of loginInfo$ | async; let i=index"></div>
<div class="row">
<div *ngIf="!authToken" class="col-md-8 offset-md-4">
<button type="submit" class="btn-primary btn-lg" (click)="form.submit()">
Είσοδος μέσω Π.Σ.Δ<span class="glyphicon glyphicon-menu-right"></span>
</button>
</div>
</div>
</form>
</div>
`
</form>
</div>
</div>
`
})
export default class SchoolHome implements OnInit, OnDestroy {
public formGroup: FormGroup;
private authToken: string;
private errorCode$: BehaviorSubject<string>;
private authRole: string;
private name: any;
private xcsrftoken: any;
......@@ -54,12 +68,13 @@ export default class SchoolHome implements OnInit, OnDestroy {
private activatedRoute: ActivatedRoute,
private _hds: HelperDataService,
private router: Router,
private _cookieService:CookieService
private _cookieService: CookieService
) {
this.authToken = '';
this.authRole = '';
this.name = '';
this.authToken = "";
this.authRole = "";
this.name = "";
this.loginInfo$ = new BehaviorSubject(LOGININFO_INITIAL_STATE);
this.errorCode$ = new BehaviorSubject('');
this.formGroup = this.fb.group({
});
};
......@@ -68,31 +83,23 @@ export default class SchoolHome implements OnInit, OnDestroy {
if (this.loginInfoSub)
this.loginInfoSub.unsubscribe();
this.loginInfo$.unsubscribe();
this.errorCode$.unsubscribe();
};
ngOnInit() {
/* this.authToken = this.getCookie('auth_token');
this.authRole = this.getCookie('auth_role');
if (this.authToken && this.authRole) {
this._ata.getloginInfo({ auth_token: this.authToken, auth_role: this.authRole });
this.removeCookie('auth_token');
this.removeCookie('auth_role');
} */
this.loginInfoSub = this._ngRedux.select(state => {
if (state.loginInfo.size > 0) {
state.loginInfo.reduce(({}, loginInfoToken) => {
state.loginInfo.reduce(({ }, loginInfoToken) => {
this.authToken = loginInfoToken.auth_token;
this.authRole = loginInfoToken.auth_role;
if (this.authToken && this.authToken.length > 0) {
if (this.authRole === 'director') {
this.router.navigate(['/school/director-buttons']);
if (this.authRole === "director") {
this.router.navigate(["/school/director-buttons"]);
}
else if (this.authRole === 'pde')
this.router.navigate(['/school/perfecture-view']);
else if (this.authRole === 'dide')
this.router.navigate(['/school/eduadmin-view']);
else if (this.authRole === "pde")
this.router.navigate(["/school/perfecture-view"]);
else if (this.authRole === "dide")
this.router.navigate(["/school/eduadmin-view"]);
}
return loginInfoToken;
}, {});
......@@ -101,29 +108,43 @@ export default class SchoolHome implements OnInit, OnDestroy {
return state.loginInfo;
}).subscribe(this.loginInfo$);
// subscribe to router event
this.activatedRoute.queryParams.subscribe((params: Params) => {
if (params) {
this.authToken = params['auth_token'];
this.authRole = params['auth_role'];
this.authToken = params["auth_token"];
this.authRole = params["auth_role"];
this.errorCode$.next((params["error_code"] === undefined) ? "" : params["error_code"]);
}
if (this.authToken && this.authRole)
if (this.authToken && this.authRole && this.errorCode$.getValue() == "") {
this._ata.getloginInfo({ auth_token: this.authToken, auth_role: this.authRole });
}
});
}
getCookie(key: string){
getCookie(key: string) {
return this._cookieService.get(key);
}
removeCookie(key: string){
removeCookie(key: string) {
return this._cookieService.remove(key);
}
checkvalidation() {
}
/**
* Logout from CAS only helper
*/
casSignOut() {
this._hds.casSignOut().then(data => {
this._ata.initLoginInfo();
// this.router.navigate(['/school']);
this.authToken = '';
this.authRole = '';
window.location.assign((<any>data).next);
}).catch(err => {
console.log(err)
});
}
}
This diff is collapsed.
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