code review-fixes, WIP:parent form

parent 73207377
epal_is_logged_in: user_data:
path: '/epal/login/check' path: '/epal/userdata'
defaults:
_controller: '\Drupal\epal\Controller\Login::helloWorld'
requirements:
_access: 'TRUE'
epal_entityapi_test:
path: '/epal/entityapi/test'
options: options:
_auth: [ 'basic_auth' ] _auth: [ 'basic_auth' ]
requirements:
_user_is_logged_in: 'TRUE'
defaults:
_controller: '\Drupal\epal\Controller\Login::testQuery'
epal_auth_test:
path: 'epal/auth/test'
options:
_auth: [ 'oauthost' ]
defaults: defaults:
_controller: '\Drupal\epal\Controller\Login::helloWorld' _controller: '\Drupal\epal\Controller\CurrentUser::getEpalUserData'
_title: 'Greeting'
requirements: requirements:
_permission: 'access content'
_user_is_logged_in: 'TRUE' _user_is_logged_in: 'TRUE'
current_user: current_user:
path: '/epal/curuser' path: '/epal/curuser'
options: options:
_auth: [ 'basic_auth' ] _auth: [ 'basic_auth' ]
defaults: defaults:
_controller: '\Drupal\epal\Controller\CurrentUser::content' _controller: '\Drupal\epal\Controller\CurrentUser::getLoginInfo'
requirements: requirements:
_user_is_logged_in: 'TRUE' _user_is_logged_in: 'TRUE'
epal.application_submit: epal.application_submit:
......
services:
logger.channel.oauth:
parent: 'logger.channel_base'
arguments: ['oauthost']
...@@ -2,59 +2,84 @@ ...@@ -2,59 +2,84 @@
namespace Drupal\epal\Controller; namespace Drupal\epal\Controller;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityTypeManagerInterface; use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Controller\ControllerBase; use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityFieldManagerInterface;
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
class CurrentUser extends ControllerBase
{
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entityTypeManager)
{
$this->entityTypeManager = $entityTypeManager;
}
public static function create(ContainerInterface $container)
{
return new static(
$container->get('entity_type.manager')
);
}
class CurrentUser extends ControllerBase { public function getLoginInfo(Request $request)
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entityTypeManager )
{ {
$this->entityTypeManager1 = $entityTypeManager; $authToken = $request->headers->get('PHP_AUTH_USER');
$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('authtoken' => $authToken));
$epalUser = reset($epalUsers);
if ($epalUser) {
return $this->respondWithStatus([
'name' => $epalUser->name->value,
], Response::HTTP_OK);
} else {
return $this->respondWithStatus([
'message' => t("EPAL user not found"),
], Response::HTTP_FORBIDDEN);
}
} }
public function getEpalUserData(Request $request)
{
$authToken = $request->headers->get('PHP_AUTH_USER');
public static function create(ContainerInterface $container) { $epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('authtoken' => $authToken));
return new static( $epalUser = reset($epalUsers);
$container->get('entity_type.manager'), if ($epalUser) {
$container->get('entity.query'), $user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
$container->get('entity_field.manager') if ($user) {
); $userName = $epalUser->name->value;
} $userSurname = $epalUser->surname->value;
$userFathername = $epalUser->fathername->value;
$userMothername = $epalUser->mothername->value;
$userEmail = $user->mail->value;
return $this->respondWithStatus([
'userName' => mb_substr($epalUser->name->value,0,4,'UTF-8') !== "####" ? $epalUser->name->value : '',
'userSurname' => mb_substr($epalUser->surname->value,0,4,'UTF-8') !== "####" ? $epalUser->surname->value : '',
'userFathername' => mb_substr($epalUser->fathername->value,0,4,'UTF-8') !== "####" ? $epalUser->fathername->value : '',
'userMothername' => mb_substr($epalUser->mothername->value,0,4,'UTF-8') !== "####" ? $epalUser->mothername->value : '',
'userEmail' => mb_substr($user->mail->value,0,4,'UTF-8') !== "####" ? $user->mail->value : '',
], Response::HTTP_OK);
} else {
return $this->respondWithStatus([
'message' => t("user not found"),
], Response::HTTP_INTERNAL_SERVER_ERROR);
}
} else {
public function content(Request $request) { return $this->respondWithStatus([
'message' => t("EPAL user not found"),
$authToken = $request->headers->get('PHP_AUTH_USER'); ], Response::HTTP_FORBIDDEN);
}
}
$epalUsers = $this->entityTypeManager1->getStorage('epal_users')->loadByProperties(array('authtoken' => $authToken));
$epalUser = reset($epalUsers);
if ($epalUser) private function respondWithStatus($arr, $s) {
{ $res = new JsonResponse($arr);
$currentUserName = $epalUser->name->value; $res->setStatusCode($s);
return $res;
$response = new JsonResponse(['name' =>$currentUserName]); }
}
else {
$response = new Response();
$response->setContent('forbidden');
$response->setStatusCode(Response::HTTP_FORBIDDEN);
$response->headers->set('Content-Type', 'application/json');
}
return $response;
}
} }
<?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;
use Drupal\Core\Entity\EntityFieldManagerInterface;
/**
* Controller routines for page example routes.
*/
class Login extends ControllerBase {
protected $query_factory;
protected $entityTypeManager;
protected $entityFieldManager;
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_type.manager'),
$container->get('entity.query'),
$container->get('entity_field.manager')
);
}
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 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 [
'#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()
]
];
}
}
services: services:
logger.channel.oauth: logger.channel.oauth:
parent: 'logger.channel_base' parent: 'logger.channel_base'
arguments: ['oauthost'] arguments: ['epal']
...@@ -53,7 +53,7 @@ class CBController extends ControllerBase ...@@ -53,7 +53,7 @@ class CBController extends ControllerBase
public static function create(ContainerInterface $container) public static function create(ContainerInterface $container)
{ {
return new static( return new static(
$container->get('entity.manager'), $container->get('entity_type.manager'),
$container->get('entity.query'), $container->get('entity.query'),
$container->get('database'), $container->get('database'),
$container->get('logger.factory') $container->get('logger.factory')
...@@ -157,7 +157,7 @@ class CBController extends ControllerBase ...@@ -157,7 +157,7 @@ class CBController extends ControllerBase
//Create a User //Create a User
$user = User::create(); $user = User::create();
//Mandatory settings //Mandatory settings
$unique_id = uniqid('id'); $unique_id = uniqid('####');
$user->setPassword($epalToken); $user->setPassword($epalToken);
$user->enforceIsNew(); $user->enforceIsNew();
$user->setEmail($unique_id); $user->setEmail($unique_id);
......
import { AMKAFILL_SAVE } from '../constants';
import { Injectable } from '@angular/core';
import { NgRedux } from 'ng2-redux';
import { IAppState } from '../store';
@Injectable()
export class AmkaFillsActions {
constructor(
private _ngRedux: NgRedux<IAppState>) {}
saveAmkaFills = (amkaFills) => {
return this._ngRedux.dispatch({
type: AMKAFILL_SAVE,
payload: {
amkaFills
}
});
};
}
\ No newline at end of file
...@@ -4,13 +4,11 @@ import { RegionSchoolsActions } from './regionschools.actions'; ...@@ -4,13 +4,11 @@ import { RegionSchoolsActions } from './regionschools.actions';
import { SectorCoursesActions } from './sectorcourses.actions'; 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 { LoginInfoActions} from './logininfo.actions'; import { LoginInfoActions} from './logininfo.actions';
import { CriteriaActions} from './criteria.actions'; import { CriteriaActions} from './criteria.actions';
const ACTION_PROVIDERS = [ CourseFieldsActions, SectorFieldsActions, RegionSchoolsActions, SectorCoursesActions, StudentDataFieldsActions, const ACTION_PROVIDERS = [ CourseFieldsActions, SectorFieldsActions, RegionSchoolsActions, SectorCoursesActions, StudentDataFieldsActions,
EpalClassesActions, AmkaFillsActions, LoginInfoActions, CriteriaActions]; EpalClassesActions, LoginInfoActions, CriteriaActions];
export { export {
CourseFieldsActions, CourseFieldsActions,
...@@ -19,9 +17,8 @@ export { ...@@ -19,9 +17,8 @@ export {
SectorCoursesActions, SectorCoursesActions,
StudentDataFieldsActions, StudentDataFieldsActions,
EpalClassesActions, EpalClassesActions,
AmkaFillsActions,
LoginInfoActions, LoginInfoActions,
CriteriaActions, CriteriaActions,
ACTION_PROVIDERS, ACTION_PROVIDERS,
}; };
...@@ -26,28 +26,17 @@ import { APP_ROUTER_PROVIDERS, APP_DECLARATIONS } from './app.routes'; ...@@ -26,28 +26,17 @@ import { APP_ROUTER_PROVIDERS, APP_DECLARATIONS } from './app.routes';
/* Here we import services */ /* Here we import services */
import {HelperDataService} from './services/helper-data-service'; import {HelperDataService} from './services/helper-data-service';
//import {UserDataService} from './services/user-data-service';
import {AmkaCheckService} from './services/amkacheck-service';
import {LoaderService} from './services/Spinner.service'; import {LoaderService} from './services/Spinner.service';
//import {UserDataService} from './services/user-data-service';
import { ACTION_PROVIDERS } from './actions'; import { ACTION_PROVIDERS } from './actions';
import Home from './components/home'; import Home from './components/home';
import { Ng2SmartTableModule } from 'ng2-smart-table'; import { Ng2SmartTableModule } from 'ng2-smart-table';
import HeaderComponent from './components/header/header.component'; import HeaderComponent from './components/header/header.component';
import NavbarComponent from './components/navbar/navbar.component'; import NavbarComponent from './components/navbar/navbar.component';
import MainComponent from './components/main/main.component'; import MainComponent from './components/main/main.component';
import FooterComponent from './components/footer/footer.component'; import FooterComponent from './components/footer/footer.component';
class MyLocalization extends NgLocalization { class MyLocalization extends NgLocalization {
getPluralCategory(value: any) { getPluralCategory(value: any) {
if (value < 5) { if (value < 5) {
...@@ -81,10 +70,7 @@ class MyLocalization extends NgLocalization { ...@@ -81,10 +70,7 @@ class MyLocalization extends NgLocalization {
ACTION_PROVIDERS, ACTION_PROVIDERS,
//Service1, again services here //Service1, again services here
HelperDataService, HelperDataService,
AmkaCheckService,
LoaderService, LoaderService,
] ]
}) })
class AppModule {} class AppModule {}
......
import {Component} from '@angular/core';
import { Http, Response, RequestOptions, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import { Student } from '../students/student';
import {
FormControl,
FormGroup
} from '@angular/forms';
import {AppSettings} from '../../app.settings';
@Component({
selector: 'form3',
template: `
<div>
<form #studentform="ngForm" (submit)="onSubmit(studentform)" class="col-sm-8">
<div class="form-group">
<label>Όνομα</label>
<input type="text" [(ngModel)]="student.name" name="name"
required class="form-control" />
</div>
<div class="form-group">
<label>Επώνυμο</label>
<input type="text" [(ngModel)]="student.studentsurname" name="studentsurname"
required class="form-control" />
</div>
<!--
<div class="form-group">
<label>Διεύθυνση</label>
<input type="text" [(ngModel)]="student.address" name="address"
required class="form-control" />
</div>
<div class="form-group">
<label>Ημερομηνία Γέννησης</label>
<input type="date" [(ngModel)]="student.birthdate"
class="form-control" name="birthdate" />
</div>
-->
<input type="submit" [disabled]="!studentform.valid" value="Υποβολή" class="btn btn-success" />
</form>
</div>
`
})
export default class Form3 {
public student;
constructor(private http: Http) {
this.student = new Student(1, '', '', '', '', '','','','','');
//this.student = new Student(1, 1, '', '');
}
onSubmit(studentform: any) {
let headers = new Headers({
//"Authorization": "Basic cmVzdHVzZXI6czNjckV0MFAwdWwwJA==", // encoded user:pass
"Authorization": "Basic bmthdHNhb3Vub3M6emVtcmFpbWU=",
"Accept": "*/*",
"Access-Control-Allow-Credentials": "true",
"Content-Type": "application/json",
// "Content-Type": "text/plain", // try to skip preflight
//"X-CSRF-Token": "hVtACDJjFRSyE4bgGJENHbXY0B9yNhF71Fw-cYHSDNY"
//"X-CSRF-Token": "fj1QtF_Z_p6kE19EdCnN08zoSjVfcT4Up-ciW6I0IG8"
"X-CSRF-Token": "LU92FaWYfImfZxfldkF5eVnssdHoV7Aa9fg8K1bWYUc"
});
let options = new RequestOptions({ headers: headers, withCredentials: true });
console.log(this.student);
this.http.post(`${AppSettings.API_ENDPOINT}/entity/epal_student`, this.student, options)
// this.http.post('http://eduslim2.minedu.gov.gr/drupal/entity/epal_student', this.student, options)
// Call map on the response observable to get the parsed people object
.map((res: Response) => res.json())
.subscribe(success => {alert("Η εγγραφή έγινε με επιτυχία"); console.log("success post")}, // put the data returned from the server in our variable
error => console.log("Error HTTP POST Service"), // in case of failure show this message
() => console.log("write this message anyway"));//run this code in all cases);
}
}
...@@ -19,18 +19,7 @@ import { API_ENDPOINT } from '../app.settings'; ...@@ -19,18 +19,7 @@ import { API_ENDPOINT } from '../app.settings';
template: ` template: `
<div> <div>
<form [formGroup]="formGroup" method = "POST" action="{{apiEndPoint}}/oauth/login" #form> <form [formGroup]="formGroup" method = "POST" action="{{apiEndPoint}}/oauth/login" #form>
<!-- <input type="hidden" name="X-oauth-enabled" value="true"> -->
<div *ngFor="let loginInfoToken$ of loginInfo$ | async; let i=index"></div> <div *ngFor="let loginInfoToken$ of loginInfo$ | async; let i=index"></div>
<!-- <div class="row">
<div class="col-md-6">
{{loginInfoToken$.auth_token}}
</div>
<div class="col-md-6">
{{loginInfoToken$.auth_role}}
</div>
</div>
</div> -->
<div class="row" style="min-height: 300px; margin-top: 100px;"> <div class="row" style="min-height: 300px; margin-top: 100px;">
<div *ngIf="!authToken" class="col-md-8 offset-md-4"> <div *ngIf="!authToken" class="col-md-8 offset-md-4">
...@@ -39,21 +28,6 @@ import { API_ENDPOINT } from '../app.settings'; ...@@ -39,21 +28,6 @@ import { API_ENDPOINT } from '../app.settings';
</button> </button>
</div> </div>
</div> </div>
<!--
<div class="row">
<div *ngIf="authToken" class="col-md-7 col-md-offset-5">
<h3>Καλώς ήρθατε</h3>
</div>
</div>
<div class="row">
<div *ngIf="authToken" class="col-md-7 col-md-offset-5">
<input type="hidden" name="dologout" value="true">
<button type="submit" class="btn-primary btn-lg pull-center" (click)="form.submit()">
Αποσύνδεση<span class="glyphicon glyphicon-menu-right"></span>
</button>
</div>
</div>
-->
</form> </form>
</div> </div>
` `
...@@ -63,8 +37,8 @@ export default class Home implements OnInit { ...@@ -63,8 +37,8 @@ export default class Home implements OnInit {
public formGroup: FormGroup; public formGroup: FormGroup;
private authToken: string; private authToken: string;
private authRole: string; private authRole: string;
private name :any; private name: any;
private xcsrftoken :any; private xcsrftoken: any;
private loginInfo$: Observable<ILoginInfo>; private loginInfo$: Observable<ILoginInfo>;
private apiEndPoint = API_ENDPOINT; private apiEndPoint = API_ENDPOINT;
...@@ -72,48 +46,43 @@ export default class Home implements OnInit { ...@@ -72,48 +46,43 @@ export default class Home implements OnInit {
private _ata: LoginInfoActions, private _ata: LoginInfoActions,
private _ngRedux: NgRedux<IAppState>, private _ngRedux: NgRedux<IAppState>,
private activatedRoute: ActivatedRoute, private activatedRoute: ActivatedRoute,
private _hds: HelperDataService, private _hds: HelperDataService,
private router: Router private router: Router
) { ) {
this.authToken = ''; this.authToken = '';
this.authRole = ''; this.authRole = '';
this.name =''; this.name = '';
this.formGroup = this.fb.group({ this.formGroup = this.fb.group({
// Username: [],
// Paswd: []
}); });
}; };
ngOnInit() { ngOnInit() {
this.loginInfo$ = this._ngRedux.select(state => { this.loginInfo$ = this._ngRedux.select(state => {
if (state.loginInfo.size > 0) { if (state.loginInfo.size > 0) {
state.loginInfo.reduce(({}, loginInfoToken) => { state.loginInfo.reduce(({}, loginInfoToken) => {
this.authToken = loginInfoToken.auth_token; this.authToken = loginInfoToken.auth_token;
this.authRole = loginInfoToken.auth_role; this.authRole = loginInfoToken.auth_role;