code review-fixes, WIP:parent form

parent 73207377
epal_is_logged_in:
path: '/epal/login/check'
defaults:
_controller: '\Drupal\epal\Controller\Login::helloWorld'
requirements:
_access: 'TRUE'
epal_entityapi_test:
path: '/epal/entityapi/test'
user_data:
path: '/epal/userdata'
options:
_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:
_controller: '\Drupal\epal\Controller\Login::helloWorld'
_title: 'Greeting'
_controller: '\Drupal\epal\Controller\CurrentUser::getEpalUserData'
requirements:
_permission: 'access content'
_user_is_logged_in: 'TRUE'
current_user:
path: '/epal/curuser'
options:
_auth: [ 'basic_auth' ]
defaults:
_controller: '\Drupal\epal\Controller\CurrentUser::content'
_controller: '\Drupal\epal\Controller\CurrentUser::getLoginInfo'
requirements:
_user_is_logged_in: 'TRUE'
epal.application_submit:
......
services:
logger.channel.oauth:
parent: 'logger.channel_base'
arguments: ['oauthost']
......@@ -2,59 +2,84 @@
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;
use Symfony\Component\HttpFoundation\Request;
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 {
protected $entityTypeManager;
public function __construct(EntityTypeManagerInterface $entityTypeManager )
public function getLoginInfo(Request $request)
{
$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) {
return new static(
$container->get('entity_type.manager'),
$container->get('entity.query'),
$container->get('entity_field.manager')
);
}
$epalUsers = $this->entityTypeManager->getStorage('epal_users')->loadByProperties(array('authtoken' => $authToken));
$epalUser = reset($epalUsers);
if ($epalUser) {
$user = $this->entityTypeManager->getStorage('user')->load($epalUser->user_id->target_id);
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);
}
public function content(Request $request) {
$authToken = $request->headers->get('PHP_AUTH_USER');
$epalUsers = $this->entityTypeManager1->getStorage('epal_users')->loadByProperties(array('authtoken' => $authToken));
$epalUser = reset($epalUsers);
if ($epalUser)
{
$currentUserName = $epalUser->name->value;
$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;
}
} else {
return $this->respondWithStatus([
'message' => t("EPAL user not found"),
], Response::HTTP_FORBIDDEN);
}
}
private function respondWithStatus($arr, $s) {
$res = new JsonResponse($arr);
$res->setStatusCode($s);
return $res;
}
}
<?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:
logger.channel.oauth:
parent: 'logger.channel_base'
arguments: ['oauthost']
arguments: ['epal']
......@@ -53,7 +53,7 @@ class CBController extends ControllerBase
public static function create(ContainerInterface $container)
{
return new static(
$container->get('entity.manager'),
$container->get('entity_type.manager'),
$container->get('entity.query'),
$container->get('database'),
$container->get('logger.factory')
......@@ -157,7 +157,7 @@ class CBController extends ControllerBase
//Create a User
$user = User::create();
//Mandatory settings
$unique_id = uniqid('id');
$unique_id = uniqid('####');
$user->setPassword($epalToken);
$user->enforceIsNew();
$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';
import { SectorCoursesActions } from './sectorcourses.actions';
import { StudentDataFieldsActions } from './studentdatafields.actions';
import { EpalClassesActions } from './epalclass.actions';
import { AmkaFillsActions} from './amkafill.actions';
import { LoginInfoActions} from './logininfo.actions';
import { CriteriaActions} from './criteria.actions';
const ACTION_PROVIDERS = [ CourseFieldsActions, SectorFieldsActions, RegionSchoolsActions, SectorCoursesActions, StudentDataFieldsActions,
EpalClassesActions, AmkaFillsActions, LoginInfoActions, CriteriaActions];
EpalClassesActions, LoginInfoActions, CriteriaActions];
export {
CourseFieldsActions,
......@@ -19,9 +17,8 @@ export {
SectorCoursesActions,
StudentDataFieldsActions,
EpalClassesActions,
AmkaFillsActions,
LoginInfoActions,
CriteriaActions,
ACTION_PROVIDERS,
};
......@@ -26,28 +26,17 @@ import { APP_ROUTER_PROVIDERS, APP_DECLARATIONS } from './app.routes';
/* Here we import services */
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 {UserDataService} from './services/user-data-service';
import { ACTION_PROVIDERS } from './actions';
import Home from './components/home';
import { Ng2SmartTableModule } from 'ng2-smart-table';
import HeaderComponent from './components/header/header.component';
import NavbarComponent from './components/navbar/navbar.component';
import MainComponent from './components/main/main.component';
import FooterComponent from './components/footer/footer.component';
class MyLocalization extends NgLocalization {
getPluralCategory(value: any) {
if (value < 5) {
......@@ -81,10 +70,7 @@ class MyLocalization extends NgLocalization {
ACTION_PROVIDERS,
//Service1, again services here
HelperDataService,
AmkaCheckService,
LoaderService,
]
})
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';
template: `
<div>
<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 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 *ngIf="!authToken" class="col-md-8 offset-md-4">
......@@ -39,21 +28,6 @@ import { API_ENDPOINT } from '../app.settings';
</button>
</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>
</div>
`
......@@ -63,8 +37,8 @@ export default class Home implements OnInit {
public formGroup: FormGroup;
private authToken: string;
private authRole: string;
private name :any;
private xcsrftoken :any;
private name: any;
private xcsrftoken: any;
private loginInfo$: Observable<ILoginInfo>;
private apiEndPoint = API_ENDPOINT;
......@@ -72,48 +46,43 @@ export default class Home implements OnInit {
private _ata: LoginInfoActions,
private _ngRedux: NgRedux<IAppState>,
private activatedRoute: ActivatedRoute,
private _hds: HelperDataService,
private _hds: HelperDataService,
private router: Router
) {
this.authToken = '';
this.authRole = '';
this.name ='';
) {
this.authToken = '';
this.authRole = '';
this.name = '';
this.formGroup = this.fb.group({
// Username: [],
// Paswd: []
});
};
ngOnInit() {
this.loginInfo$ = this._ngRedux.select(state => {
this.loginInfo$ = this._ngRedux.select(state => {
if (state.loginInfo.size > 0) {
state.loginInfo.reduce(({}, loginInfoToken) => {
this.authToken = loginInfoToken.auth_token;
this.authRole = loginInfoToken.auth_role;
if (this.authToken && this.authToken.length > 0)
this.router.navigate(['/epal-class-select']);
if (this.authToken && this.authToken.length > 0)
this.router.navigate(['/parent-form']);
return loginInfoToken;
}, {});
}
return state.loginInfo;
});
// subscribe to router event
this.activatedRoute.queryParams.subscribe((params: Params) => {
if (params) {
this.authToken = params['auth_token'];
this.authRole = params['auth_role'];
}
if (this.authToken && this.authRole)
this._ata.getloginInfo({ auth_token: this.authToken, auth_role: this.authRole});
this._ata.getloginInfo({ auth_token: this.authToken, auth_role: this.authRole });
});
}
checkvalidation() {
}
......
......@@ -22,10 +22,6 @@ import { LoginInfoActions } from '../../actions/logininfo.actions';
private loginInfo$: Observable<ILoginInfo>;
public cuser :any;
constructor( private _ata: LoginInfoActions,
private _hds: HelperDataService,
private _ngRedux: NgRedux<IAppState>,
......@@ -50,7 +46,7 @@ import { LoginInfoActions } from '../../actions/logininfo.actions';
return state.loginInfo;
});
}
oauthSignOut() {
......@@ -62,5 +58,4 @@ import { LoginInfoActions } from '../../actions/logininfo.actions';
});
}
}
import {Component} from '@angular/core';
import {GlobalEventsManager} from "../../services/login-service";
@Component({
selector: 'reg-navbar',
templateUrl: 'navbar.component.html',
})
export default class NavbarComponent {
showNavBar: boolean = false;
constructor(private globalEventsManager: GlobalEventsManager) {
this.globalEventsManager.showNavBarEmitter.subscribe((mode)=>{
if (mode !== null) {
this.showNavBar = mode;
}
});
}
}
>>>>>>> 830874b9f9533be54e9e43e3c3229884b3eeb119
import { Component, OnInit } from '@angular/core';