last changes

This commit is contained in:
Dario Rekowski on RockPI 2019-11-11 07:16:43 +00:00
parent fed853f348
commit 0f5fb4575b
11 changed files with 285 additions and 142 deletions

View File

@ -16,7 +16,10 @@ namespace App\Controller;
use Cake\Controller\Controller; use Cake\Controller\Controller;
//use Cake\Event\Event; //use Cake\Event\Event;
use Cake\Http\Client;
use Cake\Routing\Router;
use Cake\ORM\TableRegistry; use Cake\ORM\TableRegistry;
use Cake\Core\Configure;
/** /**
* Application Controller * Application Controller
@ -83,19 +86,128 @@ class AppController extends Controller
$state_user_id = $session->read('StateUser.id'); $state_user_id = $session->read('StateUser.id');
if($state_user_id) { if($state_user_id) {
$stateBalancesTable = TableRegistry::getTableLocator()->get('stateBalances'); $stateBalancesTable = TableRegistry::getTableLocator()->get('stateBalances');
$stateBalanceEntry = $stateBalancesTable $stateBalanceQuery = $stateBalancesTable
->find('all') ->find('all')
->select('amount') ->select('amount')
->contain(false) ->contain(false)
->where(['state_user_id' => $state_user_id]); ->where(['state_user_id' => $state_user_id]);
if($stateBalanceEntry->count() == 1) { if($stateBalanceQuery->count() == 1) {
//var_dump($stateBalanceEntry->first()); //var_dump($stateBalanceEntry->first());
$session->write('StateUser.balance', $stateBalanceEntry->first()->amount); $session->write('StateUser.balance', $stateBalanceQuery->first()->amount);
//echo "stateUser.balance: " . $session->read('StateUser.balance'); //echo "stateUser.balance: " . $session->read('StateUser.balance');
} }
} }
// load error count
if($state_user_id) {
$stateErrorsTable = TableRegistry::getTableLocator()->get('stateErrors');
$stateErrorQuery = $stateErrorsTable
->find('all')
->select('id')
->contain(false)
->where(['state_user_id' => $state_user_id]);
$session->write('StateUser.errorCount', $stateErrorQuery->count());
}
//echo "initialize"; //echo "initialize";
} }
protected function requestLogin()
{
$session = $this->getRequest()->getSession();
// check login
// disable encryption for cookies
//$this->Cookie->configKey('User', 'encryption', false);
$session_id = intval($this->request->getCookie('GRADIDO_LOGIN', ''));
$ip = $this->request->clientIp();
if(!$session->check('client_ip')) {
$session->write('client_ip', $ip);
}
// login server cannot detect host ip
// TODO: update login server, recognize nginx real ip header
if($session_id != 0) {
$userStored = $session->read('StateUser');
$transactionPendings = $session->read('Transactions.pending');
if($session->read('session_id') != $session_id ||
( $userStored && !isset($userStored['id'])) ||
intval($transactionPendings) > 0) {
$http = new Client();
try {
$loginServer = Configure::read('LoginServer');
$url = $loginServer['host'] . ':' . $loginServer['port'];
$response = $http->get($url . '/login', ['session_id' => $session_id]);
$json = $response->getJson();
if(isset($json) && count($json) > 0) {
if($json['state'] === 'success' && intval($json['user']['email_checked']) === 1) {
//echo "email checked: " . $json['user']['email_checked'] . "; <br>";
$session->destroy();
foreach($json['user'] as $key => $value) {
$session->write('StateUser.' . $key, $value );
}
$transactionPendings = $json['Transaction.pending'];
//echo "read transaction pending: $transactionPendings<br>";
$session->write('Transactions.pending', $transactionPendings);
$session->write('session_id', $session_id);
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
if($json['user']['public_hex'] != '') {
$public_key_bin = hex2bin($json['user']['public_hex']);
$stateUserQuery = $stateUserTable
->find('all')
->where(['public_key' => $public_key_bin])
->contain(['StateBalances']);
if($stateUserQuery->count() == 1) {
$stateUser = $stateUserQuery->first();
if($stateUser->first_name != $json['user']['first_name'] ||
$stateUser->last_name != $json['user']['last_name']) {
$stateUser->first_name = $json['user']['first_name'];
$stateUser->last_name = $json['user']['last_name'];
if(!$stateUserTable->save($stateUser)) {
$this->Flash->error(__('error updating state user ' . json_encode($stateUser->errors())));
}
}
//var_dump($stateUser);
if(count($stateUser->state_balances) > 0) {
$session->write('StateUser.balance', $stateUser->state_balances[0]->amount);
}
$session->write('StateUser.id', $stateUser->id);
//echo $stateUser['id'];
} else {
$newStateUser = $stateUserTable->newEntity();
$newStateUser->public_key = $public_key_bin;
$newStateUser->first_name = $json['user']['first_name'];
$newStateUser->last_name = $json['user']['last_name'];
if(!$stateUserTable->save($newStateUser)) {
$this->Flash->error(__('error saving state user ' . json_encode($newStateUser->errors())));
}
$session->write('StateUser.id', $newStateUser->id);
//echo $newStateUser->id;
}
}
} else {
if($json['state'] === 'not found' ) {
$this->Flash->error(__('invalid session'));
return $this->redirect(Router::url('/', true) . 'account/', 303);
}
}
}
} catch(\Exception $e) {
$msg = $e->getMessage();
$this->Flash->error(__('error http request: ') . $msg);
return $this->redirect(['controller' => 'Dashboard', 'action' => 'errorHttpRequest']);
//continue;
}
}
} else {
// no login
return $this->redirect(Router::url('/', true) . 'account/', 303);
}
return true;
}
/* /*
public function beforeFilter(Event $event) public function beforeFilter(Event $event)
{ {
@ -103,6 +215,12 @@ class AppController extends Controller
} }
*/ */
public function returnJsonEncoded($json) {
$this->autoRender = false;
$response = $this->response->withType('application/json');
return $response->withStringBody($json);
}
public function returnJson($array) { public function returnJson($array) {
$this->autoRender = false; $this->autoRender = false;
$response = $this->response->withType('application/json'); $response = $this->response->withType('application/json');

View File

@ -12,7 +12,7 @@ use Cake\Controller\Component;
class GradidoNumberComponent extends Component class GradidoNumberComponent extends Component
{ {
// input can be from 0,01 or 0.01 up to big number be anything // input can be from 0,01 or 0.01 up to big number be anything
static public function parseInputNumberToCentNumber($inputNumber) public function parseInputNumberToCentNumber($inputNumber)
{ {
//$filteredInputNumber = preg_replace('/,/', '.', $inputNumber); //$filteredInputNumber = preg_replace('/,/', '.', $inputNumber);
$parts = preg_split('/(,|\.)/', (string)$inputNumber); $parts = preg_split('/(,|\.)/', (string)$inputNumber);
@ -25,7 +25,7 @@ class GradidoNumberComponent extends Component
return $result; return $result;
} }
static public function centToPrint($centAmount) public function centToPrint($centAmount)
{ {
} }

View File

@ -2,10 +2,8 @@
namespace App\Controller; namespace App\Controller;
use App\Controller\AppController; use App\Controller\AppController;
use Cake\Http\Client;
use Cake\Routing\Router; use Cake\Routing\Router;
use Cake\ORM\TableRegistry; use Cake\ORM\TableRegistry;
use Cake\Core\Configure;
/** /**
* StateUsers Controller * StateUsers Controller
@ -33,124 +31,18 @@ class DashboardController extends AppController
$startTime = microtime(true); $startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend'); $this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession(); $session = $this->getRequest()->getSession();
// check login
// disable encryption for cookies
//$this->Cookie->configKey('User', 'encryption', false); //return $this->redirect(Router::url('/', true) . 'account/', 303);
//$this->Cookie->read('GRADIDO_LOGIN'); $result = $this->requestLogin();
$session_id = intval($this->request->getCookie('GRADIDO_LOGIN', '')); if($result !== true) {
$ip = $this->request->clientIp(); return $result;
if(!$session->check('client_ip')) {
$session->write('client_ip', $ip);
} }
$user = $session->read('StateUser');
// login server cannot detect host ip $this->set('user', $user);
//echo "client ip: $ip<br>"; $this->set('timeUsed', microtime(true) - $startTime);
//echo $session_id; echo "<br>";
//echo $session->read('session_id');
if($session_id != 0) {
$userStored = $session->read('StateUser');
$transactionPendings = $session->read('Transactions.pending');
if($session->read('session_id') != $session_id ||
( $userStored && !isset($userStored['id'])) ||
intval($transactionPendings) > 0) {
$http = new Client();
try {
$loginServer = Configure::read('LoginServer');
$url = $loginServer['host'] . ':' . $loginServer['port'];
//$url = 'http://***REMOVED***';
$requestStart = microtime(true);
$response = $http->get($url . '/login', ['session_id' => $session_id]);
$json = $response->getJson();
$requestEnd = microtime(true);
if(isset($json) && count($json) > 0) {
if($json['state'] === 'success' && intval($json['user']['email_checked']) === 1) {
//echo "email checked: " . $json['user']['email_checked'] . "; <br>";
$session->destroy();
foreach($json['user'] as $key => $value) {
if($key === 'state') { continue; }
$session->write('StateUser.' . $key, $value );
}
$transactionPendings = $json['Transaction.pending'];
//echo "read transaction pending: $transactionPendings<br>";
$session->write('Transactions.pending', $transactionPendings);
$session->write('session_id', $session_id);
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
if($json['user']['public_hex'] != '') {
$public_key_bin = hex2bin($json['user']['public_hex']);
$stateUserQuery = $stateUserTable
->find('all')
->where(['public_key' => $public_key_bin])
->contain(['StateBalances']);
if($stateUserQuery->count() == 1) {
$stateUser = $stateUserQuery->first();
if($stateUser->first_name != $json['user']['first_name'] ||
$stateUser->last_name != $json['user']['last_name']) {
$stateUser->first_name = $json['user']['first_name'];
$stateUser->last_name = $json['user']['last_name'];
if(!$stateUserTable->save($stateUser)) {
$this->Flash->error(__('error updating state user ' . json_encode($stateUser->errors())));
}
}
//var_dump($stateUser);
if(count($stateUser->state_balances) > 0) {
$session->write('StateUser.balance', $stateUser->state_balances[0]->amount);
}
$session->write('StateUser.id', $stateUser->id);
//echo $stateUser['id'];
} else {
$newStateUser = $stateUserTable->newEntity();
$newStateUser->public_key = $public_key_bin;
$newStateUser->first_name = $json['user']['first_name'];
$newStateUser->last_name = $json['user']['last_name'];
if(!$stateUserTable->save($newStateUser)) {
$this->Flash->error(__('error saving state user ' . json_encode($newStateUser->errors())));
}
$session->write('StateUser.id', $newStateUser->id);
//echo $newStateUser->id;
}
}
// for debugging
$this->set('user', $json['user']);
//$this->set('json', $json);
$this->set('timeUsed', microtime(true) - $startTime);
$this->set('requestTime', $requestEnd - $requestStart);
} else {
if($json['state'] === 'not found' ) {
$this->Flash->error(__('invalid session'));
//echo $json['user']['email_checked'];
//var_dump($json);
//
return $this->redirect(Router::url('/', true) . 'account/', 303);
}
}
}
} catch(\Exception $e) {
$msg = $e->getMessage();
$this->Flash->error(__('error http request: ') . $msg);
return $this->redirect(['controller' => 'Dashboard', 'action' => 'errorHttpRequest']);
//continue;
}
} else {
// login already in session
$user = $session->read('StateUser');
$this->set('user', $user);
$this->set('timeUsed', microtime(true) - $startTime);
}
} else {
// no login
return $this->redirect(Router::url('/', true) . 'account/', 303);
}
} }
public function errorHttpRequest() public function errorHttpRequest()

View File

@ -36,7 +36,10 @@ class StateBalancesController extends AppController
public function overview() public function overview()
{ {
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend'); $this->viewBuilder()->setLayout('frontend');
$this->set('timeUsed', microtime(true) - $startTime);
} }
/** /**

View File

@ -12,6 +12,13 @@ use App\Controller\AppController;
*/ */
class StateErrorsController extends AppController class StateErrorsController extends AppController
{ {
public function initialize()
{
parent::initialize();
$this->Auth->allow(['showForUser', 'deleteForUser']);
}
/** /**
* Index method * Index method
* *
@ -27,6 +34,50 @@ class StateErrorsController extends AppController
$this->set(compact('stateErrors')); $this->set(compact('stateErrors'));
} }
public function showForUser()
{
$startTime = microtime(true);
$this->viewBuilder()->setLayout('frontend');
$session = $this->getRequest()->getSession();
$user = $session->read('StateUser');
if(!$user) {
$result = $this->requestLogin();
if($result !== true) {
return $result;
}
$user = $session->read('StateUser');
}
$errors = $this->StateErrors->find('all')->where(['state_user_id' => $user['id']])->contain(false);
$transactionTypes = $this->StateErrors->TransactionTypes->find('all')->select(['id', 'name', 'text']);
$this->set('errors', $errors);
$this->set('transactionTypes', $transactionTypes->toList());
$this->set('timeUsed', microtime(true) - $startTime);
}
public function deleteForUser($id = null)
{
$this->request->allowMethod(['post', 'delete', 'get']);
$stateError = $this->StateErrors->get($id);
$session = $this->getRequest()->getSession();
$user = $session->read('StateUser');
if($user['id'] != $stateError->state_user_id) {
$this->Flash->error(__('Error belongs to another User, cannot delete'));
}
else if ($this->StateErrors->delete($stateError)) {
$this->Flash->success(__('The state error has been deleted.'));
} else {
$this->Flash->error(__('The state error could not be deleted. Please, try again.'));
}
$errors = $this->StateErrors->find('all')->where(['state_user_id' => $user['id']])->contain(false);
if($errors->count() == 0) {
return $this->redirect(['controller' => 'Dashboard']);
}
return $this->redirect(['action' => 'showForUser']);
}
/** /**
* View method * View method
* *

View File

@ -70,7 +70,12 @@ class TransactionCreationsController extends AppController
$user = $session->read('StateUser'); $user = $session->read('StateUser');
// var_dump($user); // var_dump($user);
if(!$user) { if(!$user) {
return $this->redirect(Router::url('/', true) . 'account/', 303); //return $this->redirect(Router::url('/', true) . 'account/', 303);
$result = $this->requestLogin();
if($result !== true) {
return $result;
}
$user = $session->read('StateUser');
} }
$creationForm = new CreationForm(); $creationForm = new CreationForm();
$transactionCreation = $this->TransactionCreations->newEntity(); $transactionCreation = $this->TransactionCreations->newEntity();

View File

@ -47,14 +47,14 @@ class TransactionJsonRequestHandlerController extends AppController {
return $this->returnJson(['state' => 'error', 'msg' => 'error parsing transaction', 'details' => $transaction->getErrors()]); return $this->returnJson(['state' => 'error', 'msg' => 'error parsing transaction', 'details' => $transaction->getErrors()]);
} }
if(!$transaction->validate()) { if(!$transaction->validate()) {
return $this->returnJson(['state' => 'error', 'msg' => 'error validate transaction', 'details' => $transaction->getErrors()]); return $this->returnJsonSaveError($transaction, ['state' => 'error', 'msg' => 'error validate transaction', 'details' => $transaction->getErrors()]);
} }
if ($transaction->save()) { if ($transaction->save()) {
// success // success
return $this->returnJson(['state' => 'success']); return $this->returnJson(['state' => 'success']);
} else { } else {
return $this->returnJson([ return $this->returnJsonSaveError($transaction, [
'state' => 'error', 'state' => 'error',
'msg' => 'error saving transaction in db', 'msg' => 'error saving transaction in db',
'details' => json_encode($transaction->getErrors()) 'details' => json_encode($transaction->getErrors())
@ -65,4 +65,23 @@ class TransactionJsonRequestHandlerController extends AppController {
} }
private function returnJsonSaveError($transaction, $errorArray) {
$json = json_encode($errorArray);
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
$pub = $transaction->getFirstPublic();
$stateUserQuery = $stateUserTable
->find('all')
->where(['public_key' => $pub])
->contain(false);
if($stateUserQuery->count() == 1) {
$stateErrorsTable = TableRegistry::getTableLocator()->get('StateErrors');
$stateErrorEntity = $stateErrorsTable->newEntity();
$stateErrorEntity->state_user_id = $stateUserQuery->first()->id;
$stateErrorEntity->transaction_type_id = $transaction->getTransactionBody()->getTransactionTypeId();
$stateErrorEntity->message_json = $json;
$stateErrorsTable->save($stateErrorEntity);
}
return $this->returnJsonEncoded($json);
}
} }

View File

@ -8,6 +8,7 @@ class TransactionBody extends TransactionBase {
private $mProtoTransactionBody = null; private $mProtoTransactionBody = null;
private $mSpecificTransaction = null; private $mSpecificTransaction = null;
private $mTransactionID = 0; private $mTransactionID = 0;
private $transactionTypeId = 0;
public function __construct($bodyBytes) { public function __construct($bodyBytes) {
$this->mProtoTransactionBody = new \Model\Messages\Gradido\TransactionBody(); $this->mProtoTransactionBody = new \Model\Messages\Gradido\TransactionBody();
@ -27,6 +28,18 @@ class TransactionBody extends TransactionBase {
} }
public function validate($sigPairs) { public function validate($sigPairs) {
// transaction type id
$transactionTypesTable = TableRegistry::getTableLocator()->get('transaction_types');
$typeName = $this->getTransactionTypeName();
$transactionType = $transactionTypesTable->find('all')->where(['name' => $typeName])->select(['id'])->first();
if($transactionType == NULL) {
$this->addError('TransactionBody::validate', 'zero type id for type: ' . $typeName);
return false;
}
$this->transactionTypeId = $transactionType->id;
// check if creation time is in the past // check if creation time is in the past
if($this->mProtoTransactionBody->getCreated()->getSeconds() > time()) { if($this->mProtoTransactionBody->getCreated()->getSeconds() > time()) {
$this->addError('TransactionBody::validate', 'Transaction were created in the past!'); $this->addError('TransactionBody::validate', 'Transaction were created in the past!');
@ -36,6 +49,9 @@ class TransactionBody extends TransactionBase {
$this->addErrors($this->mSpecificTransaction->getErrors()); $this->addErrors($this->mSpecificTransaction->getErrors());
return false; return false;
} }
return true; return true;
} }
@ -56,16 +72,8 @@ class TransactionBody extends TransactionBase {
$transactionsTable = TableRegistry::getTableLocator()->get('transactions'); $transactionsTable = TableRegistry::getTableLocator()->get('transactions');
$transactionEntity = $transactionsTable->newEntity(); $transactionEntity = $transactionsTable->newEntity();
// transaction type id
$transactionTypesTable = TableRegistry::getTableLocator()->get('transaction_types');
$typeName = $this->getTransactionTypeName(); $transactionEntity->transaction_type_id = $this->transactionTypeId;
$transactionType = $transactionTypesTable->find('all')->where(['name' => $typeName])->select(['id'])->first();
if($transactionType == NULL) {
$this->addError('TransactionBody::save', 'zero type id for type: ' . $typeName);
return false;
}
$transactionEntity->transaction_type_id = $transactionType->id;
$transactionEntity->memo = $this->getMemo(); $transactionEntity->memo = $this->getMemo();
if ($transactionsTable->save($transactionEntity)) { if ($transactionsTable->save($transactionEntity)) {
@ -86,5 +94,8 @@ class TransactionBody extends TransactionBase {
return $this->mTransactionID; return $this->mTransactionID;
} }
public function getTransactionTypeId() {
return $this->transactionTypeId;
}
} }

View File

@ -52,8 +52,10 @@ $cakeDescription = 'Gradido';
<div class="container clearfix"> <div class="container clearfix">
<?= $this->fetch('content') ?> <?= $this->fetch('content') ?>
</div> </div>
<div class="grd-time-used dev-info"> <?php if(isset($timeUsed)) : ?>
<?= round($timeUsed * 1000.0, 4) ?> ms <div class="grd-time-used dev-info">
</div> <?= round($timeUsed * 1000.0, 4) ?> ms
</div>
<?php endif;?>
</body> </body>
</html> </html>

View File

@ -20,6 +20,7 @@ use App\Controller\Component\GradidoNumberComponent;
$cakeDescription = 'Gradido'; $cakeDescription = 'Gradido';
$session = $this->getRequest()->getSession(); $session = $this->getRequest()->getSession();
$transactionPendings = $session->read('Transactions.pending'); $transactionPendings = $session->read('Transactions.pending');
$errorCount = intval($session->read('StateUser.errorCount'));
$balance = $session->read('StateUser.balance'); $balance = $session->read('StateUser.balance');
//echo "balance: $balance<br>"; //echo "balance: $balance<br>";
if(!isset($balance)) { if(!isset($balance)) {
@ -60,8 +61,13 @@ if(!isset($balance)) {
?> ?>
</li> </li>
<?php endif; ?> <?php endif; ?>
<li><?= $this->Html->link(__('Startseite'), ['controller' => 'dashboard'], ['class' => 'grd-nav-bn'])?> <li><?= $this->Html->link(__('Startseite'), ['controller' => 'Dashboard'], ['class' => 'grd-nav-bn'])?>
<!--<li><?= $this->Html->link(__('Kontostand'), ['controller' => 'StateBalances', 'action' => 'overview'], ['class' => 'grd-nav-bn']) ?>--> <!--<li><?= $this->Html->link(__('Kontostand'), ['controller' => 'StateBalances', 'action' => 'overview'], ['class' => 'grd-nav-bn']) ?>-->
<?php if($errorCount > 0) : ?>
<li>
<?= $this->Html->Link(__('Fehler '). "($errorCount)", ['controller' => 'StateErrors', 'action' => 'showForUser'], ['class' => 'grd-nav-bn grd-nav-bn-discard']) ?>
</li>
<?php endif; ?>
<?php if(intval($transactionPendings) > 0) : ?> <?php if(intval($transactionPendings) > 0) : ?>
<li> <li>
<a href="<?= Router::url('./', true) ?>account/checkTransactions" class="grd-nav-bn"> <a href="<?= Router::url('./', true) ?>account/checkTransactions" class="grd-nav-bn">
@ -79,8 +85,10 @@ if(!isset($balance)) {
<div class="flash-messages"><?= $this->Flash->render() ?></div> <div class="flash-messages"><?= $this->Flash->render() ?></div>
<?= $this->fetch('content') ?> <?= $this->fetch('content') ?>
</div> </div>
<div class="grd-time-used dev-info"> <?php if(isset($timeUsed)) : ?>
<?= round($timeUsed * 1000.0, 4) ?> ms <div class="grd-time-used dev-info">
</div> <?= round($timeUsed * 1000.0, 4) ?> ms
</div>
<?php endif; ?>
</body> </body>
</html> </html>

View File

@ -0,0 +1,34 @@
<?php
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$this->assign('title', __('Fehlermeldungen'));
//var_dump($transactionTypes);
/*foreach($transactionTypes as $i => $t) {
echo "$i => ";
var_dump($t);
echo "<br>";
}*/
?>
<div class="grd_container_small">
<table>
<thead>
<tr><th>Transaktion Typ</th><th>Datum</th><th>Fehler</th><th>Aktionen</th></tr>
</thead>
<tbody>
<?php foreach($errors as $error) :
$type = $transactionTypes[$error->transaction_type_id]; ?>
<tr>
<td title="<?= $type->text ?>"><?= $type->name ?></td>
<td><?= $error->created ?></td>
<td><?= $error->message_json ?></td>
<td><?= $this->Html->link(__('Delete'), ['action' => 'deleteForUser', $error->id], ['class' => 'grd-form-bn grd-form-bn-discard']) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>