Restore AppController

This commit is contained in:
Christine Slotty 2020-07-10 13:47:58 +02:00
parent a27a5af25f
commit 994fc42fac

View File

@ -33,7 +33,7 @@ use Cake\I18n\I18n;
*/ */
class AppController extends Controller class AppController extends Controller
{ {
var $loginServerUrl = ''; var $loginServerUrl = '';
/** /**
* Initialization hook method. * Initialization hook method.
@ -44,124 +44,104 @@ class AppController extends Controller
* *
* @return void * @return void
*/ */
public function initialize() public function initialize()
{ {
parent::initialize(); parent::initialize();
$this->loadComponent('RequestHandler', [ $this->loadComponent('RequestHandler', [
'enableBeforeRedirect' => false, 'enableBeforeRedirect' => false,
]); ]);
$this->loadComponent('Flash'); $this->loadComponent('Flash');
$this->loadComponent('Auth', [ $this->loadComponent('Auth', [
<<<<<<< Updated upstream 'loginAction' => [
'loginAction' => [ 'controller' => 'ServerUsers',
'controller' => 'ServerUsers', 'action' => 'login'
'action' => 'login' ],
], 'loginRedirect' => [
'loginRedirect' => [ 'controller' => 'Transactions',
'controller' => 'Transactions', 'action' => 'index'
'action' => 'index' ],
], 'logoutRedirect' => [
'logoutRedirect' => [ 'controller' => 'Pages',
'controller' => 'Pages', 'action' => 'display',
'action' => 'display', 'gradido'
'gradido' ],
], 'authenticate' => [
'authenticate' => [ 'all' => ['userModel' => 'ServerUsers'],
'all' => ['userModel' => 'ServerUsers'], 'Form' => [
'Form' => [ 'userModel' => 'ServerUsers',
'userModel' => 'ServerUsers', ]
] ]
] ]);
======= $this->Auth->deny(['index']);
'loginAction' => [
'controller' => 'ServerUsers',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Transactions',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Pages',
'action' => 'display',
'gradido'
],
'authenticate' => [
'all' => ['userModel' => 'ServerUsers'],
'Form' => [
'userModel' => 'ServerUsers',
]
]
]);
$this->Auth->deny(['index']); /*
* Enable the following component for recommended CakePHP security settings.
/* * see https://book.cakephp.org/3.0/en/controllers/components/security.html
* Enable the following component for recommended CakePHP security settings. */
* see https://book.cakephp.org/3.0/en/controllers/components/security.html //$this->loadComponent('Security');
*/
//$this->loadComponent('Security');
// load current balance // load current balance
$session = $this->getRequest()->getSession(); $session = $this->getRequest()->getSession();
$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');
$stateBalanceQuery = $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 ($stateBalanceQuery->count() == 1) { if($stateBalanceQuery->count() == 1) {
//var_dump($stateBalanceEntry->first()); //var_dump($stateBalanceEntry->first());
$session->write('StateUser.balance', $stateBalanceQuery->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";
// put current page into global for navi
$GLOBALS["passed"] = null;
$side = $this->request->getParam('controller');
$GLOBALS["side"] = $side;
$subside = $this->request->getParam('action');
$passedArguments = $this->request->getParam('pass');
if($passedArguments) {
$GLOBALS["passed"] = $passedArguments[0];
}
$GLOBALS["subside"] = $subside;
// server login
if($this->Auth->user('id')) {
$GLOBALS['ServerUser'] = $this->Auth->user();
}
// login server url
$loginServer = Configure::read('LoginServer');
if($loginServer && isset($loginServer['url'])) {
$this->loginServerUrl = $loginServer['url'] . '/';
} else {
$this->loginServerUrl = Router::url('/', true);
}
} }
// load error count protected function requestLogin()
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";
// put current page into global for navi
$GLOBALS["passed"] = null;
$side = $this->request->getParam('controller');
$GLOBALS["side"] = $side;
$subside = $this->request->getParam('action');
$passedArguments = $this->request->getParam('pass');
if ($passedArguments) {
$GLOBALS["passed"] = $passedArguments[0];
}
$GLOBALS["subside"] = $subside;
// server login
if ($this->Auth->user('id')) {
$GLOBALS['ServerUser'] = $this->Auth->user();
}
// login server url
$loginServer = Configure::read('LoginServer');
if ($loginServer && isset($loginServer['url'])) {
$this->loginServerUrl = $loginServer['url'] . '/';
} else {
$this->loginServerUrl = Router::url('/', true);
}
}
protected function requestLogin()
{ {
$session = $this->getRequest()->getSession(); $session = $this->getRequest()->getSession();
// check login // check login
@ -169,121 +149,118 @@ protected function requestLogin()
//$this->Cookie->configKey('User', 'encryption', false); //$this->Cookie->configKey('User', 'encryption', false);
$session_id = intval($this->request->getCookie('GRADIDO_LOGIN', '')); $session_id = intval($this->request->getCookie('GRADIDO_LOGIN', ''));
$ip = $this->request->clientIp(); $ip = $this->request->clientIp();
if (!$session->check('client_ip')) { if(!$session->check('client_ip')) {
$session->write('client_ip', $ip); $session->write('client_ip', $ip);
} }
// login server cannot detect host ip // login server cannot detect host ip
// TODO: update login server, recognize nginx real ip header // TODO: update login server, recognize nginx real ip header
$loginServer = Configure::read('LoginServer'); $loginServer = Configure::read('LoginServer');
if ($session_id != 0) { if($session_id != 0) {
$userStored = $session->read('StateUser'); $userStored = $session->read('StateUser');
$transactionPendings = $session->read('Transactions.pending');
$transactionExecutings = $session->read('Transaction.executing'); $transactionPendings = $session->read('Transactions.pending');
if ($session->read('session_id') != $session_id || $transactionExecutings = $session->read('Transaction.executing');
( $userStored && (!isset($userStored['id']) || !$userStored['email_checked'])) || if($session->read('session_id') != $session_id ||
intval($transactionPendings) > 0 || ( $userStored && (!isset($userStored['id']) || !$userStored['email_checked'])) ||
intval($transactionExecutings) > 0) { intval($transactionPendings) > 0 ||
$http = new Client(); intval($transactionExecutings) > 0 ) {
try {
$url = $loginServer['host'] . ':' . $loginServer['port'];
( $userStored && !isset($userStored['id'])) ||
intval($transactionPendings) > 0 ||
intval($transactionExecutings) > 0) {
$http = new Client(); $http = new Client();
try { try {
$url = $loginServer['host'] . ':' . $loginServer['port']; $url = $loginServer['host'] . ':' . $loginServer['port'];
$response = $http->get($url . '/login', ['session_id' => $session_id]);
$json = $response->getJson();
if (isset($json) && count($json) > 0) { $response = $http->get($url . '/login', ['session_id' => $session_id]);
if ($json['state'] === 'success') { $json = $response->getJson();
//echo "email checked: " . $json['user']['email_checked'] . "; <br>";
if ($session->read('session_id') != $session_id ||
( $userStored && !isset($userStored['id']))) {
$session->destroy();
}
foreach ($json['user'] as $key => $value) {
$session->write('StateUser.' . $key, $value);
}
//var_dump($json);
$transactionPendings = $json['Transaction.pending'];
$transactionExecuting = $json['Transaction.executing'];
//echo "read transaction pending: $transactionPendings<br>";
$session->write('Transactions.pending', $transactionPendings);
$session->write('Transaction.executing', $transactionExecuting);
$session->write('session_id', $session_id);
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
if (isset($json['user']['public_hex']) && $json['user']['public_hex'] != '') { if(isset($json) && count($json) > 0) {
$public_key_bin = hex2bin($json['user']['public_hex']);
$stateUserQuery = $stateUserTable if($json['state'] === 'success') {
//echo "email checked: " . $json['user']['email_checked'] . "; <br>";
if($session->read('session_id') != $session_id ||
( $userStored && !isset($userStored['id']))) {
$session->destroy();
}
foreach($json['user'] as $key => $value) {
$session->write('StateUser.' . $key, $value );
}
//var_dump($json);
$transactionPendings = $json['Transaction.pending'];
$transactionExecuting = $json['Transaction.executing'];
//echo "read transaction pending: $transactionPendings<br>";
$session->write('Transactions.pending', $transactionPendings);
$session->write('Transaction.executing', $transactionExecuting);
$session->write('session_id', $session_id);
$stateUserTable = TableRegistry::getTableLocator()->get('StateUsers');
if(isset($json['user']['public_hex']) && $json['user']['public_hex'] != '') {
$public_key_bin = hex2bin($json['user']['public_hex']);
$stateUserQuery = $stateUserTable
->find('all') ->find('all')
->where(['public_key' => $public_key_bin]) ->where(['public_key' => $public_key_bin])
->contain(['StateBalances']); ->contain(['StateBalances']);
if ($stateUserQuery->count() == 1) { if($stateUserQuery->count() == 1) {
$stateUser = $stateUserQuery->first(); $stateUser = $stateUserQuery->first();
if ($stateUser->first_name != $json['user']['first_name'] || if($stateUser->first_name != $json['user']['first_name'] ||
$stateUser->last_name != $json['user']['last_name'] || $stateUser->last_name != $json['user']['last_name'] ||
$stateUser->email != $json['user']['email']) { $stateUser->email != $json['user']['email']) {
$stateUser->first_name = $json['user']['first_name']; $stateUser->first_name = $json['user']['first_name'];
$stateUser->last_name = $json['user']['last_name']; $stateUser->last_name = $json['user']['last_name'];
$stateUser->email = $json['user']['email']; $stateUser->email = $json['user']['email'];
if (!$stateUserTable->save($stateUser)) { if(!$stateUserTable->save($stateUser)) {
$this->Flash->error(__('error updating state user ' . json_encode($stateUser->errors()))); $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'];
$newStateUser->email = $json['user']['email'];
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 {
// we haven't get a pubkey? something seems to gone wrong on the login-server
$this->Flash->error(__('no pubkey'));
//var_dump($json);
return $this->redirect($this->loginServerUrl . 'account/error500/noPubkey', 303);
} }
}
//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 { } else {
if ($json['state'] === 'not found') { $newStateUser = $stateUserTable->newEntity();
$this->Flash->error(__('invalid session')); $newStateUser->public_key = $public_key_bin;
} else { $newStateUser->first_name = $json['user']['first_name'];
$this->Flash->error(__('Konto ist nicht aktiviert!')); $newStateUser->last_name = $json['user']['last_name'];
} $newStateUser->email = $json['user']['email'];
//die(json_encode($json)); if(!$stateUserTable->save($newStateUser)) {
return $this->redirect($this->loginServerUrl . 'account/', 303); $this->Flash->error(__('error saving state user ' . json_encode($newStateUser->errors())));
}
$session->write('StateUser.id', $newStateUser->id);
//echo $newStateUser->id;
} }
} else {
// we haven't get a pubkey? something seems to gone wrong on the login-server
$this->Flash->error(__('no pubkey'));
//var_dump($json);
return $this->redirect($this->loginServerUrl . 'account/error500/noPubkey', 303);
}
} else {
if($json['state'] === 'not found' ) {
$this->Flash->error(__('invalid session'));
} else {
$this->Flash->error(__('Konto ist nicht aktiviert!'));
}
//die(json_encode($json));
return $this->redirect($this->loginServerUrl . 'account/', 303);
} }
} catch (\Exception $e) { }
$msg = $e->getMessage(); } catch(\Exception $e) {
$this->Flash->error(__('error http request: ') . $msg); $msg = $e->getMessage();
return $this->redirect(['controller' => 'Dashboard', 'action' => 'errorHttpRequest']); $this->Flash->error(__('error http request: ') . $msg);
return $this->redirect(['controller' => 'Dashboard', 'action' => 'errorHttpRequest']);
//continue; //continue;
} }
} }
} else { } else {
// no login // no login
//die("no login"); //die("no login");
if (isset($loginServer['path'])) { if(isset($loginServer['path'])) {
return $this->redirect($loginServer['path'], 303); return $this->redirect($loginServer['path'], 303);
} else { } else {
return $this->redirect($this->loginServerUrl . 'account/', 303); return $this->redirect($this->loginServerUrl . 'account/', 303);
} }
} }
return true; return true;
} }
@ -291,67 +268,64 @@ if ($session_id != 0) {
/* /*
public function beforeFilter(Event $event) public function beforeFilter(Event $event)
{ {
//$this->Auth->allow(['display']); //$this->Auth->allow(['display']);
} }
*/ */
public function addAdminError($controller, $action, array $returnTable, $state_user_id) public function addAdminError($controller, $action, array $returnTable, $state_user_id) {
{ if(!is_array($returnTable)) {
if (!is_array($returnTable)) { $this->addAdminError('AppController', 'addAdminError', ['state' => 'error', 'msg' => 'returnTable isn\'t array', 'details' => gettype($returnTable)], $state_user_id);
$this->addAdminError('AppController', 'addAdminError', ['state' => 'error', 'msg' => 'returnTable isn\'t array', 'details' => gettype($returnTable)], $state_user_id); return false;
return false; }
} $adminErrorTable = TableRegistry::getTableLocator()->get('AdminErrors');
$adminErrorTable = TableRegistry::getTableLocator()->get('AdminErrors'); $adminErrorEntity = $adminErrorTable->newEntity();
$adminErrorEntity = $adminErrorTable->newEntity(); $adminErrorEntity->state_user_id = $state_user_id;
$adminErrorEntity->state_user_id = $state_user_id; $adminErrorEntity->controller = $controller;
$adminErrorEntity->controller = $controller; $adminErrorEntity->action = $action;
$adminErrorEntity->action = $action; $adminErrorEntity->state = $returnTable['state'];
$adminErrorEntity->state = $returnTable['state']; if(isset($returnTable['msg'])) {
if (isset($returnTable['msg'])) { $adminErrorEntity->msg = $returnTable['msg'];
$adminErrorEntity->msg = $returnTable['msg']; } else {
} else { $adminErrorEntity->msg = __('(Leere Message)');
$adminErrorEntity->msg = __('(Leere Message)'); }
} if(isset($returnTable['details'])) {
if (isset($returnTable['details'])) { $adminErrorEntity->details = $returnTable['details'];
$adminErrorEntity->details = $returnTable['details']; } else {
} else { $adminErrorEntity->details = __('(Leere Details)');
$adminErrorEntity->details = __('(Leere Details)'); }
} if(!$adminErrorTable->save($adminErrorEntity)) {
if (!$adminErrorTable->save($adminErrorEntity)) { $this->Flash->error(
$this->Flash->error(
__('Serious error, couldn\'t save to db, please write the admin: ' . $this->getAdminEmailLink()), __('Serious error, couldn\'t save to db, please write the admin: ' . $this->getAdminEmailLink()),
['escape' => false] ['escape' => false]);
);
} }
return true; return true;
}
public function getAdminEmailLink($text = '') {
$serverAdminEmail = Configure::read('ServerAdminEmail');
return '<a href="mailto:' . $serverAdminEmail . '">'. $serverAdminEmail . '</a>';
} }
public function getAdminEmailLink($text = '') public function returnJsonEncoded($json) {
{ $this->autoRender = false;
$serverAdminEmail = Configure::read('ServerAdminEmail'); $response = $this->response->withType('application/json');
return '<a href="mailto:' . $serverAdminEmail . '">'. $serverAdminEmail . '</a>'; return $response->withStringBody($json);
} }
public function returnJsonEncoded($json) public function returnJson($array) {
{ $this->autoRender = false;
$this->autoRender = false; $response = $this->response->withType('application/json');
$response = $this->response->withType('application/json'); return $response->withStringBody(json_encode($array));
return $response->withStringBody($json);
}
public function returnJson($array)
{
$this->autoRender = false;
$response = $this->response->withType('application/json');
return $response->withStringBody(json_encode($array));
} }
public function getStartEndForMonth($month, $year) public function getStartEndForMonth($month, $year)
{ {
$timeString = $year . '-' . $month . '-01 00:00'; $timeString = $year . '-' . $month . '-01 00:00';
$firstDay = new Time($timeString); $firstDay = new Time($timeString);
$lastDay = new Time($timeString); $lastDay = new Time($timeString);
$lastDay = $lastDay->addMonth(1); $lastDay = $lastDay->addMonth(1);
return [$firstDay, $lastDay]; return [$firstDay, $lastDay];
} }
} }