diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 1dbddef5d..104b85502 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -44,19 +44,19 @@ jobs:
- name: Checkout code
uses: actions/checkout@v2
with:
- submodules: recursive
+ submodules: true
##########################################################################
# BUILD LOGIN SERVER DOCKER IMAGE ########################################
##########################################################################
- - name: login server | Build `test` image
+ - name: login server | Build `release` image
run: |
- docker build --target login_server -t "gradido/login_server:test" -f ./login_server/Dockerfile login_server/
- docker save "gradido/login_server:test" > /tmp/login_server.tar
- - name: Upload Artifact
- uses: actions/upload-artifact@v2
- with:
- name: docker-login-server-test
- path: /tmp/login_server.tar
+ docker build --target release -t "gradido/login_server:release" -f ./login_server/Dockerfile login_server/
+ #docker save "gradido/login_server:test" > /tmp/login_server.tar
+ #- name: Upload Artifact
+ # uses: actions/upload-artifact@v2
+ #with:
+ # name: docker-login-server-test
+ #path: /tmp/login_server.tar
##############################################################################
# JOB: DOCKER BUILD TEST COMMUNITY SERVER ####################################
@@ -102,7 +102,7 @@ jobs:
##########################################################################
- name: mariadb | Build `test` image
run: |
- docker build -t "gradido/mariadb:test" -f ./mariadb/Dockerfile ./
+ docker build --target mariadb_server_test -t "gradido/mariadb:test" -f ./mariadb/Dockerfile ./
docker save "gradido/mariadb:test" > /tmp/mariadb.tar
- name: Upload Artifact
uses: actions/upload-artifact@v2
@@ -215,6 +215,135 @@ jobs:
min_coverage: 21
token: ${{ github.token }}
+ ##############################################################################
+ # JOB: UNIT TEST LOGIN-SERVER ###############################################
+ ##############################################################################
+ unit_test_login_server:
+ name: Unit tests - Login-Server
+ runs-on: ubuntu-latest
+ needs: []
+ services:
+ mariadb:
+ image: gradido/mariadb:test
+ env:
+ MARIADB_ALLOW_EMPTY_PASSWORD: 1
+ MARIADB_USER: root
+ ports:
+ - 3306:3306
+ options: --health-cmd="mysqladmin ping"
+ --health-interval=6s
+ --health-timeout=3s
+ --health-retries=4
+ steps:
+ - name: Debug service
+ run: echo "$(docker ps)"
+ - name: Debug container choosing script
+ run: echo "$(docker container ls | grep mariadb | awk '{ print $1 }')"
+ ##########################################################################
+ # CHECKOUT CODE ##########################################################
+ ##########################################################################
+ - name: Checkout code
+ uses: actions/checkout@v2
+ with:
+ submodules: true
+ ##########################################################################
+ # Build Login-Server Test Docker image ###################################
+ ##########################################################################
+ - name: login server | Build `test` image
+ run: |
+ docker build --target test -t "gradido/login_server:test" -f ./login_server/Dockerfile login_server/
+ ##########################################################################
+ # UNIT TESTS BACKEND LOGIN-SERVER #######################################
+ ##########################################################################
+ - name: Login-Server | Unit tests
+ run: |
+ docker run --network container:$(docker container ls | grep mariadb | awk '{ print $1 }') -v ~/coverage:/code/build_cov/coverage -v $(pwd)/configs/login_server:/etc/grd_login gradido/login_server:test
+ cp -r ~/coverage ./coverage
+ ##########################################################################
+ # COVERAGE CHECK BACKEND LOGIN-SERVER ####################################
+ ##########################################################################
+ - name: backend login | Coverage check
+ uses: webcraftmedia/coverage-check-action@master
+ with:
+ report_name: Coverage Backend
+ type: lcov
+ result_path: ./coverage/coverage.info
+ min_coverage: 6
+ token: ${{ github.token }}
+
+ ##############################################################################
+ # JOB: UNIT TEST COMMUNITY-SERVER ###########################################
+ ##############################################################################
+ unit_test_community_server:
+ name: Unit tests - Community Server
+ runs-on: ubuntu-latest
+ needs: [build_test_community_server]
+ services:
+ mariadb:
+ image: gradido/mariadb:test
+ env:
+ MARIADB_ALLOW_EMPTY_PASSWORD: 1
+ MARIADB_USER: root
+ # ports:
+ # - 3306:3306
+ options: --health-cmd="mysqladmin ping"
+ --health-interval=5s
+ --health-timeout=5s
+ --health-retries=3
+ steps:
+ - name: get mariadb container id
+ run: echo "::set-output name=id::$(docker container ls | grep mariadb | awk '{ print $1 }')"
+ id: mariadb_container
+ - name: show networks
+ run: echo "$(docker network ls)"
+ - name: get automatic created network
+ run: echo "::set-output name=id::$(docker network ls | grep github_network | awk '{ print $1 }')"
+ id: network
+ - name: Start Login-Server
+ run: docker run --network ${{ steps.network.outputs.id }} --name=login-server -d gradido/login_server:default
+ - name: get login-server container id
+ run: echo "::set-output name=id::$(docker container ls | grep login_server | awk '{ print $1 }')"
+ id: login_server_container
+ ##########################################################################
+ # CHECKOUT CODE ##########################################################
+ ##########################################################################
+ - name: Checkout code
+ uses: actions/checkout@v2
+ ##########################################################################
+ # DOWNLOAD DOCKER IMAGE ##################################################
+ ##########################################################################
+ - name: Download Docker Image (Community-Server)
+ uses: actions/download-artifact@v2
+ with:
+ name: docker-community-server-test
+ path: /tmp
+ - name: Load Docker Image
+ run: docker load < /tmp/community_server.tar
+
+ # for debugging login-server
+ - name: check login-server
+ run: docker logs ${{ steps.login_server_container.outputs.id }}
+ - name: check mariadb
+ run: docker logs ${{ steps.mariadb_container.outputs.id }}
+ ##########################################################################
+ # UNIT TESTS BACKEND COMMUNITY-SERVER #######################################
+ ##########################################################################
+ - name: community server | Unit tests
+ run: |
+ docker run --network ${{ steps.network.outputs.id }} -v ~/coverage:/var/www/cakephp/webroot/coverage gradido/community_server:test
+ cp -r ~/coverage ./coverage
+ #########################################################################
+ # COVERAGE CHECK BACKEND COMMUNITY-SERVER ####################################
+ ##########################################################################
+ #- name: backend community simplecov | Coverage check
+ # uses: webcraftmedia/coverage-check-action@master
+ # with:
+ # report_name: Coverage Backend
+ # type: simplecov
+ # result_path: ./coverage/coverage.info
+ # min_coverage: 8
+ # token: ${{ github.token }}
+
#test:
# runs-on: ubuntu-latest
# steps:
@@ -228,4 +357,4 @@ jobs:
# GN_INSTANCE_FOLDER: /tmp/gradio-node-instance
# GN_CONTAINER_NAME: gradido-node-build
# run: docker run gradido-node-test
- # timeout-minutes: 2
\ No newline at end of file
+ # timeout-minutes: 2
diff --git a/.gitmodules b/.gitmodules
index 62e643b38..22790ccc7 100644
--- a/.gitmodules
+++ b/.gitmodules
@@ -15,16 +15,13 @@
[submodule "login_server/dependencies/spirit-po"]
path = login_server/dependencies/spirit-po
url = https://github.com/cbeck88/spirit-po.git
-[submodule "login_server/dependencies/grpc"]
- path = login_server/dependencies/grpc
- url = https://github.com/grpc/grpc.git
[submodule "login_server/dependencies/poco"]
path = login_server/dependencies/poco
url = https://github.com/pocoproject/poco.git
[submodule "login_server/dependencies/cmake-modules"]
path = login_server/dependencies/cmake-modules
url = https://github.com/viaduck/cmake-modules.git
-
+
[submodule "community_server/src/protobuf"]
path = community_server/src/protobuf
url = https://github.com/gradido/gradido_protocol.git
@@ -34,3 +31,6 @@
[submodule "login_server/src/proto"]
path = login_server/src/proto
url = https://github.com/gradido/gradido_protocol.git
+[submodule "login_server/dependencies/protobuf"]
+ path = login_server/dependencies/protobuf
+ url = https://github.com/protocolbuffers/protobuf.git
diff --git a/community_server/Dockerfile b/community_server/Dockerfile
index 8129d581d..eabb37741 100644
--- a/community_server/Dockerfile
+++ b/community_server/Dockerfile
@@ -1,8 +1,8 @@
-FROM phpdockerio/php74-fpm
+FROM phpdockerio/php74-fpm as community_server
# install php fpm
RUN apt-get update \
- && apt-get -y --no-install-recommends install curl unzip php7.4-curl php7.4-fpm php7.4-mbstring php7.4-intl php7.4-xml php7.4-pdo php7.4-mysql \
+ && apt-get -y --no-install-recommends install curl unzip php7.4-curl php7.4-fpm php7.4-mbstring php7.4-intl php7.4-xml php7.4-pdo php7.4-mysql php7.4-xdebug \
&& apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
WORKDIR /var/www/cakephp
@@ -13,5 +13,17 @@ COPY ./configs/community_server/app.php ./config/
RUN composer update
RUN composer dump-autoload
+######### special for code coverage and testing
+FROM community_server as test
+
+
+RUN apt-get update \
+ && apt-get -y --no-install-recommends install php7.4-xdebug \
+ && apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
+
+WORKDIR /var/www/cakephp
+ENV XDEBUG_MODE=coverage
+
+CMD ./vendor/bin/phpunit --coverage-text=./webroot/coverage/coverage.info
diff --git a/community_server/config/routes.php b/community_server/config/routes.php
index 3b0dfedc1..791692e96 100644
--- a/community_server/config/routes.php
+++ b/community_server/config/routes.php
@@ -66,7 +66,7 @@ Router::scope('/', function (RouteBuilder $routes) {
return true;
}
$allowedIpLocalhost = ['127.0.0.1', 'localhost', '', '::1'];
- if(in_array($clientIp, $allowedIpLocalhost)) {
+ if(in_array($request->clientIp(), $allowedIpLocalhost)) {
return true;
}
$allowedCaller = Configure::read('API.allowedCaller');
diff --git a/community_server/src/Controller/AppController.php b/community_server/src/Controller/AppController.php
index a1416678f..eb11299ce 100644
--- a/community_server/src/Controller/AppController.php
+++ b/community_server/src/Controller/AppController.php
@@ -88,19 +88,8 @@ class AppController extends Controller
// load current balance
$session = $this->getRequest()->getSession();
$state_user_id = $session->read('StateUser.id');
- if ($state_user_id) {
- $stateBalancesTable = TableRegistry::getTableLocator()->get('stateBalances');
- $stateBalanceQuery = $stateBalancesTable
- ->find('all')
- ->contain(false)
- ->where(['state_user_id' => $state_user_id]);
- if ($stateBalanceQuery->count() == 1) {
- //var_dump($stateBalanceEntry->first());
- $session->write('StateUser.balance', $stateBalanceQuery->first()->decay);
- //echo "stateUser.balance: " . $session->read('StateUser.balance');
- }
- }
-
+
+
// load error count
if ($state_user_id) {
$stateErrorsTable = TableRegistry::getTableLocator()->get('stateErrors');
@@ -111,8 +100,6 @@ class AppController extends Controller
->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;
diff --git a/community_server/src/Controller/AppRequestsController.php b/community_server/src/Controller/AppRequestsController.php
index 456065c36..6b744ff69 100644
--- a/community_server/src/Controller/AppRequestsController.php
+++ b/community_server/src/Controller/AppRequestsController.php
@@ -276,7 +276,8 @@ class AppRequestsController extends AppController
$this->viewBuilder()->setLayout('ajax');
$login_result = $this->requestLogin($session_id, false);
if($login_result !== true) {
- return $this->returnJson($login_result);
+ $this->set('body', $login_result);
+ return;
}
$session = $this->getRequest()->getSession();
$user = $session->read('StateUser');
@@ -285,16 +286,24 @@ class AppRequestsController extends AppController
$state_balance = $state_balances_table->find()->where(['state_user_id' => $user['id']])->first();
- if(!$state_balance) {
- return $this->returnJson(['state' => 'success', 'balance' => 0]);
- }
+
$now = new FrozenTime();
- $body = [
- 'state' => 'success',
- 'balance' => $state_balance->amount,
- 'decay' => $state_balance->partDecay($now),
- 'decay_date' => $now
- ];
+ if(!$state_balance) {
+ $body = [
+ 'state' => 'success',
+ 'balance' => 0,
+ 'decay' => 0
+ ];
+ } else {
+
+ $body = [
+ 'state' => 'success',
+ 'balance' => $state_balance->amount,
+ 'decay' => $state_balance->partDecay($now),
+ ];
+ }
+
+ $body['decay_date'] = $now;
$this->set('body', $body);
}
@@ -302,35 +311,31 @@ class AppRequestsController extends AppController
{
$this->viewBuilder()->setLayout('ajax');
$startTime = microtime(true);
+
$login_result = $this->requestLogin($session_id, false);
+
if($login_result !== true) {
return $this->returnJson($login_result);
}
$session = $this->getRequest()->getSession();
$user = $session->read('StateUser');
-
-
+
$stateBalancesTable = TableRegistry::getTableLocator()->get('StateBalances');
$stateUserTransactionsTable = TableRegistry::getTableLocator()->get('StateUserTransactions');
$transactionsTable = TableRegistry::getTableLocator()->get('Transactions');
-
$stateBalancesTable->updateBalances($user['id']);
-
+
$gdtSum = 0;
+
$gdtEntries = $this->JsonRequestClient->sendRequestGDT(['email' => $user['email']], 'GdtEntries' . DS . 'sumPerEmailApi');
-
+
if('success' == $gdtEntries['state'] && 'success' == $gdtEntries['data']['state']) {
$gdtSum = intval($gdtEntries['data']['sum']);
} else {
$this->addAdminError('StateBalancesController', 'overview', $gdtEntries, $user['id'] ? $user['id'] : 0);
}
- $stateUserTransactions_total = $stateUserTransactionsTable
- ->find()
- ->select(['id'])
- ->where(['state_user_id' => $user['id']])
- ->contain([]);
$stateUserTransactionsQuery = $stateUserTransactionsTable
->find()
@@ -343,17 +348,18 @@ class AppRequestsController extends AppController
$decay = true;
$transactions = [];
$transactions_from_db = $stateUserTransactionsQuery->toArray();
+
if(count($transactions_from_db)) {
if($orderDirection == 'DESC') {
$transactions_from_db = array_reverse($transactions_from_db);
}
+
$transactions = $transactionsTable->listTransactionsHumanReadable($transactions_from_db, $user, $decay);
if($orderDirection == 'DESC') {
$transactions = array_reverse($transactions);
}
-
- }
+ }
$state_balance = $stateBalancesTable->find()->where(['state_user_id' => $user['id']])->first();
@@ -361,7 +367,7 @@ class AppRequestsController extends AppController
'state' => 'success',
'transactions' => $transactions,
'transactionExecutingCount' => $session->read('Transactions.executing'),
- 'count' => $stateUserTransactions_total->count(),
+ 'count' => $stateUserTransactionsQuery->count(),
'gdtSum' => $gdtSum,
'timeUsed' => microtime(true) - $startTime
];
@@ -375,8 +381,8 @@ class AppRequestsController extends AppController
$body['balance'] = $state_balance->amount;
$body['decay'] = $stateBalancesTable->calculateDecay($state_balance->amount, $state_balance->record_date, $now);
}
-
- $this->set('body', $body);
+
+ $this->set('body', $body);
}
private function acquireAccessToken($session_id)
diff --git a/community_server/src/Controller/JsonRequestHandlerController.php b/community_server/src/Controller/JsonRequestHandlerController.php
index 12e03be8d..65bf48440 100644
--- a/community_server/src/Controller/JsonRequestHandlerController.php
+++ b/community_server/src/Controller/JsonRequestHandlerController.php
@@ -340,12 +340,13 @@ class JsonRequestHandlerController extends AppController {
return;
}
$transaction_body = $transaction->getTransactionBody();
- $transaction_type_name = $transaction_body->getTransactionTypeName();
- $senderUser = null;
- if($transaction_type_name === 'transfer') {
- $senderUser = $transaction_body->getSpecificTransaction()->getSenderUser();
- } else if($transaction_type_name === 'creation') {
- $senderUser = $transaction->getFirstSigningUser();
+ $senderUser = $transaction->getFirstSigningUser();
+ if($transaction_body != null) {
+ $transaction_type_name = $transaction_body->getTransactionTypeName();
+
+ if($transaction_type_name === 'transfer') {
+ $senderUser = $transaction_body->getSpecificTransaction()->getSenderUser();
+ }
}
// send notification email
$noReplyEmail = Configure::read('noReplyEmail');
@@ -373,18 +374,21 @@ class JsonRequestHandlerController extends AppController {
private function putTransaction($transactionBase64) {
$transaction = new Transaction($transactionBase64);
- //echo "after new transaction
";
+
if($transaction->hasErrors()) {
$this->sendEMailTransactionFailed($transaction, 'parse');
return $this->returnJson(['state' => 'error', 'msg' => 'error parsing transaction', 'details' => $transaction->getErrors()]);
}
- //echo "after check on errors
";
+
if(!$transaction->validate()) {
//$transaction_details
$this->sendEMailTransactionFailed($transaction, 'validate');
- return $this->returnJsonSaveError($transaction, ['state' => 'error', 'msg' => 'error validate transaction', 'details' => $transaction->getErrors()]);
+ return $this->returnJsonSaveError($transaction, [
+ 'state' => 'error',
+ 'msg' => 'error validate transaction',
+ 'details' => $transaction->getErrors()
+ ]);
}
- //echo "after validate
";
if ($transaction->save()) {
// success
diff --git a/community_server/src/Controller/StateBalancesController.php b/community_server/src/Controller/StateBalancesController.php
index 0dc9b672d..f16ed407b 100644
--- a/community_server/src/Controller/StateBalancesController.php
+++ b/community_server/src/Controller/StateBalancesController.php
@@ -151,35 +151,6 @@ class StateBalancesController extends AppController
$this->set('gdtSum', $gdtSum);
}
- public function ajaxGetBalance($session_id = 0)
- {
- if(!$session_id) {
- return $this->returnJson(['state' => 'error', 'msg' => 'invalid session id']);
- }
- $login_result = $this->requestLogin($session_id, false);
- if($login_result !== true) {
- return $this->returnJson($login_result);
- }
- $session = $this->getRequest()->getSession();
- $user = $session->read('StateUser');
-
- $this->StateBalances->updateBalances($user['id']);
-
- $state_balance = $this->StateBalances->find()->where(['state_user_id' => $user['id']])->first();
-
- if(!$state_balance) {
- return $this->returnJson(['state' => 'success', 'balance' => 0]);
- }
- $now = new FrozenTime();
-
- return $this->returnJson([
- 'state' => 'success',
- 'balance' => $state_balance->amount,
- 'decay' => $this->StateBalances->calculateDecay($state_balance->amount, $state_balance->record_date, $now),
- 'decay_date' => $now
- ]);
- }
-
public function ajaxGdtOverview()
{
diff --git a/community_server/src/Controller/TransactionsController.php b/community_server/src/Controller/TransactionsController.php
index 90e78b7fb..67526dfcc 100644
--- a/community_server/src/Controller/TransactionsController.php
+++ b/community_server/src/Controller/TransactionsController.php
@@ -7,6 +7,7 @@ use Model\Transactions\Transaction;
use Model\Transactions\TransactionBody;
use Cake\Core\Configure;
+use Cake\I18n\Time;
use Cake\ORM\TableRegistry;
/**
@@ -24,7 +25,7 @@ class TransactionsController extends AppController
parent::initialize();
$this->loadComponent('GradidoNumber');
$this->loadComponent('JsonRpcRequestClient');
- $this->Auth->allow(['decode']);
+ $this->Auth->allow(['decode', 'manualTransaction']);
}
/**
@@ -170,6 +171,78 @@ class TransactionsController extends AppController
$this->set('transaction', $transaction);
}
+ public function manualTransaction()
+ {
+ if ($this->request->is('post')) {
+ $data = $this->request->getData();
+ $type = $data['type'];
+
+ $transaction = new \Proto\Gradido\GradidoTransaction();
+ $transactionBody = new \Proto\Gradido\TransactionBody();
+ $transactionBody->setMemo($data['memo']);
+ $created = new \Proto\Gradido\TimestampSeconds();
+ $now = new Time();
+ $created->setSeconds($now->getTimestamp());
+ $transactionBody->setCreated($created);
+ if($type == "creation") {
+ $creation = new \Proto\Gradido\GradidoCreation();
+ $target_date = new \Proto\Gradido\TimestampSeconds();
+ $target_time = new Time($data['target_date']);
+ $target_date->setSeconds($target_time->getTimestamp());
+ $creation->setTargetDate($target_date);
+ $receiver = new \Proto\Gradido\TransferAmount();
+ $receiver->setAmount(intval($data['amount']));
+ $receiver->setPubkey(hex2bin($data['target_public_key']));
+ $creation->setReceiver($receiver);
+ $transactionBody->setCreation($creation);
+ } else if($type == "transfer") {
+ $transfer = new \Proto\Gradido\GradidoTransfer();
+ $local_transfer = new \Proto\Gradido\LocalTransfer();
+ $sender = new \Proto\Gradido\TransferAmount();
+ $sender->setAmount(intval($data['amount']));
+ $sender->setPubkey(hex2bin($data['sender_public_key']));
+ $local_transfer->setSender($sender);
+ $local_transfer->setReceiver(hex2bin($data['receiver_public_key']));
+ $transfer->setLocal($local_transfer);
+ $transactionBody->setTransfer($transfer);
+ }
+ $body_bytes = $transactionBody->serializeToString();
+ $transaction->setBodyBytes($body_bytes);
+
+ $protoSigMap = new \Proto\Gradido\SignatureMap();
+ $sigPairs = $protoSigMap->getSigPair();
+ //echo "sigPairs: "; var_dump($sigPairs); echo "
";
+ //return null;
+
+ // sign with keys
+ //foreach($keys as $key) {
+ $sigPair = new \Proto\Gradido\SignaturePair();
+ $sigPair->setPubKey(hex2bin($data['signer_public_key']));
+
+ $signature = sodium_crypto_sign_detached($body_bytes, hex2bin($data['signer_private_key']));
+ echo "signature: " . bin2hex($signature). "
";
+ $sigPair->setEd25519($signature);
+
+ $sigPairs[] = $sigPair;
+ // SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING
+ // SODIUM_BASE64_VARIANT_ORIGINAL
+ $transaction->setSigMap($protoSigMap);
+ //var_dump($protoSigMap);
+ $transaction_bin = $transaction->serializeToString();
+// $url_safe = sodium_bin2base64($transaction_bin, sodium_base64_VARIANT_ORIGINAL);
+ $base64 = [
+ //'original' => sodium_bin2base64($transaction_bin, sodium_base64_VARIANT_ORIGINAL),
+ //'original_nopadding' => sodium_bin2base64($transaction_bin, sodium_base64_VARIANT_ORIGINAL_NO_PADDING),
+ //'urlsafe' => sodium_bin2base64($transaction_bin, sodium_base64_VARIANT_URLSAFE),
+ 'urlsafe_nopadding' => sodium_bin2base64($transaction_bin, SODIUM_BASE64_VARIANT_URLSAFE_NO_PADDING),
+ 'php' => base64_encode($transaction_bin)
+
+ ];
+
+ $this->set('base64', $base64);
+ }
+ }
+
public function decode()
{
$this->viewBuilder()->setLayout('frontend');
diff --git a/community_server/src/Model/Messages/Gradido/Key.php b/community_server/src/Model/Messages/Gradido/Key.php
deleted file mode 100644
index b6190304c..000000000
--- a/community_server/src/Model/Messages/Gradido/Key.php
+++ /dev/null
@@ -1,96 +0,0 @@
-model.messages.gradido.Key
- */
-class Key extends \Google\Protobuf\Internal\Message
-{
- protected $key;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type string $ed25519
- * ed25519 signature (libsodium default)
- * @type string $ed25519_ref10
- * ed25519 ref10 signature
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\BasicTypes::initOnce();
- parent::__construct($data);
- }
-
- /**
- * ed25519 signature (libsodium default)
- *
- * Generated from protobuf field bytes ed25519 = 2;
- * @return string
- */
- public function getEd25519()
- {
- return $this->readOneof(2);
- }
-
- /**
- * ed25519 signature (libsodium default)
- *
- * Generated from protobuf field bytes ed25519 = 2;
- * @param string $var
- * @return $this
- */
- public function setEd25519($var)
- {
- GPBUtil::checkString($var, False);
- $this->writeOneof(2, $var);
-
- return $this;
- }
-
- /**
- * ed25519 ref10 signature
- *
- * Generated from protobuf field bytes ed25519_ref10 = 3;
- * @return string
- */
- public function getEd25519Ref10()
- {
- return $this->readOneof(3);
- }
-
- /**
- * ed25519 ref10 signature
- *
- * Generated from protobuf field bytes ed25519_ref10 = 3;
- * @param string $var
- * @return $this
- */
- public function setEd25519Ref10($var)
- {
- GPBUtil::checkString($var, False);
- $this->writeOneof(3, $var);
-
- return $this;
- }
-
- /**
- * @return string
- */
- public function getKey()
- {
- return $this->whichOneof("key");
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/ReceiverAmount.php b/community_server/src/Model/Messages/Gradido/ReceiverAmount.php
deleted file mode 100644
index 240c5a6fe..000000000
--- a/community_server/src/Model/Messages/Gradido/ReceiverAmount.php
+++ /dev/null
@@ -1,85 +0,0 @@
-model.messages.gradido.ReceiverAmount
- */
-class ReceiverAmount extends \Google\Protobuf\Internal\Message
-{
- /**
- * Generated from protobuf field bytes ed25519_receiver_pubkey = 1;
- */
- private $ed25519_receiver_pubkey = '';
- /**
- * Generated from protobuf field sint64 amount = 2;
- */
- private $amount = 0;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type string $ed25519_receiver_pubkey
- * @type int|string $amount
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\BasicTypes::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Generated from protobuf field bytes ed25519_receiver_pubkey = 1;
- * @return string
- */
- public function getEd25519ReceiverPubkey()
- {
- return $this->ed25519_receiver_pubkey;
- }
-
- /**
- * Generated from protobuf field bytes ed25519_receiver_pubkey = 1;
- * @param string $var
- * @return $this
- */
- public function setEd25519ReceiverPubkey($var)
- {
- GPBUtil::checkString($var, False);
- $this->ed25519_receiver_pubkey = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field sint64 amount = 2;
- * @return int|string
- */
- public function getAmount()
- {
- return $this->amount;
- }
-
- /**
- * Generated from protobuf field sint64 amount = 2;
- * @param int|string $var
- * @return $this
- */
- public function setAmount($var)
- {
- GPBUtil::checkInt64($var);
- $this->amount = $var;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/SenderAmount.php b/community_server/src/Model/Messages/Gradido/SenderAmount.php
deleted file mode 100644
index 52a41f71f..000000000
--- a/community_server/src/Model/Messages/Gradido/SenderAmount.php
+++ /dev/null
@@ -1,119 +0,0 @@
-model.messages.gradido.SenderAmount
- */
-class SenderAmount extends \Google\Protobuf\Internal\Message
-{
- /**
- * Generated from protobuf field bytes ed25519_sender_pubkey = 1;
- */
- private $ed25519_sender_pubkey = '';
- /**
- * Generated from protobuf field sint64 amount = 2;
- */
- private $amount = 0;
- /**
- * sender balance after transaction, including perishability
- *
- * Generated from protobuf field sint64 senderFinalBalance = 3;
- */
- private $senderFinalBalance = 0;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type string $ed25519_sender_pubkey
- * @type int|string $amount
- * @type int|string $senderFinalBalance
- * sender balance after transaction, including perishability
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\BasicTypes::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Generated from protobuf field bytes ed25519_sender_pubkey = 1;
- * @return string
- */
- public function getEd25519SenderPubkey()
- {
- return $this->ed25519_sender_pubkey;
- }
-
- /**
- * Generated from protobuf field bytes ed25519_sender_pubkey = 1;
- * @param string $var
- * @return $this
- */
- public function setEd25519SenderPubkey($var)
- {
- GPBUtil::checkString($var, False);
- $this->ed25519_sender_pubkey = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field sint64 amount = 2;
- * @return int|string
- */
- public function getAmount()
- {
- return $this->amount;
- }
-
- /**
- * Generated from protobuf field sint64 amount = 2;
- * @param int|string $var
- * @return $this
- */
- public function setAmount($var)
- {
- GPBUtil::checkInt64($var);
- $this->amount = $var;
-
- return $this;
- }
-
- /**
- * sender balance after transaction, including perishability
- *
- * Generated from protobuf field sint64 senderFinalBalance = 3;
- * @return int|string
- */
- public function getSenderFinalBalance()
- {
- return $this->senderFinalBalance;
- }
-
- /**
- * sender balance after transaction, including perishability
- *
- * Generated from protobuf field sint64 senderFinalBalance = 3;
- * @param int|string $var
- * @return $this
- */
- public function setSenderFinalBalance($var)
- {
- GPBUtil::checkInt64($var);
- $this->senderFinalBalance = $var;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/SignatureMap.php b/community_server/src/Model/Messages/Gradido/SignatureMap.php
deleted file mode 100644
index 228282747..000000000
--- a/community_server/src/Model/Messages/Gradido/SignatureMap.php
+++ /dev/null
@@ -1,65 +0,0 @@
-model.messages.gradido.SignatureMap
- */
-class SignatureMap extends \Google\Protobuf\Internal\Message
-{
- /**
- * Each signature pair corresponds to a unique Key required to sign the transaction.
- *
- * Generated from protobuf field repeated .model.messages.gradido.SignaturePair sigPair = 1;
- */
- private $sigPair;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type \Model\Messages\Gradido\SignaturePair[]|\Google\Protobuf\Internal\RepeatedField $sigPair
- * Each signature pair corresponds to a unique Key required to sign the transaction.
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\BasicTypes::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Each signature pair corresponds to a unique Key required to sign the transaction.
- *
- * Generated from protobuf field repeated .model.messages.gradido.SignaturePair sigPair = 1;
- * @return \Google\Protobuf\Internal\RepeatedField
- */
- public function getSigPair()
- {
- return $this->sigPair;
- }
-
- /**
- * Each signature pair corresponds to a unique Key required to sign the transaction.
- *
- * Generated from protobuf field repeated .model.messages.gradido.SignaturePair sigPair = 1;
- * @param \Model\Messages\Gradido\SignaturePair[]|\Google\Protobuf\Internal\RepeatedField $var
- * @return $this
- */
- public function setSigPair($var)
- {
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Model\Messages\Gradido\SignaturePair::class);
- $this->sigPair = $arr;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/SignaturePair.php b/community_server/src/Model/Messages/Gradido/SignaturePair.php
deleted file mode 100644
index 203eb5677..000000000
--- a/community_server/src/Model/Messages/Gradido/SignaturePair.php
+++ /dev/null
@@ -1,123 +0,0 @@
-model.messages.gradido.SignaturePair
- */
-class SignaturePair extends \Google\Protobuf\Internal\Message
-{
- /**
- * Generated from protobuf field bytes pubKey = 1;
- */
- private $pubKey = '';
- protected $signature;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type string $pubKey
- * @type string $ed25519
- * ed25519 signature (libsodium default)
- * @type string $ed25519_ref10
- * ed25519 ref10 signature
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\BasicTypes::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Generated from protobuf field bytes pubKey = 1;
- * @return string
- */
- public function getPubKey()
- {
- return $this->pubKey;
- }
-
- /**
- * Generated from protobuf field bytes pubKey = 1;
- * @param string $var
- * @return $this
- */
- public function setPubKey($var)
- {
- GPBUtil::checkString($var, False);
- $this->pubKey = $var;
-
- return $this;
- }
-
- /**
- * ed25519 signature (libsodium default)
- *
- * Generated from protobuf field bytes ed25519 = 2;
- * @return string
- */
- public function getEd25519()
- {
- return $this->readOneof(2);
- }
-
- /**
- * ed25519 signature (libsodium default)
- *
- * Generated from protobuf field bytes ed25519 = 2;
- * @param string $var
- * @return $this
- */
- public function setEd25519($var)
- {
- GPBUtil::checkString($var, False);
- $this->writeOneof(2, $var);
-
- return $this;
- }
-
- /**
- * ed25519 ref10 signature
- *
- * Generated from protobuf field bytes ed25519_ref10 = 3;
- * @return string
- */
- public function getEd25519Ref10()
- {
- return $this->readOneof(3);
- }
-
- /**
- * ed25519 ref10 signature
- *
- * Generated from protobuf field bytes ed25519_ref10 = 3;
- * @param string $var
- * @return $this
- */
- public function setEd25519Ref10($var)
- {
- GPBUtil::checkString($var, False);
- $this->writeOneof(3, $var);
-
- return $this;
- }
-
- /**
- * @return string
- */
- public function getSignature()
- {
- return $this->whichOneof("signature");
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/StateCreateGroup.php b/community_server/src/Model/Messages/Gradido/StateCreateGroup.php
deleted file mode 100644
index 4273ef93d..000000000
--- a/community_server/src/Model/Messages/Gradido/StateCreateGroup.php
+++ /dev/null
@@ -1,114 +0,0 @@
-model.messages.gradido.StateCreateGroup
- */
-class StateCreateGroup extends \Google\Protobuf\Internal\Message
-{
- /**
- * Generated from protobuf field string name = 1;
- */
- private $name = '';
- /**
- * Generated from protobuf field .model.messages.gradido.Key groupPublicKey = 2;
- */
- private $groupPublicKey = null;
- /**
- * Generated from protobuf field .model.messages.gradido.Key parentGroupPublicKey = 3;
- */
- private $parentGroupPublicKey = null;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type string $name
- * @type \Model\Messages\Gradido\Key $groupPublicKey
- * @type \Model\Messages\Gradido\Key $parentGroupPublicKey
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\StateCreateGroup::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Generated from protobuf field string name = 1;
- * @return string
- */
- public function getName()
- {
- return $this->name;
- }
-
- /**
- * Generated from protobuf field string name = 1;
- * @param string $var
- * @return $this
- */
- public function setName($var)
- {
- GPBUtil::checkString($var, True);
- $this->name = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key groupPublicKey = 2;
- * @return \Model\Messages\Gradido\Key
- */
- public function getGroupPublicKey()
- {
- return $this->groupPublicKey;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key groupPublicKey = 2;
- * @param \Model\Messages\Gradido\Key $var
- * @return $this
- */
- public function setGroupPublicKey($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\Key::class);
- $this->groupPublicKey = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key parentGroupPublicKey = 3;
- * @return \Model\Messages\Gradido\Key
- */
- public function getParentGroupPublicKey()
- {
- return $this->parentGroupPublicKey;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key parentGroupPublicKey = 3;
- * @param \Model\Messages\Gradido\Key $var
- * @return $this
- */
- public function setParentGroupPublicKey($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\Key::class);
- $this->parentGroupPublicKey = $var;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/StateGroupChangeParent.php b/community_server/src/Model/Messages/Gradido/StateGroupChangeParent.php
deleted file mode 100644
index c5371d76c..000000000
--- a/community_server/src/Model/Messages/Gradido/StateGroupChangeParent.php
+++ /dev/null
@@ -1,114 +0,0 @@
-model.messages.gradido.StateGroupChangeParent
- */
-class StateGroupChangeParent extends \Google\Protobuf\Internal\Message
-{
- /**
- * Generated from protobuf field .model.messages.gradido.Key groupPublicKey = 1;
- */
- private $groupPublicKey = null;
- /**
- * Generated from protobuf field .model.messages.gradido.Key newParentGroupPublicKey = 2;
- */
- private $newParentGroupPublicKey = null;
- /**
- * Generated from protobuf field .model.messages.gradido.Key oldParentGroupPublicKey = 3;
- */
- private $oldParentGroupPublicKey = null;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type \Model\Messages\Gradido\Key $groupPublicKey
- * @type \Model\Messages\Gradido\Key $newParentGroupPublicKey
- * @type \Model\Messages\Gradido\Key $oldParentGroupPublicKey
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\StateGroupChangeParent::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key groupPublicKey = 1;
- * @return \Model\Messages\Gradido\Key
- */
- public function getGroupPublicKey()
- {
- return $this->groupPublicKey;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key groupPublicKey = 1;
- * @param \Model\Messages\Gradido\Key $var
- * @return $this
- */
- public function setGroupPublicKey($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\Key::class);
- $this->groupPublicKey = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key newParentGroupPublicKey = 2;
- * @return \Model\Messages\Gradido\Key
- */
- public function getNewParentGroupPublicKey()
- {
- return $this->newParentGroupPublicKey;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key newParentGroupPublicKey = 2;
- * @param \Model\Messages\Gradido\Key $var
- * @return $this
- */
- public function setNewParentGroupPublicKey($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\Key::class);
- $this->newParentGroupPublicKey = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key oldParentGroupPublicKey = 3;
- * @return \Model\Messages\Gradido\Key
- */
- public function getOldParentGroupPublicKey()
- {
- return $this->oldParentGroupPublicKey;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Key oldParentGroupPublicKey = 3;
- * @param \Model\Messages\Gradido\Key $var
- * @return $this
- */
- public function setOldParentGroupPublicKey($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\Key::class);
- $this->oldParentGroupPublicKey = $var;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/Timestamp.php b/community_server/src/Model/Messages/Gradido/Timestamp.php
deleted file mode 100644
index 19721729b..000000000
--- a/community_server/src/Model/Messages/Gradido/Timestamp.php
+++ /dev/null
@@ -1,101 +0,0 @@
-model.messages.gradido.Timestamp
- */
-class Timestamp extends \Google\Protobuf\Internal\Message
-{
- /**
- * Number of complete seconds since the start of the epoch
- *
- * Generated from protobuf field int64 seconds = 1;
- */
- private $seconds = 0;
- /**
- * Number of nanoseconds since the start of the last second
- *
- * Generated from protobuf field int32 nanos = 2;
- */
- private $nanos = 0;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type int|string $seconds
- * Number of complete seconds since the start of the epoch
- * @type int $nanos
- * Number of nanoseconds since the start of the last second
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\BasicTypes::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Number of complete seconds since the start of the epoch
- *
- * Generated from protobuf field int64 seconds = 1;
- * @return int|string
- */
- public function getSeconds()
- {
- return $this->seconds;
- }
-
- /**
- * Number of complete seconds since the start of the epoch
- *
- * Generated from protobuf field int64 seconds = 1;
- * @param int|string $var
- * @return $this
- */
- public function setSeconds($var)
- {
- GPBUtil::checkInt64($var);
- $this->seconds = $var;
-
- return $this;
- }
-
- /**
- * Number of nanoseconds since the start of the last second
- *
- * Generated from protobuf field int32 nanos = 2;
- * @return int
- */
- public function getNanos()
- {
- return $this->nanos;
- }
-
- /**
- * Number of nanoseconds since the start of the last second
- *
- * Generated from protobuf field int32 nanos = 2;
- * @param int $var
- * @return $this
- */
- public function setNanos($var)
- {
- GPBUtil::checkInt32($var);
- $this->nanos = $var;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/TimestampSeconds.php b/community_server/src/Model/Messages/Gradido/TimestampSeconds.php
deleted file mode 100644
index 2a588a312..000000000
--- a/community_server/src/Model/Messages/Gradido/TimestampSeconds.php
+++ /dev/null
@@ -1,67 +0,0 @@
-model.messages.gradido.TimestampSeconds
- */
-class TimestampSeconds extends \Google\Protobuf\Internal\Message
-{
- /**
- * Number of complete seconds since the start of the epoch
- *
- * Generated from protobuf field int64 seconds = 1;
- */
- private $seconds = 0;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type int|string $seconds
- * Number of complete seconds since the start of the epoch
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\BasicTypes::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Number of complete seconds since the start of the epoch
- *
- * Generated from protobuf field int64 seconds = 1;
- * @return int|string
- */
- public function getSeconds()
- {
- return $this->seconds;
- }
-
- /**
- * Number of complete seconds since the start of the epoch
- *
- * Generated from protobuf field int64 seconds = 1;
- * @param int|string $var
- * @return $this
- */
- public function setSeconds($var)
- {
- GPBUtil::checkInt64($var);
- $this->seconds = $var;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/Transaction.php b/community_server/src/Model/Messages/Gradido/Transaction.php
deleted file mode 100644
index 065cd80bb..000000000
--- a/community_server/src/Model/Messages/Gradido/Transaction.php
+++ /dev/null
@@ -1,166 +0,0 @@
-model.messages.gradido.Transaction
- */
-class Transaction extends \Google\Protobuf\Internal\Message
-{
- /**
- * Generated from protobuf field uint64 id = 1;
- */
- private $id = 0;
- /**
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds received = 2;
- */
- private $received = null;
- /**
- * Generated from protobuf field .model.messages.gradido.SignatureMap sigMap = 3;
- */
- private $sigMap = null;
- /**
- * Generated from protobuf field bytes txHash = 4;
- */
- private $txHash = '';
- /**
- * Generated from protobuf field bytes bodyBytes = 5;
- */
- private $bodyBytes = '';
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type int|string $id
- * @type \Model\Messages\Gradido\TimestampSeconds $received
- * @type \Model\Messages\Gradido\SignatureMap $sigMap
- * @type string $txHash
- * @type string $bodyBytes
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\Transaction::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Generated from protobuf field uint64 id = 1;
- * @return int|string
- */
- public function getId()
- {
- return $this->id;
- }
-
- /**
- * Generated from protobuf field uint64 id = 1;
- * @param int|string $var
- * @return $this
- */
- public function setId($var)
- {
- GPBUtil::checkUint64($var);
- $this->id = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds received = 2;
- * @return \Model\Messages\Gradido\TimestampSeconds
- */
- public function getReceived()
- {
- return $this->received;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds received = 2;
- * @param \Model\Messages\Gradido\TimestampSeconds $var
- * @return $this
- */
- public function setReceived($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\TimestampSeconds::class);
- $this->received = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.SignatureMap sigMap = 3;
- * @return \Model\Messages\Gradido\SignatureMap
- */
- public function getSigMap()
- {
- return $this->sigMap;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.SignatureMap sigMap = 3;
- * @param \Model\Messages\Gradido\SignatureMap $var
- * @return $this
- */
- public function setSigMap($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\SignatureMap::class);
- $this->sigMap = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field bytes txHash = 4;
- * @return string
- */
- public function getTxHash()
- {
- return $this->txHash;
- }
-
- /**
- * Generated from protobuf field bytes txHash = 4;
- * @param string $var
- * @return $this
- */
- public function setTxHash($var)
- {
- GPBUtil::checkString($var, False);
- $this->txHash = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field bytes bodyBytes = 5;
- * @return string
- */
- public function getBodyBytes()
- {
- return $this->bodyBytes;
- }
-
- /**
- * Generated from protobuf field bytes bodyBytes = 5;
- * @param string $var
- * @return $this
- */
- public function setBodyBytes($var)
- {
- GPBUtil::checkString($var, False);
- $this->bodyBytes = $var;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/TransactionBody.php b/community_server/src/Model/Messages/Gradido/TransactionBody.php
deleted file mode 100644
index 3452d4251..000000000
--- a/community_server/src/Model/Messages/Gradido/TransactionBody.php
+++ /dev/null
@@ -1,193 +0,0 @@
-model.messages.gradido.TransactionBody
- */
-class TransactionBody extends \Google\Protobuf\Internal\Message
-{
- /**
- * max 150 chars
- *
- * Generated from protobuf field string memo = 1;
- */
- private $memo = '';
- /**
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds created = 2;
- */
- private $created = null;
- protected $data;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type string $memo
- * max 150 chars
- * @type \Model\Messages\Gradido\TimestampSeconds $created
- * @type \Model\Messages\Gradido\StateCreateGroup $createGroup
- * @type \Model\Messages\Gradido\StateGroupChangeParent $groupChangeParent
- * @type \Model\Messages\Gradido\Transfer $transfer
- * @type \Model\Messages\Gradido\TransactionCreation $creation
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\TransactionBody::initOnce();
- parent::__construct($data);
- }
-
- /**
- * max 150 chars
- *
- * Generated from protobuf field string memo = 1;
- * @return string
- */
- public function getMemo()
- {
- return $this->memo;
- }
-
- /**
- * max 150 chars
- *
- * Generated from protobuf field string memo = 1;
- * @param string $var
- * @return $this
- */
- public function setMemo($var)
- {
- GPBUtil::checkString($var, True);
- $this->memo = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds created = 2;
- * @return \Model\Messages\Gradido\TimestampSeconds
- */
- public function getCreated()
- {
- return $this->created;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds created = 2;
- * @param \Model\Messages\Gradido\TimestampSeconds $var
- * @return $this
- */
- public function setCreated($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\TimestampSeconds::class);
- $this->created = $var;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.StateCreateGroup createGroup = 6;
- * @return \Model\Messages\Gradido\StateCreateGroup
- */
- public function getCreateGroup()
- {
- return $this->readOneof(6);
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.StateCreateGroup createGroup = 6;
- * @param \Model\Messages\Gradido\StateCreateGroup $var
- * @return $this
- */
- public function setCreateGroup($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\StateCreateGroup::class);
- $this->writeOneof(6, $var);
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.StateGroupChangeParent groupChangeParent = 7;
- * @return \Model\Messages\Gradido\StateGroupChangeParent
- */
- public function getGroupChangeParent()
- {
- return $this->readOneof(7);
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.StateGroupChangeParent groupChangeParent = 7;
- * @param \Model\Messages\Gradido\StateGroupChangeParent $var
- * @return $this
- */
- public function setGroupChangeParent($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\StateGroupChangeParent::class);
- $this->writeOneof(7, $var);
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Transfer transfer = 8;
- * @return \Model\Messages\Gradido\Transfer
- */
- public function getTransfer()
- {
- return $this->readOneof(8);
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.Transfer transfer = 8;
- * @param \Model\Messages\Gradido\Transfer $var
- * @return $this
- */
- public function setTransfer($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\Transfer::class);
- $this->writeOneof(8, $var);
-
- return $this;
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.TransactionCreation creation = 9;
- * @return \Model\Messages\Gradido\TransactionCreation
- */
- public function getCreation()
- {
- return $this->readOneof(9);
- }
-
- /**
- * Generated from protobuf field .model.messages.gradido.TransactionCreation creation = 9;
- * @param \Model\Messages\Gradido\TransactionCreation $var
- * @return $this
- */
- public function setCreation($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\TransactionCreation::class);
- $this->writeOneof(9, $var);
-
- return $this;
- }
-
- /**
- * @return string
- */
- public function getData()
- {
- return $this->whichOneof("data");
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/TransactionCreation.php b/community_server/src/Model/Messages/Gradido/TransactionCreation.php
deleted file mode 100644
index ae5f86e07..000000000
--- a/community_server/src/Model/Messages/Gradido/TransactionCreation.php
+++ /dev/null
@@ -1,136 +0,0 @@
-model.messages.gradido.TransactionCreation
- */
-class TransactionCreation extends \Google\Protobuf\Internal\Message
-{
- /**
- * 40 Byte
- *
- * Generated from protobuf field .model.messages.gradido.ReceiverAmount receiverAmount = 1;
- */
- private $receiverAmount = null;
- /**
- * 4 Byte
- *
- * Generated from protobuf field sint32 ident_hash = 2;
- */
- private $ident_hash = 0;
- /**
- * 8 Byte
- *
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds target_date = 3;
- */
- private $target_date = null;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type \Model\Messages\Gradido\ReceiverAmount $receiverAmount
- * 40 Byte
- * @type int $ident_hash
- * 4 Byte
- * @type \Model\Messages\Gradido\TimestampSeconds $target_date
- * 8 Byte
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\TransactionCreation::initOnce();
- parent::__construct($data);
- }
-
- /**
- * 40 Byte
- *
- * Generated from protobuf field .model.messages.gradido.ReceiverAmount receiverAmount = 1;
- * @return \Model\Messages\Gradido\ReceiverAmount
- */
- public function getReceiverAmount()
- {
- return $this->receiverAmount;
- }
-
- /**
- * 40 Byte
- *
- * Generated from protobuf field .model.messages.gradido.ReceiverAmount receiverAmount = 1;
- * @param \Model\Messages\Gradido\ReceiverAmount $var
- * @return $this
- */
- public function setReceiverAmount($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\ReceiverAmount::class);
- $this->receiverAmount = $var;
-
- return $this;
- }
-
- /**
- * 4 Byte
- *
- * Generated from protobuf field sint32 ident_hash = 2;
- * @return int
- */
- public function getIdentHash()
- {
- return $this->ident_hash;
- }
-
- /**
- * 4 Byte
- *
- * Generated from protobuf field sint32 ident_hash = 2;
- * @param int $var
- * @return $this
- */
- public function setIdentHash($var)
- {
- GPBUtil::checkInt32($var);
- $this->ident_hash = $var;
-
- return $this;
- }
-
- /**
- * 8 Byte
- *
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds target_date = 3;
- * @return \Model\Messages\Gradido\TimestampSeconds
- */
- public function getTargetDate()
- {
- return $this->target_date;
- }
-
- /**
- * 8 Byte
- *
- * Generated from protobuf field .model.messages.gradido.TimestampSeconds target_date = 3;
- * @param \Model\Messages\Gradido\TimestampSeconds $var
- * @return $this
- */
- public function setTargetDate($var)
- {
- GPBUtil::checkMessage($var, \Model\Messages\Gradido\TimestampSeconds::class);
- $this->target_date = $var;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Messages/Gradido/Transfer.php b/community_server/src/Model/Messages/Gradido/Transfer.php
deleted file mode 100644
index 2c031d02b..000000000
--- a/community_server/src/Model/Messages/Gradido/Transfer.php
+++ /dev/null
@@ -1,85 +0,0 @@
-model.messages.gradido.Transfer
- */
-class Transfer extends \Google\Protobuf\Internal\Message
-{
- /**
- * Generated from protobuf field repeated .model.messages.gradido.SenderAmount senderAmounts = 1;
- */
- private $senderAmounts;
- /**
- * Generated from protobuf field repeated .model.messages.gradido.ReceiverAmount receiverAmounts = 2;
- */
- private $receiverAmounts;
-
- /**
- * Constructor.
- *
- * @param array $data {
- * Optional. Data for populating the Message object.
- *
- * @type \Model\Messages\Gradido\SenderAmount[]|\Google\Protobuf\Internal\RepeatedField $senderAmounts
- * @type \Model\Messages\Gradido\ReceiverAmount[]|\Google\Protobuf\Internal\RepeatedField $receiverAmounts
- * }
- */
- public function __construct($data = NULL) {
- \GPBMetadata\Transfer::initOnce();
- parent::__construct($data);
- }
-
- /**
- * Generated from protobuf field repeated .model.messages.gradido.SenderAmount senderAmounts = 1;
- * @return \Google\Protobuf\Internal\RepeatedField
- */
- public function getSenderAmounts()
- {
- return $this->senderAmounts;
- }
-
- /**
- * Generated from protobuf field repeated .model.messages.gradido.SenderAmount senderAmounts = 1;
- * @param \Model\Messages\Gradido\SenderAmount[]|\Google\Protobuf\Internal\RepeatedField $var
- * @return $this
- */
- public function setSenderAmounts($var)
- {
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Model\Messages\Gradido\SenderAmount::class);
- $this->senderAmounts = $arr;
-
- return $this;
- }
-
- /**
- * Generated from protobuf field repeated .model.messages.gradido.ReceiverAmount receiverAmounts = 2;
- * @return \Google\Protobuf\Internal\RepeatedField
- */
- public function getReceiverAmounts()
- {
- return $this->receiverAmounts;
- }
-
- /**
- * Generated from protobuf field repeated .model.messages.gradido.ReceiverAmount receiverAmounts = 2;
- * @param \Model\Messages\Gradido\ReceiverAmount[]|\Google\Protobuf\Internal\RepeatedField $var
- * @return $this
- */
- public function setReceiverAmounts($var)
- {
- $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Model\Messages\Gradido\ReceiverAmount::class);
- $this->receiverAmounts = $arr;
-
- return $this;
- }
-
-}
-
diff --git a/community_server/src/Model/Transactions/Transaction.php b/community_server/src/Model/Transactions/Transaction.php
index 40be13cd3..db7ed9e5b 100644
--- a/community_server/src/Model/Transactions/Transaction.php
+++ b/community_server/src/Model/Transactions/Transaction.php
@@ -25,7 +25,7 @@ class Transaction extends TransactionBase {
//$transactionBin = base64_decode($base64Data, true);
//if($transactionBin == false) {
//sodium_base64_VARIANT_URLSAFE_NO_PADDING
- if(is_a($base64Data, '\Proto\Gradido\Transaction')) {
+ if(is_a($base64Data, '\Proto\Gradido\GradidoTransaction')) {
$this->mProtoTransaction = $base64Data;
$this->mTransactionBody = new TransactionBody($this->mProtoTransaction->getBodyBytes());
return;
@@ -93,7 +93,11 @@ class Transaction extends TransactionBase {
return $this->mTransactionBody;
}
- public function getFirstPublic() {
+ public function getFirstPublic()
+ {
+ if(!$this->mProtoTransaction || !$this->mProtoTransaction->getSigMap()) {
+ return '';
+ }
$sigPairs = $this->mProtoTransaction->getSigMap()->getSigPair();
return $sigPairs[0]->getPubKey();
}
@@ -111,6 +115,7 @@ class Transaction extends TransactionBase {
$sigMap = $this->mProtoTransaction->getSigMap();
if(!$sigMap) {
$this->addError('Transaction', 'signature map is zero');
+ //var_dump($this->mProtoTransaction);
return false;
}
//var_dump($sigMap);
diff --git a/community_server/src/Model/Transactions/TransactionTransfer.php b/community_server/src/Model/Transactions/TransactionTransfer.php
index 4f3f4e88c..c36583c13 100644
--- a/community_server/src/Model/Transactions/TransactionTransfer.php
+++ b/community_server/src/Model/Transactions/TransactionTransfer.php
@@ -58,7 +58,7 @@ class TransactionTransfer extends TransactionBase {
//$this->addError('TransactionTransfer::validate', 'not implemented yet');
//return false;
//$time = microtime(true);
- static $functionName = 'TransactionCreation::validate';
+ static $functionName = 'TransactionTransfer::validate';
$sigPubHexs = [];
foreach($sigPairs as $sigPair)
diff --git a/community_server/src/Template/Transactions/manual_transaction.ctp b/community_server/src/Template/Transactions/manual_transaction.ctp
new file mode 100644
index 000000000..30bda1175
--- /dev/null
+++ b/community_server/src/Template/Transactions/manual_transaction.ctp
@@ -0,0 +1,63 @@
+loadHelper('Form', [
+ 'templates' => 'horizontal_form',
+]);
+$now = new \DateTime;
+?>
+ 0) : ?>
+
+
+
+ -
+ = var_dump($error); ?>
+
+
+
+
+
+
+
+
+
+
+
+ $value) : ?>
+ - = $name ?>: = $value ?>
+
+
+
+
\ No newline at end of file
diff --git a/community_server/tests/Fixture/CommunityProfilesFixture.php b/community_server/tests/Fixture/CommunityProfilesFixture.php
index 1259d6e25..0fa7ed764 100644
--- a/community_server/tests/Fixture/CommunityProfilesFixture.php
+++ b/community_server/tests/Fixture/CommunityProfilesFixture.php
@@ -23,8 +23,7 @@ class CommunityProfilesFixture extends TestFixture
'state_user_id' => ['type' => 'index', 'columns' => ['state_user_id'], 'length' => []],
],
'_constraints' => [
- 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
- 'community_profiles_ibfk_1' => ['type' => 'foreign', 'columns' => ['state_user_id'], 'references' => ['state_users', 'id'], 'update' => 'restrict', 'delete' => 'restrict', 'length' => []],
+ 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []]
],
'_options' => [
'engine' => 'InnoDB',
diff --git a/community_server/tests/Fixture/Migrations2Fixture.php b/community_server/tests/Fixture/Migrations2Fixture.php
new file mode 100644
index 000000000..c8608cd18
--- /dev/null
+++ b/community_server/tests/Fixture/Migrations2Fixture.php
@@ -0,0 +1,45 @@
+ ['type' => 'integer', 'length' => 10, 'unsigned' => true, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
+ 'db_version' => ['type' => 'integer', 'length' => 11, 'unsigned' => false, 'null' => true, 'default' => '0', 'comment' => '', 'precision' => null, 'autoIncrement' => null],
+ '_constraints' => [
+ 'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
+ ],
+ '_options' => [
+ 'engine' => 'InnoDB',
+ 'collation' => 'utf8mb4_unicode_ci'
+ ],
+ ];
+ // @codingStandardsIgnoreEnd
+ /**
+ * Init method
+ *
+ * @return void
+ */
+ public function init()
+ {
+ $this->table = "migrations";
+ $this->records = [
+ [
+ 'id' => 1,
+ 'db_version' => 2,
+ ],
+ ];
+ parent::init();
+ }
+}
diff --git a/community_server/tests/Fixture/StateBalancesFixture.php b/community_server/tests/Fixture/StateBalancesFixture.php
index f4a6fd7fc..015366c80 100644
--- a/community_server/tests/Fixture/StateBalancesFixture.php
+++ b/community_server/tests/Fixture/StateBalancesFixture.php
@@ -6,7 +6,7 @@ use Cake\TestSuite\Fixture\TestFixture;
/**
* StateBalancesFixture
*/
-class StateBalancesFixture extends TestFixture
+class StateBalancesFixture extends BaseTestFixture
{
/**
* Fields
@@ -36,8 +36,11 @@ class StateBalancesFixture extends TestFixture
*/
public function init()
{
- $this->records = [
+ $sql = [
+ [4, 4, '2021-05-27 17:47:50', '2021-05-27 17:47:50', 28808497],
+ [5, 1, '2021-05-27 17:47:51', '2021-05-27 17:47:50', 9823963]
];
+ $this->records = $this->sqlEntrysToRecords($sql, $this->fields);
parent::init();
}
}
diff --git a/community_server/tests/Fixture/TransactionCreationsFixture.php b/community_server/tests/Fixture/TransactionCreationsFixture.php
index 1833385b4..4221e8729 100644
--- a/community_server/tests/Fixture/TransactionCreationsFixture.php
+++ b/community_server/tests/Fixture/TransactionCreationsFixture.php
@@ -1,8 +1,6 @@
['type' => 'integer', 'length' => 10, 'unsigned' => true, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'state_user_id' => ['type' => 'integer', 'length' => 10, 'unsigned' => true, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
'amount' => ['type' => 'biginteger', 'length' => 20, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null, 'autoIncrement' => null],
- 'ident_hash' => ['type' => 'binary', 'length' => 32, 'null' => false, 'default' => null, 'comment' => '', 'precision' => null],
'target_date' => ['type' => 'timestamp', 'length' => null, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null],
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
@@ -37,9 +34,9 @@ class TransactionCreationsFixture extends BaseTestFixture
*/
public function init()
{
- $sql = [
- [2, 1, 4, 10000000, '0000000000000000000000000000000000000000000000000000000000000000', '2021-01-01 00:00:00'],
- [3, 2, 1, 10000000, '0000000000000000000000000000000000000000000000000000000000000000', '2021-01-01 00:00:00']
+ $sql = [
+ [2, 1, 4, 10000000, '2021-01-01 00:00:00'],
+ [3, 2, 1, 10000000, '2021-01-01 00:00:00']
];
$this->records = $this->sqlEntrysToRecords($sql, $this->fields);
parent::init();
diff --git a/community_server/tests/TestCase/Controller/AppControllerTest.php b/community_server/tests/TestCase/Controller/AppControllerTest.php
deleted file mode 100644
index 502ed46da..000000000
--- a/community_server/tests/TestCase/Controller/AppControllerTest.php
+++ /dev/null
@@ -1,46 +0,0 @@
-session(['StateUser.id' => 1]);
- $this->get('/');
- $this->assertSession(1200, 'StateUser.balance');
- //$this->markTestIncomplete('Not implemented yet.');
- }
-
-
-}
diff --git a/community_server/tests/TestCase/Controller/AppRequestControllerTest.php b/community_server/tests/TestCase/Controller/AppRequestControllerTest.php
new file mode 100644
index 000000000..118f25a32
--- /dev/null
+++ b/community_server/tests/TestCase/Controller/AppRequestControllerTest.php
@@ -0,0 +1,303 @@
+session([
+ 'session_id' => $session_id,
+ 'Transaction' => ['pending' => 0, 'executing' => 0],
+ 'StateUser' => [
+ 'id' => 1,
+ 'email_checked' => 1,
+ 'public_hex' => 'f7f4a49a4ac10379f8b9ddcb731c4d9ec495e6edd16075f52672cd25e3179f0f'
+ ]
+ ]);
+
+ $response = $this->getAndParseWithoutCompare('/api/get-balance/' . $session_id);
+ $this->assertEquals('success', $response->state);
+ $this->assertEquals(9100000, $response->balance);
+ $this->assertLessThan(9100000, $response->decay);
+
+ }
+
+ public function testGetBalance2()
+ {
+ $session_id = rand();
+ $this->session([
+ 'session_id' => $session_id,
+ 'Transaction' => ['pending' => 0, 'executing' => 0],
+ 'StateUser' => [
+ 'id' => 3,
+ 'email_checked' => 1,
+ 'public_hex' => '131c7f68dd94b2be4c913400ff7ff4cdc03ac2bda99c2d29edcacb3b065c67e6'
+ ]
+ ]);
+
+ $response = $this->getAndParseWithoutCompare('/api/get-balance/' . $session_id);
+ $this->assertEquals('success', $response->state);
+ $this->assertEquals(0, $response->balance);
+ }
+ public function testGetBalance3()
+ {
+ $session_id = rand();
+ $this->session([
+ 'session_id' => $session_id,
+ 'Transaction' => ['pending' => 0, 'executing' => 0],
+ 'StateUser' => [
+ 'id' => 4,
+ 'email_checked' => 1,
+ 'public_hex' => 'e3369de3623ce8446d0424c4013e7a1d71a2671ae3d7bf1e798ebf0665d145f2'
+ ]
+ ]);
+
+ $response = $this->getAndParseWithoutCompare('/api/get-balance/' . $session_id);
+ $this->assertEquals('success', $response->state);
+ $this->assertEquals(10900000, $response->balance);
+ $this->assertLessThan(10900000, $response->decay);
+ }
+
+ public function testGetBalanceInvalidSession()
+ {
+ $session_id = rand();
+ $this->session([
+ 'session_id' => $session_id,
+ 'Transaction' => ['pending' => 0, 'executing' => 0],
+ 'StateUser' => [
+ 'email_checked' => 1,
+ 'public_hex' => '8190bda585ee5f1d9fbf7d06e81e69ec18e13376104cff54b7457eb7d3ef710d'
+ ]
+ ]);
+
+ $this->getAndParse('/api/get-balance/' . 1211,
+ ['state' => 'not found', 'msg' => 'invalid session']
+ );
+ }
+
+ public function testGetBalanceInvalidSessionId()
+ {
+ $session_id = rand();
+ $this->session([
+ 'session_id' => $session_id,
+ 'Transaction' => ['pending' => 0, 'executing' => 0],
+ 'StateUser' => [
+ 'email_checked' => 1,
+ 'public_hex' => '8190bda585ee5f1d9fbf7d06e81e69ec18e13376104cff54b7457eb7d3ef710d'
+ ]
+ ]);
+
+ $this->getAndParse('/api/get-balance/' ,
+ ['state' => 'not found', 'msg' => 'invalid session']
+ );
+ }
+
+ /**
+ * Test ajaxListTransactions method
+ *
+ * @return void
+ */
+ public function testListTransactions()
+ {
+ //ajaxListTransactions
+ $session_id = rand();
+ $this->session([
+ 'session_id' => $session_id,
+ 'Transactions' => ['pending' => 0, 'executing' => 0],
+ 'StateUser' => [
+ 'id' => 1,
+ 'first_name' => 'Dario',
+ 'last_name' => 'Frodo',
+ 'email_checked' => 1,
+ 'email' => 'fördertest@gradido.org',
+ 'public_hex' => '94ae135b93cd9f33752b4e55c41903a3faa13a75bb90bfd411ea1d4a1a5e711f'
+ ]
+ ]);
+ //echo "balance: $balance";
+ $expectedResult = '{
+ "state": "success",
+ "transactions": [
+ {
+ "name": "Gradido Akademie",
+ "type": "creation",
+ "transaction_id": 2,
+ "date": "2021-04-12T00:00:00+00:00",
+ "target_date": "2021-01-01T00:00:00+00:00",
+ "creation_amount": 10000000,
+ "balance": 10000000,
+ "memo": "AGE Januar 2021"
+ },
+ {
+ "name": "Samuel Schmied",
+ "email": "test3.yahoo.com",
+ "type": "send",
+ "transaction_id": 3,
+ "date": "2021-04-12T00:00:00+00:00",
+ "balance": 1000000,
+ "memo": "test",
+ "pubkey": "e3369de3623ce8446d0424c4013e7a1d71a2671ae3d7bf1e798ebf0665d145f2"
+ },
+ {
+ "name": "Samuel Schmied",
+ "email": "test3.yahoo.com",
+ "type": "send",
+ "transaction_id": 4,
+ "date": "2021-04-14T00:00:00+00:00",
+ "balance": 100000,
+ "memo": "test time",
+ "pubkey": "e3369de3623ce8446d0424c4013e7a1d71a2671ae3d7bf1e798ebf0665d145f2"
+ },
+ {
+ "name": "Samuel Schmied",
+ "email": "test3.yahoo.com",
+ "type": "send",
+ "transaction_id": 5,
+ "date": "2021-04-14T09:01:07+00:00",
+ "balance": 100000,
+ "memo": "test time",
+ "pubkey": "e3369de3623ce8446d0424c4013e7a1d71a2671ae3d7bf1e798ebf0665d145f2"
+ },
+ {
+ "name": "Samuel Schmied",
+ "email": "test3.yahoo.com",
+ "type": "receive",
+ "transaction_id": 6,
+ "date": "2021-04-14T09:02:28+00:00",
+ "balance": 100000,
+ "memo": "test time 3",
+ "pubkey": "0000000000000000000000000000000000000000000000000000000000000000"
+ },
+ {
+ "name": "Samuel Schmied",
+ "email": "test3.yahoo.com",
+ "type": "receive",
+ "transaction_id": 7,
+ "date": "2021-04-14T09:28:46+00:00",
+ "balance": 100000,
+ "memo": "test login crash",
+ "pubkey": "0000000000000000000000000000000000000000000000000000000000000000"
+ },
+ {
+ "name": "Samuel Schmied",
+ "email": "test3.yahoo.com",
+ "type": "receive",
+ "transaction_id": 8,
+ "date": "2021-04-14T09:31:28+00:00",
+ "balance": 100000,
+ "memo": "test login crash",
+ "pubkey": "0000000000000000000000000000000000000000000000000000000000000000"
+ }
+ ],
+ "transactionExecutingCount": 0,
+ "count": 7,
+ "gdtSum": 180000,
+ "timeUsed": 0.5575470924377441,
+ "decay_date": "2021-05-28T09:35:02+00:00",
+ "balance": 9100000,
+ "decay": 9100000
+}';
+ $this->getAndParse('/api/list-transactions/', json_decode($expectedResult, true));
+ }
+
+
+ private function getAndParse($path, $expected)
+ {
+ $this->configRequest([
+ 'headers' => ['Accept' => 'application/json']
+ ]);
+
+ $this->disableErrorHandlerMiddleware();
+ $this->get($path);
+
+ // Check that the response was in 2xx - 3xx
+ $this->assertResponseSuccess();
+ $json = (object)$this->viewVariable('body');
+
+ if(!$json) {
+ // Check that the response was a 200
+ $this->assertResponseOk();
+
+ $responseBodyString = (string)$this->_response->getBody();
+ $json = json_decode($responseBodyString);
+ $this->assertNotFalse($json);
+ } else {
+ $responseBodyString = json_encode($json);
+ }
+
+ if(is_array($expected)) {
+ $dynamic_fields = ['timeUsed', 'decay_date', 'decay', 'gdtSum'];
+ // copy timeUsed because this value will be variy always
+ foreach($dynamic_fields as $field) {
+ if(isset($expected[$field]) && isset($json->$field)) {
+ $expected[$field] = $json->$field;
+ }
+ }
+ $expected = json_encode($expected);
+ }
+
+ $this->assertEquals($expected, $responseBodyString);
+ }
+ private function getAndParseWithoutCompare($path)
+ {
+ $this->configRequest([
+ 'headers' => ['Accept' => 'application/json']
+ ]);
+
+ $this->disableErrorHandlerMiddleware();
+ $this->get($path);
+
+ // Check that the response was in 2xx - 3xx
+ $this->assertResponseSuccess();
+ $view_body = $this->viewVariable('body');
+ if($view_body) {
+ return (object)$view_body;
+ }
+ // Check that the response was a 200
+ $this->assertResponseOk();
+ $responseBodyString = (string)$this->_response->getBody();
+ $json = json_decode($responseBodyString, true);
+ $this->assertNotFalse($json);
+
+ return $json;
+ }
+}
diff --git a/community_server/tests/TestCase/Controller/Component/JsonRequestClientComponentTest.php b/community_server/tests/TestCase/Controller/Component/JsonRequestClientComponentTest.php
index fb882478a..c1ba84ee3 100644
--- a/community_server/tests/TestCase/Controller/Component/JsonRequestClientComponentTest.php
+++ b/community_server/tests/TestCase/Controller/Component/JsonRequestClientComponentTest.php
@@ -51,19 +51,7 @@ class JsonRequestClientComponentTest extends TestCase
$this->markTestIncomplete('Not implemented yet.');
}
- /**
- * Test getLoginServerUrl method
- *
- * @return void
- */
- public function testGetLoginServerUrl()
- {
- //$this->markTestIncomplete('Not implemented yet.');
- $serverUrl = $this->JsonRequestClientComponent->getLoginServerUrl();
- $this->assertEquals($serverUrl, 'http://***REMOVED***');
- }
-
- /**
+ /**
* Test is_base64 method
*
* @return void
diff --git a/community_server/tests/TestCase/Controller/JsonRequestHandlerControllerTest.php b/community_server/tests/TestCase/Controller/JsonRequestHandlerControllerTest.php
index d8a241d7d..f990b3e57 100644
--- a/community_server/tests/TestCase/Controller/JsonRequestHandlerControllerTest.php
+++ b/community_server/tests/TestCase/Controller/JsonRequestHandlerControllerTest.php
@@ -5,9 +5,9 @@ use Cake\TestSuite\IntegrationTestTrait;
use Cake\TestSuite\TestCase;
/**
- * App\Controller\TransactionJsonRequestHandlerController Test Case
+ * App\Controller\JsonRequestHandlerController Test Case
*
- * @uses \App\Controller\TransactionJsonRequestHandlerController
+ * @uses \App\Controller\JsonRequestHandlerController
*/
class JsonRequestHandlerControllerTest extends TestCase
{
@@ -22,6 +22,7 @@ class JsonRequestHandlerControllerTest extends TestCase
'app.TransactionCreations',
'app.Transactions',
'app.StateUsers',
+ 'app.StateUserTransactions',
'app.StateErrors',
'app.TransactionSignatures',
'app.TransactionSendCoins',
@@ -30,13 +31,12 @@ class JsonRequestHandlerControllerTest extends TestCase
];
public $transactions = [
- 'validCreation' => 'GmYKZAogYbkjwhjLY6ZKjGLzhgEhKDuVd_N00KMVkLoCzcKRKZkSQJ8wF12eZo3hcMAlAKKJ9WLT-zuSkNmGh7D98UEqH4KoIysnCkXqEya9EBZl9o11_nJ8xmm_nOevuVjR-GfLMQ8qSQoOSGFsbG8gV2VsdCAxMjMSBgiZm4ruBUovCicKIJSuE1uTzZ8zdStOVcQZA6P6oTp1u5C_1BHqHUoaXnEfEKDakwEQtYntlgo',
- 'validCreation900' => 'GmYKZAogYbkjwhjLY6ZKjGLzhgEhKDuVd_N00KMVkLoCzcKRKZkSQNVZ8Ae3Zbg3G0wZ840fzKan6N4KtTcSe0KYi17kQwFmsl18oFxXv8_s6j1xXFrIKjy1_1Olq0a7xYLErDMkjwYqORIGCNb5iu4FSi8KJwoglK4TW5PNnzN1K05VxBkDo_qhOnW7kL_UEeodShpecR8QgNHKCBC1ie2WCg',
- 'validCreation1200' => 'GmYKZAogYbkjwhjLY6ZKjGLzhgEhKDuVd_N00KMVkLoCzcKRKZkSQEEey5QMAdldoOTP_jTETHgOQriGsixEY0cziQeRfT_J5YtbI_A6AizEYD-JcxmRmXzv1xjjTgsV39Y32ta2CQkqORIGCIeGi-4FSi8KJwoglK4TW5PNnzN1K05VxBkDo_qhOnW7kL_UEeodShpecR8QgOy4CxC1ie2WCg',
+ 'validCreation' => 'CmYKZAog4zad42I86ERtBCTEAT56HXGiZxrj178eeY6_BmXRRfISQDnatUMvitiiP0-sY93JStYPhPKKPU4Vosv_EGrh77BVs48xhPgPj2QHWC3oyuuMh6nN8YNjBQZx20rKvdQ4uwMSRwoMQUdFIE1haSAyMDIxEgYI_c3ChQY6LwolCiD39KSaSsEDefi53ctzHE2exJXm7dFgdfUmcs0l4xefDxDQDxoGCPqbtIQG',
+ 'validCreation900' => 'CmYKZAog9_SkmkrBA3n4ud3LcxxNnsSV5u3RYHX1JnLNJeMXnw8SQCaZHmvmvJOt336E3qst3rn1pptdAR5ZPzePaUT10x0_Yky8FnEiQtMGNy1yT94QErzwQudJZjJwDY2uyK4cTgkSOxIGCKb1vYUGOjEKJwog4zad42I86ERtBCTEAT56HXGiZxrj178eeY6_BmXRRfIQgNHKCBoGCIDMuf8F',
+ 'validCreation1200' => 'CmYKZAog9_SkmkrBA3n4ud3LcxxNnsSV5u3RYHX1JnLNJeMXnw8SQF8jptIrosEyVmCf3WEIGVOK0NR8YCcO0j-s8v2yUyR5BKus0ciT6B7IA5LDtn7eQX6zHjg1v5WlsTiZuOpuNgwSRAoHVG8gbXVjaBIGCL3Jv4UGOjEKJwog4zad42I86ERtBCTEAT56HXGiZxrj178eeY6_BmXRRfIQgOy4CxoGCOG5toQG',
'notBase64' => 'CgpIYWxsbyBXZW-0EgYIyfSG7gV_LwonCiCboKikqwjZfes9xuqgthFH3',
- 'validTransfer' => 'GmYKZAoggZC9pYXuXx2fv30G6B5p7BjhM3YQTP9Ut0V-t9PvcQ0SQDddHyKzAX3LBV0PuDiPc6lxkUipss5tyuLRpMtFJQnT30tsbYIkA1FXimjMKOoiuLswf4OLLV3bAIYehW-b9AgqYQoFSGFsbG8SBgiJlaPvBUJQCiYKIIGQvaWF7l8dn799BugeaewY4TN2EEz_VLdFfrfT73ENEICfSRImCiDtdleSLxhUgEbMW9DpqIwsykFj3-z_enKEOuGnXrmW8xCAn0k',
- 'errornusTransfer' => 'ClxGcm9oZXMgTmV1ZXMgSmFociB1bmQgREFOS0UsIGRhc3MgZHUgZGljaCBzbyBlaW5zZXR6dCBmw7xyIEdyYWRpZG8hIEhlcnpsaWNoZSBHcsO8w59lIFRlcmVzYRIGCPjjgvEFQlAKJgogUQwFYeVlGlfWDrkXNN7rHwejoCDJKt+YkYJfbJVyj3EQwIQ9EiYKIPXIRnUhVJ/zCs5+y/VaTBjTIoYizJNwS+JC//xsbQrHEMCEPQ==',
- 'creationValid' => 'GmYKZAogLtKKHPXhFtg2FUBrxXcVIiHC93SlZW9moOdUD3V21xsSQHpXYAGiVmSfhjB3o7OPx0ZJuPXrDk5eu1_AOhQBODU3KpUqBRA9yMX54S_mvGijGubCNRcMLcm7wiYbyAG-3AkqSwoQZWluIE1vbmF0c2dlaGFsdBIGCKqs5vEFSi8KJwoggZC9pYXuXx2fv30G6B5p7BjhM3YQTP9Ut0V-t9PvcQ0QgNrECRDKyd3uAQ'
+ 'validTransfer' => 'CmYKZAog9_SkmkrBA3n4ud3LcxxNnsSV5u3RYHX1JnLNJeMXnw8SQA0ZVQ9T1qBabzmgDO1NAWNy2J6mlv0YjMP99CiV7bSR0zemt5XoM-kTviR1aTqKggzpSYSyTN5T6gIx2xa-hgkSYwoLTXkgQmlydGhkYXkSBgie0L-FBjJMCkoKJgog9_SkmkrBA3n4ud3LcxxNnsSV5u3RYHX1JnLNJeMXnw8QgIl6EiDjNp3jYjzoRG0EJMQBPnodcaJnGuPXvx55jr8GZdFF8g',
+ 'errornusTransfer' => 'ClxGcm9oZXMgTmV1ZXMgSmFociB1bmQgREFOS0UsIGRhc3MgZHUgZGljaCBzbyBlaW5zZXR6dCBmw7xyIEdyYWRpZG8hIEhlcnpsaWNoZSBHcsO8w59lIFRlcmVzYRIGCPjjgvEFQlAKJgogUQwFYeVlGlfWDrkXNN7rHwejoCDJKt+YkYJfbJVyj3EQwIQ9EiYKIPXIRnUhVJ/zCs5+y/VaTBjTIoYizJNwS+JC//xsbQrHEMCEPQ=='
];
/*public function setUp() {
@@ -51,7 +51,7 @@ class JsonRequestHandlerControllerTest extends TestCase
$this->get('/JsonRequestHandler');
$this->assertResponseOk();
- $expected = json_encode(['state' => 'error', 'msg' => 'no post']);
+ $expected = json_encode(['state' => 'error', 'msg' => 'unknown method for get', 'details' => null]);
$this->assertEquals($expected, (string)$this->_response->getBody());
}
@@ -87,7 +87,7 @@ class JsonRequestHandlerControllerTest extends TestCase
//$this->post('/TransactionJsonRequestHandler', ['method' => 'putTransaction', 'transaction' => 'CgpIYWxsbyBXZWx0EgYIyfSG7gVKLwonCiCboKikqwjZfes9xuqgthFH3/cHHaWchkUhWiGhQjB23xCg2pMBELWJ7ZYK']);
$this->postAndParse(
['method' => 'foobar', 'transaction' => $this->transactions['validCreation']],
- ['state' => 'error', 'msg' => 'unknown method', 'details' => 'foobar']
+ ['state' => 'error', 'msg' => 'unknown method for post', 'details' => 'foobar']
);
}
@@ -97,7 +97,8 @@ class JsonRequestHandlerControllerTest extends TestCase
$this->postAndParse(
['method' => 'putTransaction', 'transaction' => $this->transactions['notBase64']],
['state' => 'error', 'msg' => 'error parsing transaction', 'details' => [
- ['Transaction' => 'invalid base64 string']
+ ['Transaction' => 'invalid base64 string'],
+ ['base64' => 'CgpIYWxsbyBXZW-0EgYIyfSG7gV_LwonCiCboKikqwjZfes9xuqgthFH3']
]]
);
}
@@ -114,9 +115,10 @@ class JsonRequestHandlerControllerTest extends TestCase
public function testToLargeCreationSum()
{
+
$this->postAndParse(
['method' => 'putTransaction', 'transaction' => $this->transactions['validCreation900']],
- '{"state":"error","msg":"error validate transaction","details":[{"TransactionCreation::validate":"Creation more than 1000 gr per Month not allowed"}]}'
+ '{"state":"error","msg":"error validate transaction","details":[{"TransactionCreation::validate":"Creation more than 1.000 GDD per Month for in target_date not allowed"}]}'
);
}
@@ -124,49 +126,36 @@ class JsonRequestHandlerControllerTest extends TestCase
{
$this->postAndParse(
['method' => 'putTransaction', 'transaction' => $this->transactions['validCreation1200']],
- '{"state":"error","msg":"error validate transaction","details":[{"TransactionCreation::validate":"Creation more than 1000 gr per Month not allowed"}]}'
+ '{"state":"error","msg":"error validate transaction","details":[{"TransactionCreation::validate":"Creation more than 1.000 GDD per Month for in target_date not allowed"}]}'
);
}
public function testValidTransfer()
- {
- $this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => $this->transactions['validTransfer']],
- ['state' => 'success']
- );
- }
-
- /*public function testMissingPreviousTransaction()
- {
-
- }*/
-
- public function testValidTransaction()
- {
- $this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => $this->transactions['validCreation']],
- ['state' => 'success']
+ {
+ $this->postAndParse(
+ ['method' => 'putTransaction', 'transaction' => $this->transactions['validTransfer']],
+ ['state' => 'success']
);
}
-
+
public function testValidCreation()
{
$this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => $this->transactions['creationValid']],
+ ['method' => 'putTransaction', 'transaction' => $this->transactions['validCreation']],
['state' => 'success']
);
}
private function postAndParse($params, $expected)
{
- //$this->enableCsrfToken();
+ $this->enableCsrfToken();
//$this->enableSecurityToken();
- $token = 'my-csrf-token';
- $this->cookie('csrfToken', $token);
+ //$token = 'my-csrf-token';
+ //$this->cookie('csrfToken', $token);
$this->configRequest([
- 'headers' => ['Accept' => 'application/json', 'X-CSRF-Token' => $token]
+ 'headers' => ['Accept' => 'application/json']//, 'X-CSRF-Token' => $token]
]);
$this->disableErrorHandlerMiddleware();
diff --git a/community_server/tests/TestCase/Controller/PagesControllerTest.php b/community_server/tests/TestCase/Controller/PagesControllerTest.php
index 35fe1a13b..004d7c079 100644
--- a/community_server/tests/TestCase/Controller/PagesControllerTest.php
+++ b/community_server/tests/TestCase/Controller/PagesControllerTest.php
@@ -27,6 +27,10 @@ use Cake\View\Exception\MissingTemplateException;
*/
class PagesControllerTest extends IntegrationTestCase
{
+
+ public $fixtures = [
+ 'app.Migrations2'
+ ];
/**
* testMultipleGet method
*
@@ -35,9 +39,12 @@ class PagesControllerTest extends IntegrationTestCase
public function testMultipleGet()
{
$this->get('/');
- $this->assertRedirect('account/');
+ $locations = $this->_response->getHeader('Location');
+ $this->assertRegExp('%.*/account/$%', $locations[0]);
+
$this->get('/');
- $this->assertRedirect('account/');
+ $locations = $this->_response->getHeader('Location');
+ $this->assertRegExp('%.*/account/$%', $locations[0]);
}
/**
@@ -64,7 +71,7 @@ class PagesControllerTest extends IntegrationTestCase
$this->get('/pages/not_existing');
$this->assertResponseError();
- $this->assertResponseContains('Error');
+ $this->assertResponseContains('Not Found');
}
/**
@@ -78,8 +85,7 @@ class PagesControllerTest extends IntegrationTestCase
$this->get('/pages/not_existing');
$this->assertResponseFailure();
- $this->assertResponseContains('Missing Template');
- $this->assertResponseContains('Stacktrace');
+ $this->assertResponseContains('Template file \u0022Pages\/not_existing.ctp\u0022 is missing.');
$this->assertResponseContains('not_existing.ctp');
}
diff --git a/community_server/tests/TestCase/Controller/StateBalancesControllerTest.php b/community_server/tests/TestCase/Controller/StateBalancesControllerTest.php
index cfa6bebc4..9ef8d28e9 100644
--- a/community_server/tests/TestCase/Controller/StateBalancesControllerTest.php
+++ b/community_server/tests/TestCase/Controller/StateBalancesControllerTest.php
@@ -69,142 +69,7 @@ class StateBalancesControllerTest extends TestCase
$this->markTestIncomplete('Not implemented yet.');
}
- /**
- * Test ajaxGetBalance method
- *
- * @return void
- */
- public function testAjaxGetBalance1()
- {
- $session_id = rand();
- $this->session([
- 'session_id' => $session_id,
- 'Transaction' => ['pending' => 0, 'executing' => 0],
- 'StateUser' => [
- 'id' => 1,
- 'email_checked' => 1,
- 'public_hex' => 'f7f4a49a4ac10379f8b9ddcb731c4d9ec495e6edd16075f52672cd25e3179f0f'
- ]
- ]);
-
- $response = $this->getAndParseWithoutCompare('/state-balances/ajaxGetBalance/' . $session_id);
-
- $this->assertEquals('success', $response->state);
- $this->assertEquals(7321825, $response->balance);
- $this->assertLessThan(7321825, $response->decay);
-
- }
- public function testAjaxGetBalance2()
- {
- $session_id = rand();
- $this->session([
- 'session_id' => $session_id,
- 'Transaction' => ['pending' => 0, 'executing' => 0],
- 'StateUser' => [
- 'id' => 3,
- 'email_checked' => 1,
- 'public_hex' => '131c7f68dd94b2be4c913400ff7ff4cdc03ac2bda99c2d29edcacb3b065c67e6'
- ]
- ]);
-
- $response = $this->getAndParseWithoutCompare('/state-balances/ajaxGetBalance/' . $session_id);
- $this->assertEquals('success', $response->state);
- $this->assertEquals(0, $response->balance);
- }
- public function testAjaxGetBalance3()
- {
- $session_id = rand();
- $this->session([
- 'session_id' => $session_id,
- 'Transaction' => ['pending' => 0, 'executing' => 0],
- 'StateUser' => [
- 'id' => 4,
- 'email_checked' => 1,
- 'public_hex' => 'e3369de3623ce8446d0424c4013e7a1d71a2671ae3d7bf1e798ebf0665d145f2'
- ]
- ]);
-
- $response = $this->getAndParseWithoutCompare('/state-balances/ajaxGetBalance/' . $session_id);
- $this->assertEquals('success', $response->state);
- $this->assertEquals(9112592, $response->balance);
- $this->assertLessThan(9112592, $response->decay);
- }
-
- public function testAjaxGetBalanceInvalidSession()
- {
- $session_id = rand();
- $this->session([
- 'session_id' => $session_id,
- 'Transaction' => ['pending' => 0, 'executing' => 0],
- 'StateUser' => [
- 'email_checked' => 1,
- 'public_hex' => '8190bda585ee5f1d9fbf7d06e81e69ec18e13376104cff54b7457eb7d3ef710d'
- ]
- ]);
- //echo "balance: $balance";
- $this->getAndParse('/state-balances/ajaxGetBalance/' . 1211,
- ['state' => 'not found', 'msg' => 'invalid session']
- );
- }
-
- public function testAjaxGetBalanceInvalidSessionId()
- {
- $session_id = rand();
- $this->session([
- 'session_id' => $session_id,
- 'Transaction' => ['pending' => 0, 'executing' => 0],
- 'StateUser' => [
- 'email_checked' => 1,
- 'public_hex' => '8190bda585ee5f1d9fbf7d06e81e69ec18e13376104cff54b7457eb7d3ef710d'
- ]
- ]);
- //echo "balance: $balance";
- $this->getAndParse('/state-balances/ajaxGetBalance' ,
- ['state' => 'error', 'msg' => 'invalid session id']
- );
- }
-
- /**
- * Test ajaxListTransactions method
- *
- * @return void
- */
- public function testAjaxListTransactions()
- {
- //ajaxListTransactions
- $session_id = rand();
- $this->session([
- 'session_id' => $session_id,
- 'Transaction' => ['pending' => 0, 'executing' => 0],
- 'StateUser' => [
- 'id' => 1,
- 'first_name' => 'Dario',
- 'last_name' => 'Frodo',
- 'email_checked' => 1,
- 'email' => 'fördertest@gradido.org',
- 'public_hex' => '94ae135b93cd9f33752b4e55c41903a3faa13a75bb90bfd411ea1d4a1a5e711f'
- ]
- ]);
- //echo "balance: $balance";
- $this->getAndParse('/state-balances/ajaxListTransactions/' . $session_id,
- [
- 'state' => 'success', 'transactions' => [[
- 'name' => 'Dario Frodo',
- 'email'=> 'dariofrodo@gmx.de',
- 'type'=> '',
- 'transaction_id' => 4,
- 'date' => '2021-02-19T13:27:14+00:00',
- 'balance' => 150000001,
- 'memo' => ''
- ]],
- 'transactionExecutingCount' => 0,
- 'count' => 1,
- 'gdtSum' => 0,
- 'timeUsed' => 0.03168010711669922
- ]
- );
- }
/**
* Test overviewGdt method
diff --git a/community_server/tests/TestCase/Controller/TransactionJsonRequestHandlerControllerTest.php b/community_server/tests/TestCase/Controller/TransactionJsonRequestHandlerControllerTest.php
deleted file mode 100644
index 7ad28760c..000000000
--- a/community_server/tests/TestCase/Controller/TransactionJsonRequestHandlerControllerTest.php
+++ /dev/null
@@ -1,174 +0,0 @@
- 'GmYKZAogYbkjwhjLY6ZKjGLzhgEhKDuVd_N00KMVkLoCzcKRKZkSQJ8wF12eZo3hcMAlAKKJ9WLT-zuSkNmGh7D98UEqH4KoIysnCkXqEya9EBZl9o11_nJ8xmm_nOevuVjR-GfLMQ8qSQoOSGFsbG8gV2VsdCAxMjMSBgiZm4ruBUovCicKIJSuE1uTzZ8zdStOVcQZA6P6oTp1u5C_1BHqHUoaXnEfEKDakwEQtYntlgo',
- 'validCreation900' => 'GmYKZAogYbkjwhjLY6ZKjGLzhgEhKDuVd_N00KMVkLoCzcKRKZkSQNVZ8Ae3Zbg3G0wZ840fzKan6N4KtTcSe0KYi17kQwFmsl18oFxXv8_s6j1xXFrIKjy1_1Olq0a7xYLErDMkjwYqORIGCNb5iu4FSi8KJwoglK4TW5PNnzN1K05VxBkDo_qhOnW7kL_UEeodShpecR8QgNHKCBC1ie2WCg',
- 'validCreation1200' => 'GmYKZAogYbkjwhjLY6ZKjGLzhgEhKDuVd_N00KMVkLoCzcKRKZkSQEEey5QMAdldoOTP_jTETHgOQriGsixEY0cziQeRfT_J5YtbI_A6AizEYD-JcxmRmXzv1xjjTgsV39Y32ta2CQkqORIGCIeGi-4FSi8KJwoglK4TW5PNnzN1K05VxBkDo_qhOnW7kL_UEeodShpecR8QgOy4CxC1ie2WCg',
- 'notBase64' => 'CgpIYWxsbyBXZW-0EgYIyfSG7gV_LwonCiCboKikqwjZfes9xuqgthFH3',
- 'validTransfer' => 'GmYKZAoggZC9pYXuXx2fv30G6B5p7BjhM3YQTP9Ut0V-t9PvcQ0SQDddHyKzAX3LBV0PuDiPc6lxkUipss5tyuLRpMtFJQnT30tsbYIkA1FXimjMKOoiuLswf4OLLV3bAIYehW-b9AgqYQoFSGFsbG8SBgiJlaPvBUJQCiYKIIGQvaWF7l8dn799BugeaewY4TN2EEz_VLdFfrfT73ENEICfSRImCiDtdleSLxhUgEbMW9DpqIwsykFj3-z_enKEOuGnXrmW8xCAn0k',
- 'errornusTransfer' => 'ClxGcm9oZXMgTmV1ZXMgSmFociB1bmQgREFOS0UsIGRhc3MgZHUgZGljaCBzbyBlaW5zZXR6dCBmw7xyIEdyYWRpZG8hIEhlcnpsaWNoZSBHcsO8w59lIFRlcmVzYRIGCPjjgvEFQlAKJgogUQwFYeVlGlfWDrkXNN7rHwejoCDJKt+YkYJfbJVyj3EQwIQ9EiYKIPXIRnUhVJ/zCs5+y/VaTBjTIoYizJNwS+JC//xsbQrHEMCEPQ=='
- ];
-
- /*public function setUp() {
- parent::setUp();
- }
-*/
- public function testWrongMethod()
- {
- $this->configRequest([
- 'headers' => ['Accept' => 'application/json']
- ]);
- $this->get('/TransactionJsonRequestHandler');
- $this->assertResponseOk();
-
- $expected = json_encode(['state' => 'error', 'msg' => 'no post']);
- $this->assertEquals($expected, (string)$this->_response->getBody());
- }
-
- public function testInvalidJson()
- {
- $this->configRequest([
- 'headers' => ['Accept' => 'application/json']
- ]);
- $this->post('/TransactionJsonRequestHandler', '{This isn\'t valid json}');
- $this->assertResponseOk();
-
- $expected = json_encode(['state' => 'error', 'msg' => 'parameter error']);
- $this->assertEquals($expected, (string)$this->_response->getBody());
- }
-
- public function testNotSetTransaction()
- {
- $this->postAndParse(
- ['method' => 'putTransaction'],
- ['state' => 'error', 'msg' => 'parameter error']
- );
- }
- public function testNotSetMethod()
- {
- $this->postAndParse(
- ['transaction' => $this->transactions['validCreation']],
- ['state' => 'error', 'msg' => 'parameter error']
- );
- }
-
- public function testUnknownMethod()
- {
- //$this->post('/TransactionJsonRequestHandler', ['method' => 'putTransaction', 'transaction' => 'CgpIYWxsbyBXZWx0EgYIyfSG7gVKLwonCiCboKikqwjZfes9xuqgthFH3/cHHaWchkUhWiGhQjB23xCg2pMBELWJ7ZYK']);
- $this->postAndParse(
- ['method' => 'foobar', 'transaction' => $this->transactions['validCreation']],
- ['state' => 'error', 'msg' => 'unknown method', 'details' => 'foobar']
- );
-
- }
-
- public function testInvalidEncodedTransaction() {
- //"msg":"error parsing transaction","details":[{"Transaction":"base64 decode error"}]
- $this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => $this->transactions['notBase64']],
- ['state' => 'error', 'msg' => 'error parsing transaction', 'details' => [
- ['Transaction' => 'invalid base64 string']
- ]]
- );
- }
-
- public function testInvalidTransaction() {
-
- $this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => base64_encode('Hallo Miau Welt')],
- ['state' => 'error', 'msg' => 'error parsing transaction', 'details' => [
- ['Transaction' => 'Error occurred during parsing: Unexpected wire type.']
- ]]
- );
- }
-
- public function testToLargeCreationSum()
- {
- $this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => $this->transactions['validCreation900']],
- '{"state":"error","msg":"error validate transaction","details":[{"TransactionCreation::validate":"Creation more than 1000 gr per Month not allowed"}]}'
- );
- }
-
- public function testToLargeCreation()
- {
- $this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => $this->transactions['validCreation1200']],
- '{"state":"error","msg":"error validate transaction","details":[{"TransactionCreation::validate":"Creation more than 1000 gr per Month not allowed"}]}'
- );
- }
-
- public function testValidTransfer()
- {
- $this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => $this->transactions['validTransfer']],
- ['state' => 'success']
- );
- }
-
- /*public function testMissingPreviousTransaction()
- {
-
- }*/
-
- public function testValidTransaction()
- {
- $this->postAndParse(
- ['method' => 'putTransaction', 'transaction' => $this->transactions['validCreation']],
- ['state' => 'success']
- );
- }
-
- private function postAndParse($params, $expected)
- {
-
- $this->configRequest([
- 'headers' => ['Accept' => 'application/json']
- ]);
-
- $this->disableErrorHandlerMiddleware();
- $this->post('/TransactionJsonRequestHandler', json_encode($params));
-
- // Check that the response was a 200
- $this->assertResponseOk();
-
- $responseBodyString = (string)$this->_response->getBody();
- $json = json_decode($responseBodyString);
- $this->assertNotFalse($json);
-
- if(is_array($expected)) {
- $expected = json_encode($expected);
- }
- $this->assertEquals($expected, $responseBodyString);
- }
-}
diff --git a/community_server/tests/TestCase/Model/Entity/TableTest.php b/community_server/tests/TestCase/Model/Entity/TableTest.php
deleted file mode 100644
index 5a189942a..000000000
--- a/community_server/tests/TestCase/Model/Entity/TableTest.php
+++ /dev/null
@@ -1,51 +0,0 @@
-Table = new Table();
- }
-
- /**
- * tearDown method
- *
- * @return void
- */
- public function tearDown()
- {
- unset($this->Table);
-
- parent::tearDown();
- }
-
- /**
- * Test initial setup
- *
- * @return void
- */
- public function testInitialization()
- {
- $this->markTestIncomplete('Not implemented yet.');
- }
-}
diff --git a/community_server/tests/TestCase/Model/Transactions/TransactionCreationTest.php b/community_server/tests/TestCase/Model/Transactions/TransactionCreationTest.php
index 60a6307ed..e53549a42 100644
--- a/community_server/tests/TestCase/Model/Transactions/TransactionCreationTest.php
+++ b/community_server/tests/TestCase/Model/Transactions/TransactionCreationTest.php
@@ -30,84 +30,12 @@ class TransactionCreationTest extends TestCase
parent::setUp();
}
-
- public function testHashingFunction()
+ public function testDummy()
{
- $pairs = [
- "a" => 97,
- "b" => 98,
- "c" => 99,
- "d" => 100,
- "aa" => 12513,
- "ab" => 12514,
- "@" => 64,
- ".d" => 5988,
- "gmx" => 1701624,
- "@gmx" => 135919352,
- "@gmx.de" => 3742152099,
- "***REMOVED***" => 2928827813,
- "***REMOVED***" => 1899591683,
- "***REMOVED***" => 2089074830,
- "maximilian.muster@gradido.net" => 793144931,
- "coin-info5@gradido.net" => 1829129963,
- "coin-info6@gradido.net" => 1830178539,
- "coin-info8@gradido.net" => 1832275691,
- "coin-info9@gradido.net" => 1833324267,
- "coin-info10@gradido.net" => 3877298078,
- "coin-info11@gradido.net" => 3878346654,
- "coin-info12@gradido.net" => 3879395230,
- "***REMOVED***" => 2089074830,
- "***REMOVED***" => 3996757473,
- "***REMOVED***" => 3788634614,
- "***REMOVED***" => 807797884,
- "***REMOVED***" => 1640973721,
- "***REMOVED***" => 2025729173,
- "***REMOVED***" => 1961122507,
- "***REMOVED***" => 362466358,
- "***REMOVED***" => 3796728871,
- "***REMOVED***" => 807797884,
- "***REMOVED***" => 3794905967,
- "***REMOVED***" => 3077694284,
- "***REMOVED***" => 3246159770,
- "***REMOVED***" => 3123402690,
- "testneu-11-12-3@gradido.net" => 4092403827,
- "***REMOVED***" => 3151414199,
- "***REMOVED***" => 3526188273,
- "***REMOVED***" => 966804823,
- "***REMOVED***" => 1309273258,
- "***REMOVED***" => 995978784,
- "***REMOVED***" => 310113324,
- "***REMOVED***" => 1309273258,
- "***REMOVED***" => 530108573,
- "***REMOVED***" => 1734855679,
- "***REMOVED***" => 767779182,
- "***REMOVED***" => 2247491519,
- "***REMOVED***" => 3248626267,
- "***REMOVED***" => 3516649930,
- "***REMOVED***" => 231214190,
- "***REMOVED***" => 4247461928,
- "***REMOVED***" => 324829839,
- "***REMOVED***" => 3046147747,
- "***REMOVED***" => 3207307415,
- "***REMOVED***" => 728893500,
- "***REMOVED***" => 3905254663,
- "***REMOVED***" => 3207307415,
- "***REMOVED***" => 1155733239,
- "***REMOVED***" => 2013046423,
- "***REMOVED***" => 4033835283,
- "***REMOVED***" => 1945541625,
- "***REMOVED***" => 2310715309,
- "***REMOVED***" => 1221362064,
- "***REMOVED***" => 4161339877
- ];
- foreach($pairs as $email => $cpp_hash) {
- $php_hash = TransactionCreation::DRMakeStringHash($email);
- // assertEquals(mixed $expected, mixed $actual[, string $message = ''])
- if($php_hash != $cpp_hash) {
- $this->assertEquals($cpp_hash, $php_hash, "hashes for $email don't match");
- }
- }
+ $this->assertEquals(true, true);
}
+
+
}
diff --git a/configs/community_server/app.php b/configs/community_server/app.php
index f0cf46220..5bbdcdc4c 100644
--- a/configs/community_server/app.php
+++ b/configs/community_server/app.php
@@ -304,11 +304,11 @@ return [
'className' => Connection::class,
'driver' => Mysql::class,
'persistent' => false,
- 'host' => 'localhost',
+ 'host' => 'mariadb',
//'port' => 'non_standard_port_number',
- 'username' => 'my_app',
- 'password' => 'secret',
- 'database' => 'test_myapp',
+ 'username' => 'root',
+ 'password' => '',
+ 'database' => 'gradido_community_test',
//'encoding' => 'utf8mb4',
'timezone' => 'UTC',
'cacheMetadata' => true,
diff --git a/configs/login_server/grd_login_test.properties b/configs/login_server/grd_login_test.properties
new file mode 100644
index 000000000..8a269694a
--- /dev/null
+++ b/configs/login_server/grd_login_test.properties
@@ -0,0 +1,57 @@
+HTTPServer.port = 1200
+JSONServer.port = 1201
+Gradido.group_id = 1
+
+crypto.server_admin_public = f909a866baec97c5460b8d7a93b72d3d4d20cc45d9f15d78bd83944eb9286b7f
+crypto.server_key = a51ef8ac7ef1abf162fb7a65261acd7a
+# TODO auto-generate in docker build step
+crypto.app_secret = 21ffbbc616fe
+
+# Server admin Passphrase
+# nerve execute merit pool talk hockey basic win cargo spin disagree ethics swear price purchase say clutch decrease slow half forest reform cheese able
+#
+
+phpServer.url = http://localhost/
+phpServer.host = nginx
+
+loginServer.path = http://localhost/account
+loginServer.default_locale = de
+loginServer.db.host = mariadb
+loginServer.db.name = gradido_login_test
+loginServer.db.user = root
+loginServer.db.password =
+loginServer.db.port = 3306
+
+frontend.checkEmailPath = http://localhost/reset
+
+email.disable = true
+
+#email.username =
+#email.sender =
+#email.admin_receiver =
+#email.password =
+#email.smtp.url =
+#email.smtp.port =
+
+# binary is default, for debugging also json is possible
+#hedera.consensus.message_format = json
+# TESTNET or MAINNET, TESTNET is default
+hedera.nettype = TESTNET
+
+# server setup types: test, staging or production
+ServerSetupType=test
+dev.default_group = docker
+
+
+# Session timeout in minutes
+#
+session.timeout = 15
+
+# Disabling security features for faster develop and testing
+unsecure.allow_passwort_via_json_request = 1
+unsecure.allow_auto_sign_transactions = 1
+unsecure.allow_cors_all = 1
+# default disable, passwords must contain a number, a lower character, a high character, special character, and be at least 8 characters long
+
+unsecure.allow_all_passwords = 1
+
diff --git a/configs/login_server/setup_db_tables/setup_hedera_group.sql b/configs/login_server/setup_db_tables/setup_hedera_group.sql
deleted file mode 100644
index 2ae4dfeb6..000000000
--- a/configs/login_server/setup_db_tables/setup_hedera_group.sql
+++ /dev/null
@@ -1,19 +0,0 @@
-INSERT INTO `groups` (`id`, `alias`, `name`, `url`, `host`, `home`, `description`) VALUES
-(2, 'dockerStage2', 'docker stage2 gradido group', 'localhost', 'nginx', '/', 'gradido test group for docker and stage2');
-
-INSERT INTO `hedera_ids` (`id`, `shardNum`, `realmNum`, `num`) VALUES
-(1, 0, 0, 3),
-(2, 0, 0, 3327),
-(3, 0, 0, 413151);
-
-INSERT INTO `node_servers` (`id`, `url`, `port`, `group_id`, `server_type`, `node_hedera_id`, `last_live_sign`) VALUES
-(1, 'http://0.testnet.hedera.com', 50211, 0, 4, 2, '2000-01-01 00:00:00');
-
-INSERT INTO `hedera_accounts` (`id`, `user_id`, `account_hedera_id`, `account_key_id`, `balance`, `network_type`, `updated`) VALUES
-(1, 1, 2, 1, 1000000000000, 1, '2021-01-07 10:22:52');
-
-INSERT INTO `hedera_topics` (`id`, `topic_hedera_id`, `name`, `auto_renew_account_hedera_id`, `auto_renew_period`, `group_id`, `admin_key_id`, `submit_key_id`, `current_timeout`, `sequence_number`, `running_hash`, `running_hash_version`, `updated`) VALUES
-(1, 3, 'dockerStage2', 1, 7890000, 1, 0, 0, '2021-06-08 23:17:19', 0, NULL, 0, '2021-03-09 16:42:34');
-
-
-
diff --git a/docker-compose.override.yml b/docker-compose.override.yml
index 1311fe894..1060002ba 100644
--- a/docker-compose.override.yml
+++ b/docker-compose.override.yml
@@ -38,7 +38,7 @@ services:
- ./login_server/dependencies:/code/dependencies
- ./login_server/scripts:/code/scripts
- ./configs/login_server:/etc/grd_login
- - login_build_alpine:/code/build
+ - login_build_3.1:/code/build
#########################################################
@@ -47,11 +47,8 @@ services:
community-server:
build:
context: .
+ target: community_server
dockerfile: ./community_server/Dockerfile
- environment:
- - DB_PASSWORD=''
- - DB_USER='root'
- - DB_DATABASE='gradido_community'
depends_on:
- mariadb
networks:
@@ -103,4 +100,4 @@ services:
volumes:
frontend_node_modules:
- login_build_alpine:
+ login_build_3.1:
diff --git a/docker-compose.test.yml b/docker-compose.test.yml
new file mode 100644
index 000000000..b9d44363e
--- /dev/null
+++ b/docker-compose.test.yml
@@ -0,0 +1,99 @@
+version: "3.4"
+
+services:
+
+ #########################################################
+ ## MARIADB ##############################################
+ #########################################################
+ mariadb:
+ build:
+ context: .
+ dockerfile: ./mariadb/Dockerfile
+ target: mariadb_server_test
+ environment:
+ - MARIADB_ALLOW_EMPTY_PASSWORD=1
+ - MARIADB_USER=root
+ networks:
+ - internal-net
+ ports:
+ - 3306:3306
+ volumes:
+ - db_test_vol:/var/lib/mysql
+
+ #########################################################
+ ## LOGIN SERVER #########################################
+ #########################################################
+ login-server:
+ build:
+ context: ./login_server/
+ target: test
+ security_opt:
+ - seccomp:unconfined
+ cap_add:
+ - SYS_PTRACE
+ depends_on:
+ - mariadb
+ networks:
+ - internal-net
+ volumes:
+ - ./logs:/var/log/grd_login
+ - ./login_server/src:/code/src
+ - ./configs/login_server:/etc/grd_login
+ - login_build_cov:/code/build_cov
+ - ./coverage/login:/code/build_cov/coverage_html
+
+ #########################################################
+ ## COMMUNITY SERVER (cakephp with php-fpm) ##############
+ #########################################################
+ community-server:
+ build:
+ context: .
+ target: test
+ dockerfile: ./community_server/Dockerfile
+ depends_on:
+ - mariadb
+ networks:
+ - internal-net
+ volumes:
+ - ./community_server/config/php-fpm/php-ini-overrides.ini:/etc/php/7.4/fpm/conf.d/99-overrides.ini
+ - ./community_server/src:/var/www/cakephp/src
+ - ./coverage/community:/var/www/cakephp/webroot/coverage
+
+
+ #########################################################
+ ## PHPMYADMIN ###########################################
+ #########################################################
+ phpmyadmin:
+ image: phpmyadmin
+ environment:
+ - PMA_ARBITRARY=1
+ #restart: always
+ ports:
+ - 8074:80
+ networks:
+ - internal-net
+ - external-net
+ volumes:
+ - /sessions
+
+ #########################################################
+ ## skeema for updating dbs if changes happend ###########
+ #########################################################
+ skeema:
+ build:
+ context: .
+ dockerfile: ./skeema/Dockerfile
+ target: skeema_run
+ depends_on:
+ - mariadb
+ networks:
+ - internal-net
+
+networks:
+ external-net:
+ internal-net:
+ internal: true
+
+volumes:
+ db_test_vol:
+ login_build_cov:
\ No newline at end of file
diff --git a/docker-compose.yml b/docker-compose.yml
index 59e617d71..2cc2ceff7 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -38,7 +38,7 @@ services:
build:
context: .
dockerfile: ./mariadb/Dockerfile
- target: mariadb_server
+ target: mariadb_server_test
environment:
- MARIADB_ALLOW_EMPTY_PASSWORD=1
- MARIADB_USER=root
@@ -47,7 +47,7 @@ services:
ports:
- 3306:3306
volumes:
- - db_vol:/var/lib/mysql
+ - db_vol:/var/lib/mysql
#########################################################
## LOGIN SERVER #########################################
@@ -80,6 +80,7 @@ services:
depends_on:
- community-server
- login-server
+ - frontend
ports:
- 80:80
@@ -89,6 +90,7 @@ services:
community-server:
build:
context: .
+ target: community_server
dockerfile: ./community_server/Dockerfile
environment:
- DB_PASSWORD=''
diff --git a/docu/login_server.api.md b/docu/login_server.api.md
index 70f19cdde..b466be7fc 100644
--- a/docu/login_server.api.md
+++ b/docu/login_server.api.md
@@ -38,9 +38,12 @@ with:
```json
{
"email": "max.musterman@gmail.de",
+ "username": "Maxilein",
"password": "123abcDE&"
}
```
+`username` or `email` must be present!
+If booth present, `email` will be used.
### Response
In case of success returns:
@@ -50,6 +53,7 @@ In case of success returns:
"state":"success",
"user": {
"created": 1614782270,
+ "description": "",
"disabled": false,
"email": "max.musterman@gmail.de",
"email_checked": true,
@@ -69,6 +73,7 @@ In case of success returns:
- `user`: contain user object
- `created`: timestamp on which account was created
+ - `description`: description of user for other user
- `disabled`: true if account was disabled, if disabled no login or coin transfer is possible
- `email`: email of user
- `email_checked`: true if user has successfully clicked on activation link in email
@@ -96,7 +101,9 @@ with:
{
"email":"max.musterman@gmail.de",
"first_name":"Max",
- "last_name":"Musterman" ,
+ "last_name":"Musterman",
+ "username": "Maxilein",
+ "description": "Tischler",
"emailType": 2,
"group_id": 1,
"password":"123abcDE&",
@@ -104,6 +111,8 @@ with:
}
```
+- `username`: (optional), mindestens 4 Zeichen, return error if already used
+- `description`: (optional), mindestens 4 Zeichen
- `emailType`: control email-text sended with email verification code
- 2: default, if user has registered directly
- 5: if user was registered by an admin
@@ -167,6 +176,8 @@ with:
"update": {
"User.first_name": "Max",
"User.last_name" : "Musterman",
+ "User.username" : "Maxilein",
+ "User.description" : "Tischler",
"User.disabled": 0,
"User.language": "de",
"User.password": "1234"
@@ -237,6 +248,8 @@ with:
"user.pubkeyhex",
"user.first_name",
"user.last_name",
+ "user.username",
+ "user.description",
"user.disabled",
"user.email_checked",
"user.language"
@@ -271,6 +284,8 @@ Return only the fields which are defined in request
- `user.pubkeyhex`: public key of user in hex-format
- `user.first_name`: first name of user
- `user.last_name`: last name of user
+- `user.username`: username of user (min 4 Character, unique per group)
+- `user.description`: profil text for user
- `user.disabled`: User will be disabled if he wants a account delete but has transactions. Until transactions are saved in real blockchain, we need this data because the public key
is in db only saved in state_users so if we delete this entry, validating all transactions is no longer possible. Disabled User cannot login and cannot receive transactions.
- `email_checked`: If user has clicked on link in verification email (register), can only transfer gradidos if email_checked is 1
@@ -298,6 +313,7 @@ In case of success returns:
"info":[],
"user": {
"created": 1614782270,
+ "description": "Tischler"
"disabled": false,
"email": "max.musterman@gmail.de",
"email_checked": true,
diff --git a/frontend/babel.config.js b/frontend/babel.config.js
index faf55f74f..5907ab074 100644
--- a/frontend/babel.config.js
+++ b/frontend/babel.config.js
@@ -4,7 +4,6 @@ module.exports = {
[
'component',
{
- libraryName: 'element-ui',
styleLibraryName: 'theme-chalk',
},
],
diff --git a/frontend/package.json b/frontend/package.json
index 4371a6a57..68b4a5807 100755
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -29,7 +29,6 @@
"datamaps": "^0.5.9",
"date-fns": "^1.30.1",
"dropzone": "^5.5.1",
- "element-ui": "2.4.11",
"es6-promise": "^4.1.1",
"eslint": "^7.25.0",
"eslint-config-prettier": "^8.1.0",
diff --git a/frontend/src/components/LoadingPanel.vue b/frontend/src/components/LoadingPanel.vue
deleted file mode 100644
index c6b4fd70a..000000000
--- a/frontend/src/components/LoadingPanel.vue
+++ /dev/null
@@ -1,25 +0,0 @@
-
-
-
-
-
diff --git a/frontend/src/components/index.js b/frontend/src/components/index.js
index a6960c636..c75b2a8fa 100755
--- a/frontend/src/components/index.js
+++ b/frontend/src/components/index.js
@@ -20,7 +20,6 @@ import Collapse from './Collapse/Collapse.vue'
import CollapseItem from './Collapse/CollapseItem.vue'
import Modal from './Modal.vue'
import BaseSlider from './BaseSlider.vue'
-import LoadingPanel from './LoadingPanel.vue'
import BasePagination from './BasePagination.vue'
@@ -48,5 +47,4 @@ export {
BaseButton,
Collapse,
CollapseItem,
- LoadingPanel,
}
diff --git a/frontend/src/config/index.js b/frontend/src/config/index.js
index fa4bf388b..db60d2b84 100644
--- a/frontend/src/config/index.js
+++ b/frontend/src/config/index.js
@@ -1,7 +1,8 @@
// ATTENTION: DO NOT PUT ANY SECRETS IN HERE (or the .env)
// Load Package Details for some default values
-// const pkg = require('../../package')
+const pkg = require('../../package')
+
const environment = {
NODE_ENV: process.env.NODE_ENV,
DEBUG: process.env.NODE_ENV !== 'production' || false,
@@ -17,6 +18,7 @@ const server = {
const CONFIG = {
...environment,
...server,
+ APP_VERSION: pkg.version,
}
export default CONFIG
diff --git a/frontend/src/plugins/dashboard-plugin.js b/frontend/src/plugins/dashboard-plugin.js
index 6bafb569e..b7c0ea06c 100755
--- a/frontend/src/plugins/dashboard-plugin.js
+++ b/frontend/src/plugins/dashboard-plugin.js
@@ -11,10 +11,6 @@ import GlobalDirectives from './globalDirectives'
// Sidebar on the right. Used as a local plugin in DashboardLayout.vue
import SideBar from '@/components/SidebarPlugin'
-// element ui language configuration
-import lang from 'element-ui/lib/locale/lang/en'
-import locale from 'element-ui/lib/locale'
-
// vue-bootstrap
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
@@ -38,7 +34,6 @@ import VueMoment from 'vue-moment'
import Loading from 'vue-loading-overlay'
// import the styles
import 'vue-loading-overlay/dist/vue-loading.css'
-locale.use(lang)
Object.keys(rules).forEach((rule) => {
extend(rule, {
diff --git a/frontend/src/plugins/globalComponents.js b/frontend/src/plugins/globalComponents.js
index 7428dec6b..312f19296 100755
--- a/frontend/src/plugins/globalComponents.js
+++ b/frontend/src/plugins/globalComponents.js
@@ -13,7 +13,6 @@ import BaseAlert from '@/components/BaseAlert'
import BaseNav from '@/components/Navbar/BaseNav'
import BaseHeader from '@/components/BaseHeader'
import { ValidationProvider, ValidationObserver } from 'vee-validate'
-import { Input, Tooltip, Popover } from 'element-ui'
/**
* You can register global components here and use them as a plugin in your main Vue instance
*/
@@ -34,11 +33,8 @@ const GlobalComponents = {
Vue.component(Card.name, Card)
Vue.component(Modal.name, Modal)
Vue.component(StatsCard.name, StatsCard)
- Vue.component(Input.name, Input)
Vue.component('validation-provider', ValidationProvider)
Vue.component('validation-observer', ValidationObserver)
- Vue.use(Tooltip)
- Vue.use(Popover)
},
}
diff --git a/frontend/test/testSetup.js b/frontend/test/testSetup.js
index 1fb5cd195..f9c49880e 100644
--- a/frontend/test/testSetup.js
+++ b/frontend/test/testSetup.js
@@ -1,5 +1,4 @@
import { createLocalVue } from '@vue/test-utils'
-import ElementUI from 'element-ui'
import { BootstrapVue, IconsPlugin } from 'bootstrap-vue'
import Vuex from 'vuex'
import { ValidationProvider, ValidationObserver, extend } from 'vee-validate'
@@ -30,7 +29,6 @@ Object.keys(rules).forEach((rule) => {
})
})
-global.localVue.use(ElementUI)
global.localVue.use(BootstrapVue)
global.localVue.use(Vuex)
global.localVue.use(IconsPlugin)
diff --git a/frontend/yarn.lock b/frontend/yarn.lock
index 1f293d882..333df7d04 100644
--- a/frontend/yarn.lock
+++ b/frontend/yarn.lock
@@ -2749,13 +2749,6 @@ async-limiter@~1.0.0:
resolved "https://registry.yarnpkg.com/async-limiter/-/async-limiter-1.0.1.tgz#dd379e94f0db8310b08291f9d64c3209766617fd"
integrity sha512-csOlWGAcRFJaI6m+F2WKdnMKr4HhdhFVBk0H/QbJFMCr+uO2kwohwXQPxw/9OCxp05r5ghVBFSyioixx3gfkNQ==
-async-validator@~1.8.1:
- version "1.8.5"
- resolved "https://registry.yarnpkg.com/async-validator/-/async-validator-1.8.5.tgz#dc3e08ec1fd0dddb67e60842f02c0cd1cec6d7f0"
- integrity sha512-tXBM+1m056MAX0E8TL2iCjg8WvSyXu0Zc8LNtYqrVeyoL3+esHRZ4SieE9fKQyyU09uONjnMEjrNBMqT0mbvmA==
- dependencies:
- babel-runtime "6.x"
-
async@^2.6.2:
version "2.6.3"
resolved "https://registry.yarnpkg.com/async/-/async-2.6.3.tgz#d72625e2344a3656e3a3ad4fa749fa83299d82ff"
@@ -2829,7 +2822,7 @@ babel-eslint@^10.0.1, babel-eslint@^10.1.0:
eslint-visitor-keys "^1.0.0"
resolve "^1.12.0"
-babel-helper-vue-jsx-merge-props@^2.0.0, babel-helper-vue-jsx-merge-props@^2.0.2:
+babel-helper-vue-jsx-merge-props@^2.0.2:
version "2.0.3"
resolved "https://registry.yarnpkg.com/babel-helper-vue-jsx-merge-props/-/babel-helper-vue-jsx-merge-props-2.0.3.tgz#22aebd3b33902328e513293a8e4992b384f9f1b6"
integrity sha512-gsLiKK7Qrb7zYJNgiXKpXblxbV5ffSwR0f5whkPAaBAR4fhi6bwRZxX9wBlIc5M/v8CCkXUbXZL4N/nSE97cqg==
@@ -3059,7 +3052,7 @@ babel-preset-vue@^2.0.2:
babel-plugin-syntax-jsx "^6.18.0"
babel-plugin-transform-vue-jsx "^3.5.0"
-babel-runtime@6.x, babel-runtime@^6.22.0, babel-runtime@^6.26.0:
+babel-runtime@^6.22.0, babel-runtime@^6.26.0:
version "6.26.0"
resolved "https://registry.yarnpkg.com/babel-runtime/-/babel-runtime-6.26.0.tgz#965c7058668e82b55d7bfe04ff2337bc8b5647fe"
integrity sha1-llxwWGaOgrVde/4E/yM3vItWR/4=
@@ -4916,7 +4909,7 @@ deep-is@^0.1.3, deep-is@~0.1.3:
resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.3.tgz#b369d6fb5dbc13eecf524f91b070feedc357cf34"
integrity sha1-s2nW+128E+7PUk+RsHD+7cNXzzQ=
-deepmerge@^1.2.0, deepmerge@^1.5.2:
+deepmerge@^1.5.2:
version "1.5.2"
resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-1.5.2.tgz#10499d868844cdad4fee0842df8c7f6f0c95a753"
integrity sha512-95k0GDqvBjZavkuvzx/YqVLv/6YYa17fz6ILMSf7neqQITCPbnfEnQvEgMPNjH4kgobe7+WIL0yJEHku+H3qtQ==
@@ -5296,18 +5289,6 @@ electron-to-chromium@^1.3.649:
resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.3.673.tgz#b4f81c930b388f962b7eba20d0483299aaa40913"
integrity sha512-ms+QR2ckfrrpEAjXweLx6kNCbpAl66DcW//3BZD4BV5KhUgr0RZRce1ON/9J3QyA3JO28nzgb5Xv8DnPr05ILg==
-element-ui@2.4.11:
- version "2.4.11"
- resolved "https://registry.yarnpkg.com/element-ui/-/element-ui-2.4.11.tgz#db6a2d37001b8fe5fff9f176fb58bb3908cfa9c9"
- integrity sha512-RtgK0t840NAFTajGMWvylzZRSX1EkZ7V4YgAoBxhv4TtkeMscLuk/IdYOzPdlQq6IN0byx1YVBxCX+u4yYkGvw==
- dependencies:
- async-validator "~1.8.1"
- babel-helper-vue-jsx-merge-props "^2.0.0"
- deepmerge "^1.2.0"
- normalize-wheel "^1.0.1"
- resize-observer-polyfill "^1.5.0"
- throttle-debounce "^1.0.1"
-
elliptic@^6.5.3:
version "6.5.4"
resolved "https://registry.yarnpkg.com/elliptic/-/elliptic-6.5.4.tgz#da37cebd31e79a1367e941b592ed1fbebd58abbb"
@@ -9795,11 +9776,6 @@ normalize-url@^3.0.0:
resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-3.3.0.tgz#b2e1c4dc4f7c6d57743df733a4f5978d18650559"
integrity sha512-U+JJi7duF1o+u2pynbp2zXDW2/PADgC30f0GsHZtRh+HOcXHnw137TrNlyxxRvWW5fjKd3bcLHPxofWuCjaeZg==
-normalize-wheel@^1.0.1:
- version "1.0.1"
- resolved "https://registry.yarnpkg.com/normalize-wheel/-/normalize-wheel-1.0.1.tgz#aec886affdb045070d856447df62ecf86146ec45"
- integrity sha1-rsiGr/2wRQcNhWRH32Ls+GFG7EU=
-
nouislider@^12.1.0:
version "12.1.0"
resolved "https://registry.yarnpkg.com/nouislider/-/nouislider-12.1.0.tgz#a4416b4b3357e77e52217f8ecf060eb14a855f59"
@@ -12704,11 +12680,6 @@ throat@^5.0.0:
resolved "https://registry.yarnpkg.com/throat/-/throat-5.0.0.tgz#c5199235803aad18754a667d659b5e72ce16764b"
integrity sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA==
-throttle-debounce@^1.0.1:
- version "1.1.0"
- resolved "https://registry.yarnpkg.com/throttle-debounce/-/throttle-debounce-1.1.0.tgz#51853da37be68a155cb6e827b3514a3c422e89cd"
- integrity sha512-XH8UiPCQcWNuk2LYePibW/4qL97+ZQ1AN3FNXwZRBNPPowo/NRU5fAlDCSNBJIYCKbioZfuYtMhG4quqoJhVzg==
-
through2@^2.0.0, through2@~2.0.3:
version "2.0.5"
resolved "https://registry.yarnpkg.com/through2/-/through2-2.0.5.tgz#01c1e39eb31d07cb7d03a96a70823260b23132cd"
diff --git a/login_server/CMakeLists.txt b/login_server/CMakeLists.txt
index d20dcdaf9..40954b5a7 100644
--- a/login_server/CMakeLists.txt
+++ b/login_server/CMakeLists.txt
@@ -19,9 +19,7 @@ include_directories(
"dependencies/mariadb-connector-c/include"
"dependencies/mariadb-connector-c/build/include"
"dependencies/spirit-po/include"
- "dependencies/grpc/include"
- "dependencies/grpc/third_party/protobuf/src"
- "dependencies/grpc/third_party/googletest/googletest/include"
+ "dependencies/protobuf/src"
"build"
"build/proto"
"build/http_pages"
@@ -39,56 +37,28 @@ IF(UNIX)
"dependencies/poco/NetSSL_OpenSSL/include"
)
ENDIF()
-############################## config and add grpc ###################################
-set(GRPC_PATH "${DEP_PATH}/grpc/build")
-set(GRPC_ABSL_PATH "${GRPC_PATH}/third_party/abseil-cpp/absl/types")
-set(GRPC_CARES_PATH "${GRPC_PATH}/third_party/cares/cares/lib")
-set(GRPC_BORING_SSL_PATH "${GRPC_PATH}/third_party/boringssl-with-bazel")
-set(GRPC_RE2_PATH "${GRPC_PATH}/third_party/re2")
-set(GRPC_PROTOBUF_PATH "${GRPC_PATH}/third_party/protobuf")
-
-if(WIN32)
- set(GRPC_PATH "${GRPC_PATH}/Debug")
- set(GRPC_ABSL_PATH "${GRPC_ABSL_PATH}/Debug")
- set(GRPC_CARES_PATH "${GRPC_CARES_PATH}/Debug")
- set(GRPC_BORING_SSL_PATH "${GRPC_CGRPC_BORING_SSL_PATHARES_PATH}/Debug")
- set(GRPC_RE2_PATH "${GRPC_RE2_PATH}/Debug")
- set(GRPC_PROTOBUF_DEBUG_PATH "${GRPC_PROTOBUF_PATH}/Debug")
-endif()
-
-
-set(BUILD_TESTING OFF)
-#set(gRPC_SSL_PROVIDER "package")
-add_subdirectory("dependencies/grpc/")
-#set(gRPC_SSL_PROVIDER "package")
-message(STATUS "Using gRPC via add_subdirectory.")
-
-set(GRPC_LIBS libprotobuf grpc++_reflection grpc++)
+############################## find protobuf #########################################
+add_subdirectory(dependencies/protobuf/cmake)
############################## parse protobuf files ###################################
FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/src/proto GRADIDO_PROTO_MODEL_PATH)
-FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/src/proto/hedera/hedera-protobuf/src/main/proto HEDERA_PROTO_MODEL_PATH)
FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/build/proto PROTOBINDING_PATH)
file(MAKE_DIRECTORY ${PROTOBINDING_PATH})
file(MAKE_DIRECTORY ${PROTOBINDING_PATH}/gradido)
-file(MAKE_DIRECTORY ${PROTOBINDING_PATH}/hedera)
FILE(GLOB DATAMODEL_GRADIDO_PROTOS "${GRADIDO_PROTO_MODEL_PATH}/gradido/*.proto")
-FILE(GLOB DATAMODEL_HEDERA_PROTOS "${HEDERA_PROTO_MODEL_PATH}/*.proto")
IF(WIN32)
- find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin PATHS "build/dependencies/grpc/bin/Debug")
- find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin PATHS "build/dependencies/grpc/bin/Release")
- find_program(PROTOBUF_PROTOC_EXECUTABLE protoc PATHS "build/dependencies/grpc/third_party/protobuf/bin/Debug" )
- find_program(PROTOBUF_PROTOC_EXECUTABLE protoc PATHS "build/dependencies/grpc/third_party/protobuf/bin/Release" )
+ set(PROTOC_BIN_PATH "build/dependencies/protobuf/cmake/bin")
+ find_program(PROTOBUF_PROTOC_EXECUTABLE protoc PATHS "${PROTOC_BIN_PATH}/Debug" )
+ find_program(PROTOBUF_PROTOC_EXECUTABLE protoc PATHS "${PROTOC_BIN_PATH}/Release" )
ELSE()
- find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin PATHS "build/dependencies/grpc/bin")
- find_program(PROTOBUF_PROTOC_EXECUTABLE protoc PATHS "build/dependencies/grpc/third_party/protobuf/bin" )
+ find_program(PROTOBUF_PROTOC_EXECUTABLE protoc PATHS "build/dependencies/protobuf/cmake/bin" )
ENDIF()
-FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/dependencies/grpc/third_party/protobuf/src GOOGLE_PROTOBUF_INCLUDES)
-MESSAGE("protoc: ${PROTOBUF_PROTOC_EXECUTABLE} in build/dependencies/grpc/bin/${CMAKE_BUILD_TYPE}")
+FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/dependencies/protobuf/src GOOGLE_PROTOBUF_INCLUDES)
+MESSAGE("protoc: ${PROTOBUF_PROTOC_EXECUTABLE} in build/dependencies/protobuf/bin/${CMAKE_BUILD_TYPE}")
FOREACH(proto ${DATAMODEL_GRADIDO_PROTOS})
FILE(TO_NATIVE_PATH ${proto} proto_native)
get_filename_component(proto_parsed ${proto} NAME_WLE)
@@ -113,30 +83,6 @@ FOREACH(proto ${DATAMODEL_GRADIDO_PROTOS})
ENDFOREACH(proto)
-FOREACH(proto ${DATAMODEL_HEDERA_PROTOS})
- FILE(TO_NATIVE_PATH ${proto} proto_native)
- get_filename_component(proto_parsed ${proto} NAME_WLE)
- FILE(TO_NATIVE_PATH ${PROTOBINDING_PATH}/hedera/${proto_parsed}.pb.h proto_parsed_native)
- IF(${proto_native} IS_NEWER_THAN ${proto_parsed_native})
- EXECUTE_PROCESS(
- COMMAND
- ${PROTOBUF_PROTOC_EXECUTABLE}
- --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN}
- --proto_path=${HEDERA_PROTO_MODEL_PATH}
- --proto_path=${GOOGLE_PROTOBUF_INCLUDES}
- --cpp_out=${PROTOBINDING_PATH}/hedera
- --grpc_out ${PROTOBINDING_PATH}/hedera
- ${proto_native}
- RESULT_VARIABLE rv
- )
- # Optional, but that can show the user if something have gone wrong with the proto generation
- IF(${rv})
- MESSAGE("Generation of data model returned ${rv} for proto ${proto_native}")
- ELSE()
- MESSAGE("Parsed: src/proto/hedera/hedera-protobuf/src/main/proto/${proto_parsed}.proto")
- ENDIF()
- ENDIF()
-ENDFOREACH(proto)
############################## parse cpsp Files ####################################
@@ -212,13 +158,11 @@ FILE(GLOB LIB_SRC "src/cpp/lib/*.h" "src/cpp/lib/*.cpp")
FILE(GLOB MODEL "src/cpp/model/*.h" "src/cpp/model/*.cpp")
FILE(GLOB MODEL_TABLE "src/cpp/model/table/*.h" "src/cpp/model/table/*.cpp")
FILE(GLOB MODEL_EMAIL "src/cpp/model/email/*.h" "src/cpp/model/email/*.cpp")
-FILE(GLOB MODEL_HEDERA "src/cpp/model/hedera/*.h" "src/cpp/model/hedera/*.cpp")
FILE(GLOB MODEL_GRADIDO "src/cpp/model/gradido/*.h" "src/cpp/model/gradido/*.cpp")
FILE(GLOB CRYPTO "src/cpp/Crypto/*.h" "src/cpp/Crypto/*.cpp")
FILE(GLOB MAIN "src/cpp/*.cpp" "src/cpp/*.c" "src/cpp/*.h")
FILE(GLOB MYSQL "src/cpp/MySQL/*.cpp" "src/cpp/MySQL/*.h" "src/cpp/MySQL/Poco/*.h")
FILE(GLOB PROTO_GRADIDO "build/proto/gradido/*.cc" "build/proto/gradido/*.h")
-FILE(GLOB PROTO_HEDERA "build/proto/hedera/*.cc" "build/proto/hedera/*.h")
# used only for test project
FILE(GLOB TEST "src/cpp/test/*.cpp" "src/cpp/test/*.h")
@@ -230,9 +174,9 @@ FILE(GLOB TEST_CONTROLLER "src/cpp/test/controller/*.cpp" "src/cpp/test/controll
SET(LOCAL_SRCS
${CONTROLLER} ${TINF} ${MAIN} ${HTTPInterface} ${COMPILED_PAGES}
${JSONInterface} ${CRYPTO}
- ${MODEL} ${MODEL_TABLE} ${MODEL_EMAIL} ${MODEL_HEDERA} ${MODEL_GRADIDO}
+ ${MODEL} ${MODEL_TABLE} ${MODEL_EMAIL} ${MODEL_GRADIDO}
${SINGLETON_MANAGER} ${LIB_SRC} ${MYSQL} ${TASKS}
- ${PROTO_GRADIDO} ${PROTO_HEDERA}
+ ${PROTO_GRADIDO}
)
SET(LOCAL_TEST_SRC
${TEST} ${TEST_CRYPTO} ${TEST_MODEL} ${TEST_MODEL_TABLE} ${TEST_CONTROLLER}
@@ -243,13 +187,11 @@ if(MSVC)
# src
source_group("controller" FILES ${CONTROLLER})
source_group("proto\\gradido" FILES ${PROTO_GRADIDO})
- source_group("proto\\hedera" FILES ${PROTO_HEDERA})
source_group("tinf" FILES ${TINF})
source_group("Crypto" FILES ${CRYPTO})
source_group("tasks" FILES ${TASKS})
source_group("model\\table" FILES ${MODEL_TABLE})
source_group("model\\email" FILES ${MODEL_EMAIL})
- source_group("model\\hedera" FILES ${MODEL_HEDERA})
source_group("model\\gradido" FILES ${MODEL_GRADIDO})
source_group("model" FILES ${MODEL})
source_group("mysql" FILES ${MYSQL})
@@ -266,7 +208,6 @@ if(MSVC)
endif()
-
add_executable(Gradido_LoginServer ${LOCAL_SRCS})
############################## config and add mariadb ###################################
@@ -314,11 +255,11 @@ ENDIF()
target_link_libraries(Gradido_LoginServer ${GRPC_LIBS})
if(WIN32)
- target_link_libraries(Gradido_LoginServer mariadbclient ${CONAN_LIBS})
+ target_link_libraries(Gradido_LoginServer mariadbclient libprotobuf ${CONAN_LIBS})
#TARGET_LINK_LIBRARIES(Gradido_LoginServer optimized ${MYSQL_LIBRARIES} Shlwapi)
#TARGET_LINK_LIBRARIES(Gradido_LoginServer debug ${COMPILED_MARIADB_CLIENT_DEBUG} Shlwapi)
else() # unix
- target_link_libraries(Gradido_LoginServer ${POCO_LIBS} libmariadb sodium)
+ target_link_libraries(Gradido_LoginServer ${POCO_LIBS} libmariadb sodium libprotobuf)
endif()
# install
@@ -333,12 +274,66 @@ install(DIRECTORY src/LOCALE DESTINATION /etc/grd_login/
endif(UNIX)
+# ---------------------- Test -----------------------------------------
+
enable_testing()
-# ---------------------- Test -----------------------------------------
-#project(Gradido_LoginServer_Test C CXX)
+option(COLLECT_COVERAGE_DATA "Use cov to collect coverage informations" OFF)
+set(COVERAGE_TOOL "Coverage Tool (gcovr|lcov|fastcov)" CACHE STRING "gcovr")
+
+if(COLLECT_COVERAGE_DATA)
+
+ include(cmake/CodeCoverage.cmake)
+ append_coverage_compiler_flags()
+ set(EXCLUDE_FOR_HTML_COV
+ "${CMAKE_CURRENT_SOURCE_DIR}/build/proto/*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/src/cpp/test/*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/googletest/googletest/include/gtest/internal/*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/googletest/googletest/src/"
+ )
+ if("${COVERAGE_TOOL}" STREQUAL "gcovr")
+ setup_target_for_coverage_gcovr_html(
+ NAME coverage
+ EXECUTABLE Gradido_LoginServer_Test
+ EXCLUDE ${EXCLUDE_FOR_HTML_COV}
+ GCOVR_ADDITIONAL_ARGS "--txt "
+ #DEPENDENCIES lib/libmariadb.so.3
+ )
+ endif()
+
+ set(EXCLUDE_FOR_COV
+ ${EXCLUDE_FOR_HTML_COV}
+ "/usr/include/*"
+ )
+ if("${COVERAGE_TOOL}" STREQUAL "lcov")
+ setup_target_for_coverage_lcov(
+ NAME coverage
+ EXECUTABLE Gradido_LoginServer_Test
+ EXCLUDE "${EXCLUDE_FOR_COV}"
+ #DEPENDENCIES lib/libmariadb.so.3
+ )
+ endif()
+
+ if("${COVERAGE_TOOL}" STREQUAL "fastcov")
+ setup_target_for_coverage_fastcov(
+ NAME coverage # New target name
+ EXECUTABLE Gradido_LoginServer_Test -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
+ #BASE_DIRECTORY "../" # Base directory for report
+ # (defaults to PROJECT_SOURCE_DIR)
+ EXCLUDE "${EXCLUDE_FOR_COV}" # Patterns to exclude.
+ NO_DEMANGLE # Don't demangle C++ symbols
+ # even if c++filt is found
+ SKIP_HTML # Don't create html report
+ )
+ endif()
+
+endif()
+
+project(Gradido_LoginServer_Test C CXX)
#_TEST_BUILD
-#find_package(gtest)
+#find_package(GTest CONFIG REQUIRED)
+#add_subdirectory("dependencies/protobuf/third_party/googletest")
add_executable(Gradido_LoginServer_Test ${LOCAL_SRCS} ${LOCAL_TEST_SRC})
target_compile_definitions(Gradido_LoginServer_Test PUBLIC "_TEST_BUILD")
@@ -351,7 +346,7 @@ if(WIN32)
#TARGET_LINK_LIBRARIES(Gradido_LoginServer_Test debug ${COMPILED_MARIADB_CLIENT_DEBUG} Shlwapi)
#TARGET_LINK_LIBRARIES(Gradido_LoginServer_Test debug ${GRPC_LIBS} ${PROTOBUF_DEBUG_LIBS})
else()
- target_link_libraries(Gradido_LoginServer_Test ${POCO_LIBS} libmariadb sodium)
+ target_link_libraries(Gradido_LoginServer_Test ${POCO_LIBS} libmariadb sodium gtest)
endif()
add_test(NAME main COMMAND Gradido_LoginServer_Test)
diff --git a/login_server/CMakeLists.txt.lib b/login_server/CMakeLists.txt.lib
index bf62814c4..cb45dcfce 100644
--- a/login_server/CMakeLists.txt.lib
+++ b/login_server/CMakeLists.txt.lib
@@ -30,22 +30,16 @@ include_directories(
find_package(Protobuf REQUIRED)
include_directories(${Protobuf_INCLUDE_DIRS})
-FIND_PACKAGE(gRPC CONFIG REQUIRED)
-find_program(GRPC_CPP_PLUGIN grpc_cpp_plugin)
-
set(PROTOBUF_LIBS protobuf::libprotobuf protobuf::libprotobuf-lite protobuf::libprotoc)
############################## parse proto files ###################################
FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/src/proto GRADIDO_PROTO_MODEL_PATH)
-FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/src/proto/hedera/hedera-protobuf/src/main/proto HEDERA_PROTO_MODEL_PATH)
FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/build/proto PROTOBINDING_PATH)
file(MAKE_DIRECTORY ${PROTOBINDING_PATH})
file(MAKE_DIRECTORY ${PROTOBINDING_PATH}/gradido)
-file(MAKE_DIRECTORY ${PROTOBINDING_PATH}/hedera)
FILE(GLOB DATAMODEL_GRADIDO_PROTOS "${GRADIDO_PROTO_MODEL_PATH}/gradido/*.proto")
-FILE(GLOB DATAMODEL_HEDERA_PROTOS "${HEDERA_PROTO_MODEL_PATH}/*.proto")
FOREACH(proto ${DATAMODEL_GRADIDO_PROTOS})
FILE(TO_NATIVE_PATH ${proto} proto_native)
@@ -71,31 +65,6 @@ FOREACH(proto ${DATAMODEL_GRADIDO_PROTOS})
ENDFOREACH(proto)
-FOREACH(proto ${DATAMODEL_HEDERA_PROTOS})
- FILE(TO_NATIVE_PATH ${proto} proto_native)
- get_filename_component(proto_parsed ${proto} NAME_WLE)
- FILE(TO_NATIVE_PATH ${PROTOBINDING_PATH}/hedera/${proto_parsed}.pb.h proto_parsed_native)
- IF(${proto_native} IS_NEWER_THAN ${proto_parsed_native})
- EXECUTE_PROCESS(
- COMMAND
- ${PROTOBUF_PROTOC_EXECUTABLE}
- --plugin=protoc-gen-grpc=${GRPC_CPP_PLUGIN}
- --proto_path=${HEDERA_PROTO_MODEL_PATH}
- --proto_path=${GOOGLE_PROTOBUF_INCLUDES}
- --cpp_out=${PROTOBINDING_PATH}/hedera
- --grpc_out ${PROTOBINDING_PATH}/hedera
- ${proto_native}
- RESULT_VARIABLE rv
- )
- # Optional, but that can show the user if something have gone wrong with the proto generation
- IF(${rv})
- MESSAGE("Generation of data model returned ${rv} for proto ${proto_native}")
- ELSE()
- MESSAGE("Parsed: src/proto/hedera/hedera-protobuf/src/main/proto/${proto_parsed}.proto")
- ENDIF()
- ENDIF()
-ENDFOREACH(proto)
-
############################## parse cpsp Files ####################################
FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/src/cpsp GRADIDO_CPSP_PAGE_SRC_PATH)
FILE(TO_NATIVE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/build/http_pages GRADIDO_HTTP_PAGES_PATH)
@@ -153,7 +122,6 @@ FILE(GLOB CRYPTO "src/cpp/Crypto/*.h" "src/cpp/Crypto/*.cpp")
FILE(GLOB MAIN "src/cpp/*.cpp" "src/cpp/*.c" "src/cpp/*.h")
FILE(GLOB MYSQL "src/cpp/MySQL/*.cpp" "src/cpp/MySQL/*.h" "src/cpp/MySQL/Poco/*.h")
FILE(GLOB PROTO_GRADIDO "${PROTOBINDING_PATH}/gradido/*.cc" "${PROTOBINDING_PATH}/gradido/*.h")
-FILE(GLOB PROTO_HEDERA "${PROTOBINDING_PATH}/hedera/*.cc" "${PROTOBINDING_PATH}/hedera/*.h")
# used only for test project
FILE(GLOB TEST "src/cpp/test/*.cpp" "src/cpp/test/*.h")
@@ -204,5 +172,83 @@ set(POCO_LIBS ${POCO_FOUNDATION_LIB} ${POCO_UTIL_LIB} ${POCO_NET_SSL_LIB} ${POCO
############################## build login server ###################################
-target_link_libraries(Gradido_LoginServer gRPC::grpc++ ${PROTOBUF_LIBS} ${MYSQL_LIBRARIES} ${POCO_LIBS} sodium pthread)
+target_link_libraries(Gradido_LoginServer ${PROTOBUF_LIBS} ${MYSQL_LIBRARIES} ${POCO_LIBS} sodium pthread)
+############################## build login server test ###################################
+IF(CMAKE_BUILD_TYPE STREQUAL "Debug")
+ project(Gradido_LoginServer_Test C CXX)
+
+ enable_testing()
+
+ option(COLLECT_COVERAGE_DATA "Use cov to collect coverage informations" OFF)
+ set(COVERAGE_TOOL "Coverage Tool (gcovr|lcov|fastcov)" CACHE STRING "gcovr")
+
+
+ if(COLLECT_COVERAGE_DATA)
+
+ include(cmake/CodeCoverage.cmake)
+ append_coverage_compiler_flags()
+ set(EXCLUDE_FOR_HTML_COV
+ "${CMAKE_CURRENT_SOURCE_DIR}/build/proto/*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/dependencies/*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/src/cpp/test/*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/googletest/googletest/include/gtest/internal/*"
+ "${CMAKE_CURRENT_SOURCE_DIR}/googletest/googletest/src/"
+ )
+ if("${COVERAGE_TOOL}" STREQUAL "gcovr")
+ setup_target_for_coverage_gcovr_html(
+ NAME coverage
+ EXECUTABLE Gradido_LoginServer_Test
+ EXCLUDE ${EXCLUDE_FOR_HTML_COV}
+ GCOVR_ADDITIONAL_ARGS "--txt "
+ #DEPENDENCIES lib/libmariadb.so.3
+ )
+ endif()
+
+ set(EXCLUDE_FOR_COV
+ ${EXCLUDE_FOR_HTML_COV}
+ "/usr/include/*"
+ )
+ if("${COVERAGE_TOOL}" STREQUAL "lcov")
+ setup_target_for_coverage_lcov(
+ NAME coverage
+ EXECUTABLE Gradido_LoginServer_Test
+ EXCLUDE "${EXCLUDE_FOR_COV}"
+ #DEPENDENCIES lib/libmariadb.so.3
+ )
+ endif()
+
+ if("${COVERAGE_TOOL}" STREQUAL "fastcov")
+ setup_target_for_coverage_fastcov(
+ NAME coverage # New target name
+ EXECUTABLE Gradido_LoginServer_Test -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
+ #BASE_DIRECTORY "coverage" # Base directory for report
+ # (defaults to PROJECT_SOURCE_DIR)
+ EXCLUDE "${EXCLUDE_FOR_COV}" # Patterns to exclude.
+ NO_DEMANGLE # Don't demangle C++ symbols
+ # even if c++filt is found
+ SKIP_HTML # Don't create html report
+ )
+ endif()
+
+ endif()
+ #_TEST_BUILD
+
+ add_subdirectory("googletest")
+
+ add_executable(Gradido_LoginServer_Test ${LOCAL_SRCS} ${LOCAL_TEST_SRC})
+ target_compile_definitions(Gradido_LoginServer_Test PUBLIC "_TEST_BUILD")
+
+ target_link_libraries(Gradido_LoginServer_Test ${GRPC_LIBS} )
+
+ if(WIN32)
+ target_link_libraries(Gradido_LoginServer_Test ${CONAN_LIBS} )
+ #TARGET_LINK_LIBRARIES(Gradido_LoginServer_Test optimized ${MYSQL_LIBRARIES} Shlwapi)
+ #TARGET_LINK_LIBRARIES(Gradido_LoginServer_Test debug ${COMPILED_MARIADB_CLIENT_DEBUG} Shlwapi)
+ #TARGET_LINK_LIBRARIES(Gradido_LoginServer_Test debug ${GRPC_LIBS} ${PROTOBUF_DEBUG_LIBS})
+ else()
+ target_link_libraries(Gradido_LoginServer_Test ${PROTOBUF_LIBS} ${MYSQL_LIBRARIES} ${POCO_LIBS} sodium pthread gtest)
+ endif()
+
+ add_test(NAME main COMMAND Gradido_LoginServer_Test)
+ENDIF()
\ No newline at end of file
diff --git a/login_server/Dockerfile b/login_server/Dockerfile
index 83adec256..cd14eb73b 100644
--- a/login_server/Dockerfile
+++ b/login_server/Dockerfile
@@ -1,13 +1,96 @@
+
+#########################################################################################################
+# Prepare debug
+#########################################################################################################
+FROM gradido/login_dependencies:gcc9-debug-3 as prepare_debug
+
+ENV DOCKER_WORKDIR="/code"
+WORKDIR ${DOCKER_WORKDIR}
+
+RUN echo '/usr/local/lib' >> /etc/ld.so.conf && ldconfig
+
+COPY ./CMakeLists.txt.lib ./CMakeLists.txt
+RUN ln -s /usr/local/googletest ./googletest
+COPY ./src ./src
+COPY ./cmake/CodeCoverage.cmake ./cmake/CodeCoverage.cmake
+COPY ./dependencies/cmake-modules ./dependencies/cmake-modules
+COPY ./dependencies/spirit-po ./dependencies/spirit-po
+COPY ./dependencies/tinf ./dependencies/tinf
+COPY ./scripts ./scripts
+
+
+#########################################################################################################
+# Install Coverage tool
+#########################################################################################################
+FROM prepare_debug as coverage
+
+
+RUN apt-get update && \
+ apt-get install -y --no-install-recommends python3-pip && \
+ apt-get autoclean && \
+ apt-get autoremove && \
+ apt-get clean && \
+ rm -rf /var/lib/apt/lists/*
+
+RUN pip3 install gcovr setuptools wheel && \
+ pip3 install fastcov
+
+
+#########################################################################################################
+# Build test
+#########################################################################################################
+FROM coverage as test
+
+ENV DOCKER_WORKDIR="/code"
+WORKDIR ${DOCKER_WORKDIR}
+
+
+RUN if [ ! -d "./build_cov" ] ; then mkdir build_cov; fi
+
+RUN cd build_cov && \
+ cmake -DCMAKE_BUILD_TYPE=Debug -DCOLLECT_COVERAGE_DATA=ON -DCOVERAGE_TOOL=fastcov ..
+ #make -j$(nproc) Gradido_LoginServer_Test
+
+#RUN chmod +x build_cov/bin/Gradido_LoginServer_Test
+#CMD gdb -ex run ./build_cov/bin/Gradido_LoginServer_Test
+#CMD ./build_cov/bin/Gradido_LoginServer_Test
+
+#ENTRYPOINT make -C build_cov coverage
+CMD cd build_cov && make -j$(nproc) Gradido_LoginServer_Test && make coverage && \
+ if [ ! -d "./coverage" ] ; then mkdir coverage; fi && \
+ cp coverage.info ./coverage/
+
+#########################################################################################################
+# Build debug
+#########################################################################################################
+FROM prepare_debug as debug
+
+ENV DOCKER_WORKDIR="/code"
+WORKDIR ${DOCKER_WORKDIR}
+
+RUN mkdir build && \
+ cd build && \
+ cmake -DCMAKE_BUILD_TYPE=Debug .. && \
+ make -j$(nproc) Gradido_LoginServer
+
+RUN cd scripts && \
+ chmod +x compile_pot.sh && \
+ ./compile_pot.sh
+
+RUN chmod +x build/bin/Gradido_LoginServer
+ENTRYPOINT ["build/bin/Gradido_LoginServer"]
+
#########################################################################################################
# Build release
#########################################################################################################
-FROM gradido/login_dependencies:alpine-release-1 as release
+FROM gradido/login_dependencies:alpine-release-3 as release
ENV DOCKER_WORKDIR="/code"
WORKDIR ${DOCKER_WORKDIR}
COPY ./CMakeLists.txt.lib ./CMakeLists.txt
COPY ./src ./src
+RUN ln -s /usr/local/googletest ./googletest
COPY ./dependencies/cmake-modules ./dependencies/cmake-modules
COPY ./dependencies/spirit-po ./dependencies/spirit-po
COPY ./dependencies/tinf ./dependencies/tinf
@@ -35,10 +118,11 @@ WORKDIR "/usr/bin"
COPY --from=release /code/build/bin/Gradido_LoginServer /usr/bin/
COPY --from=release /usr/local/lib/mariadb/libmariadb.so.3 /usr/local/lib/
-COPY --from=release /usr/local/lib/libPoco* /usr/local/lib/
-COPY --from=release /usr/lib/libsodium.so.23 /usr/lib/
-COPY --from=release /usr/lib/libstdc++.so.6 /usr/lib/
-COPY --from=release /usr/lib/libgcc_s.so.1 /usr/lib/
+COPY --from=release /usr/local/lib/libPoco* /usr/local/lib/
+COPY --from=release /usr/local/lib/libproto* /usr/local/lib/
+COPY --from=release /usr/lib/libsodium.so.23 /usr/lib/
+COPY --from=release /usr/lib/libstdc++.so.6 /usr/lib/
+COPY --from=release /usr/lib/libgcc_s.so.1 /usr/lib/
RUN chmod +x /usr/bin/Gradido_LoginServer
diff --git a/login_server/Dockerfile.alpine-debug b/login_server/Dockerfile.alpine-debug
index 948d434d1..e1f168586 100644
--- a/login_server/Dockerfile.alpine-debug
+++ b/login_server/Dockerfile.alpine-debug
@@ -1,4 +1,4 @@
-FROM gradido/login_dependencies:alpine-debug-1 as login_server_alpine_debug
+FROM gradido/login_dependencies:alpine-debug-3 as login_server_alpine_debug
ENV DOCKER_WORKDIR="/code"
@@ -9,6 +9,8 @@ WORKDIR ${DOCKER_WORKDIR}
COPY ./CMakeLists.txt.lib ./CMakeLists.txt
COPY ./scripts ./scripts
+COPY ./cmake ./cmake
+RUN ln -s /usr/local/googletest ./googletest
CMD cd scripts; ./build_debug.sh; cd ..; ./build/bin/Gradido_LoginServer
diff --git a/login_server/Dockerfile.debug b/login_server/Dockerfile.debug
deleted file mode 100644
index 613c3daf4..000000000
--- a/login_server/Dockerfile.debug
+++ /dev/null
@@ -1,60 +0,0 @@
-#########################################################################################################
-# cmake
-#########################################################################################################
-FROM gcc:9 as cmake-gcc-9
-
-ENV DOCKER_WORKDIR="/code"
-RUN mkdir -p ${DOCKER_WORKDIR}
-WORKDIR ${DOCKER_WORKDIR}
-
-USER root
-
-RUN git clone https://github.com/Kitware/CMake.git --branch=v3.19.8 \
- && cd CMake \
- && ./bootstrap \
- && make -j$(nproc) \
- && make install
-
-#########################################################################################################
-# Build debug
-#########################################################################################################
-From gradido/login_dependencies:stage2 as debug
-
-ENV DOCKER_WORKDIR="/code"
-
-USER root
-
-WORKDIR ${DOCKER_WORKDIR}
-COPY . .
-
-RUN cd scripts \
- && chmod +x ./prepare_build.sh \
- && ./prepare_build.sh
-
-RUN ./compile_pot.sh
-RUN ./unix_parse_proto.sh
-
-
-#########################################################################################################
-# run debug
-#########################################################################################################
-FROM debug as login_server_debug
-
-ENV DOCKER_WORKDIR="/code"
-#RUN apt-get update && \
-# apt-get install -y --no-install-recommends gdb && \
-# apt-get autoclean && \
-# apt-get autoremove && \
-# apt-get clean && \
-# rm -rf /var/lib/apt/lists/*
-
-VOLUME /var/log/grd_login
-VOLUME /code/src
-
-EXPOSE 1200
-EXPOSE 1201
-WORKDIR ${DOCKER_WORKDIR}
-RUN chmod +x ./scripts/build_and_run.sh
-
-CMD ./Dockerfiles/build_and_run.sh; ./build_vol/bin/Gradido_LoginServer
-
diff --git a/login_server/Dockerfiles/Dockerfile.default b/login_server/Dockerfiles/Dockerfile.default
new file mode 100644
index 000000000..4be44dfd0
--- /dev/null
+++ b/login_server/Dockerfiles/Dockerfile.default
@@ -0,0 +1,58 @@
+
+#########################################################################################################
+# Build release
+#########################################################################################################
+FROM gradido/login_dependencies:alpine-release-3 as release_default
+
+ENV DOCKER_WORKDIR="/code"
+WORKDIR ${DOCKER_WORKDIR}
+
+COPY ./login_server/CMakeLists.txt.lib ./CMakeLists.txt
+COPY ./login_server/src ./src
+COPY ./login_server/dependencies/cmake-modules ./dependencies/cmake-modules
+COPY ./login_server/dependencies/spirit-po ./dependencies/spirit-po
+COPY ./login_server/dependencies/tinf ./dependencies/tinf
+COPY ./login_server/scripts ./scripts
+
+RUN mkdir build && \
+ cd build && \
+ cmake -DCMAKE_BUILD_TYPE=Release .. && \
+ make -j$(nproc) Gradido_LoginServer
+
+RUN cd scripts && \
+ chmod +x compile_pot.sh && \
+ ./compile_pot.sh
+
+
+#########################################################################################################
+# run release with docker default config
+#########################################################################################################
+#From alpine:latest as login_server
+FROM alpine:3.13.5 as login_server_default
+
+USER root
+WORKDIR "/usr/bin"
+
+COPY --from=release_default /code/build/bin/Gradido_LoginServer /usr/bin/
+
+COPY --from=release_default /usr/local/lib/mariadb/libmariadb.so.3 /usr/local/lib/
+COPY --from=release_default /usr/local/lib/libPoco* /usr/local/lib/
+COPY --from=release_default /usr/lib/libsodium.so.23 /usr/lib/
+COPY --from=release_default /usr/lib/libstdc++.so.6 /usr/lib/
+COPY --from=release_default /usr/lib/libgcc_s.so.1 /usr/lib/
+
+COPY ./configs/login_server/grd_login.properties /etc/grd_login/
+COPY ./configs/login_server/cacert.pem /etc/grd_login/
+COPY ./configs/login_server/LOCALE /etc/grd_login/
+
+EXPOSE 1200
+EXPOSE 1201
+
+RUN chmod +x /usr/bin/Gradido_LoginServer
+ENTRYPOINT ["/usr/bin/Gradido_LoginServer"]
+#CMD Gradido_LoginServer
+
+
+
+
+
diff --git a/login_server/Dockerfiles/Dockerfile.dependencies b/login_server/Dockerfiles/Dockerfile.dependencies
index 79a573ea2..bc2cd1fd2 100644
--- a/login_server/Dockerfiles/Dockerfile.dependencies
+++ b/login_server/Dockerfiles/Dockerfile.dependencies
@@ -1,11 +1,8 @@
-#########################################################################################################
-# gcc 9 with libssl
-#########################################################################################################
-FROM gcc:9 as gcc_9_libssl
-USER root
+##### BUILD-ENV #####
+FROM gcc:9 as gcc9_build
RUN apt-get update && \
- apt-get install -y --no-install-recommends libssl-dev libboost-dev && \
+ apt-get install -y --no-install-recommends libssl-dev libboost-dev gettext libsodium-dev lcov && \
apt-get autoclean && \
apt-get autoremove && \
apt-get clean && \
@@ -15,79 +12,73 @@ RUN apt-get update && \
#########################################################################################################
# gcc 9 cmake
#########################################################################################################
-FROM gcc_9_libssl as gcc_9_cmake
-
-USER root
-ENV DOCKER_WORKDIR="/code"
-
-RUN mkdir -p ${DOCKER_WORKDIR}
-WORKDIR ${DOCKER_WORKDIR}
-
+FROM gcc9_build as gcc_9_cmake
RUN git clone https://github.com/Kitware/CMake.git --branch=v3.19.8 && \
cd CMake && \
./bootstrap --parallel=$(nproc) && \
make -j$(nproc) && \
- make install && \
- cd .. && \
- rm -rf CMake
+ make install
+
+######### BUILD grpc ##############
+FROM gcc_9_cmake as gcc_9_protobuf
+
+ARG BUILD_TYPE=Debug
+
+RUN git clone https://github.com/protocolbuffers/protobuf.git --recursive -j4 && \
+ cd protobuf && \
+ ./autogen.sh && \
+ ./configure && \
+ make -j$(nproc) && \
+ make install && \
+ ldconfig
+
+# protobuf libs missing after make install
+#RUN cp grpc/build/third_party/protobuf/*.a /usr/local/lib/
+
+######### BUILD poco ##############
+FROM gcc_9_cmake as gcc_9_poco
+
+ARG BUILD_TYPE=Debug
+
+RUN git clone https://github.com/pocoproject/poco.git --recursive && \
+ cd poco && \
+ git checkout poco-1.9.4-release && \
+ mkdir cmake-build && cd cmake-build && \
+ cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE .. && make -j$(nproc) && \
+ make install
+
+######### BUILD mariadb ###########
+FROM gcc_9_cmake as gcc_9_mariadb-connector
+
+ARG BUILD_TYPE=Debug
+
+RUN git clone https://github.com/mariadb-corporation/mariadb-connector-c.git && \
+ cd mariadb-connector-c && \
+ git checkout 159540f && \
+ mkdir build && cd build && \
+ cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE .. && make -j$(nproc) && \
+ make install
#########################################################################################################
-# debug build preparation
+# builded libs and binaries
#########################################################################################################
-FROM gcc_9_libssl as build_debug_dependencies
+FROM gcc9_build as gcc9_libs
-USER root
-ENV DOCKER_WORKDIR="/code"
+RUN echo '/usr/local/lib' >> /etc/ld.so.conf && ldconfig
-RUN mkdir -p ${DOCKER_WORKDIR}
-WORKDIR ${DOCKER_WORKDIR}
-
-# copy CMake from last stage
+# copy CMake from cmake stage
COPY --from=gcc_9_cmake /usr/local/bin/cmake /usr/local/bin/cmake
COPY --from=gcc_9_cmake /usr/local/share/cmake-3.19/Modules /usr/local/share/cmake-3.19/Modules
COPY --from=gcc_9_cmake /usr/local/share/cmake-3.19/Templates /usr/local/share/cmake-3.19/Templates
-COPY ./dependencies ./dependencies
-COPY ./scripts ./scripts
-COPY ./CMakeLists.txt .
-COPY ./src ./src
+# copy from grpc
+COPY --from=gcc_9_protobuf /usr/local /usr/local
+COPY --from=gcc_9_protobuf /protobuf/third_party/googletest /usr/local/googletest
+# COPY from poco
+COPY --from=gcc_9_poco /usr/local /usr/local
-RUN cd scripts && \
- chmod +x ./prepare_build.sh && \
- ./prepare_build.sh && \
- mkdir ../build && \
- chmod +x ./build_debug.sh && \
- ./build_debug.sh
-
-# remove unneccessary stuff
-RUN rm -rf build/bin/Gradido_LoginServer
-
-#########################################################################################################
-# debug build
-#########################################################################################################
-FROM gcc_9_libssl as build_debug
-
-USER root
-ENV DOCKER_WORKDIR="/code"
-
-RUN mkdir -p ${DOCKER_WORKDIR}
-WORKDIR ${DOCKER_WORKDIR}
-
-
-# copy CMake from last stage
-COPY --from=build_debug_dependencies /usr/local/bin/cmake /usr/local/bin/cmake
-COPY --from=build_debug_dependencies /usr/local/share/cmake-3.19 /usr/local/share/cmake-3.19
-
-COPY --from=build_debug_dependencies /code/build/bin /code/build/bin
-COPY --from=build_debug_dependencies /code/build/lib /code/build/lib
-
-# grpc
-COPY --from=build_debug_dependencies /code/build/dependencies/grpc/lib /build/dependencies/grpc/lib
-COPY --from=build_debug_dependencies /code/build/dependencies/grpc/third_party/protobuf/lib /build/dependencies/grpc/third_party/protobuf/lib
-COPY --from=build_debug_dependencies /code/build/dependencies/grpc/third_party/re2/lib /build/dependencies/grpc/third_party/re2/lib
-COPY --from=build_debug_dependencies /code/build/dependencies/grpc/third_party/zlib/lib /build/dependencies/grpc/third_party/zlib/lib
-COPY --from=build_debug_dependencies /code/build/dependencies/grpc/third_party/cares/cares/lib /build/dependencies/grpc/third_party/cares/cares/lib
-COPY --from=build_debug_dependencies /code/build/dependencies/mariadb-connector-c/libmariadb/lib /build/dependencies/mariadb-connector-c/libmariadb/lib
+# COPY from mariadb
+COPY --from=gcc_9_mariadb-connector /usr/local /usr/local
diff --git a/login_server/Dockerfiles/Dockerfile.dependencies-alpine b/login_server/Dockerfiles/Dockerfile.dependencies-alpine
index a2cc3225c..c388d528c 100644
--- a/login_server/Dockerfiles/Dockerfile.dependencies-alpine
+++ b/login_server/Dockerfiles/Dockerfile.dependencies-alpine
@@ -2,8 +2,8 @@
##### BUILD-ENV #####
FROM alpine:3.13.5 as alpine-build
-RUN apk add --update --no-cache icu-dev
-RUN apk add --no-cache git openssl-dev make gcc musl-dev g++ linux-headers libintl gettext-dev boost-dev libsodium-dev
+RUN apk add --update --no-cache icu-dev
+RUN apk add --no-cache git openssl-dev make gcc musl-dev g++ linux-headers libintl gettext-dev boost-dev libsodium-dev
##### CMAKE #####
@@ -16,21 +16,21 @@ RUN git clone https://github.com/Kitware/CMake.git --branch=v3.19.8 && \
make install
######### BUILD grpc ##############
-FROM alpine-gxx-cmake as alpine-gxx-grpc
+FROM alpine-gxx-cmake as alpine-gxx-protobuf
ARG BUILD_TYPE=Debug
-RUN git clone https://github.com/grpc/grpc.git --branch=v1.37.0 --recursive -j4 && \
- cd grpc && \
- mkdir build && cd build && \
- cmake -DCMAKE_BUILD_TYPE=$BUILD_TYPE .. && make -j$(nproc) && \
- make install
+RUN apk add --no-cache autoconf automake libtool curl unzip
-# abseil don't install themself correctly
-RUN cp -r grpc/third_party/abseil-cpp/absl /usr/local/include/
+RUN git clone https://github.com/protocolbuffers/protobuf.git --recursive -j4 && \
+ cd protobuf && \
+ ./autogen.sh && \
+ ./configure && \
+ make -j$(nproc) && \
+ make install
# protobuf libs missing after make install
-RUN cp grpc/build/third_party/protobuf/*.a /usr/local/lib/
+#RUN cp grpc/build/third_party/protobuf/*.a /usr/local/lib/
######### BUILD poco ##############
FROM alpine-gxx-cmake as alpine-gxx-poco
@@ -67,8 +67,7 @@ COPY --from=alpine-gxx-cmake /usr/local/share/cmake-3.19/Modules /usr/local/shar
COPY --from=alpine-gxx-cmake /usr/local/share/cmake-3.19/Templates /usr/local/share/cmake-3.19/Templates
# copy from grpc
-COPY --from=alpine-gxx-grpc /usr/local /usr/local
-
+COPY --from=alpine-gxx-protobuf /usr/local /usr/local
# COPY from poco
COPY --from=alpine-gxx-poco /usr/local /usr/local
@@ -76,4 +75,10 @@ COPY --from=alpine-gxx-poco /usr/local /usr/local
# COPY from mariadb
COPY --from=alpine-gxx-mariadb-connector /usr/local /usr/local
+#########################################################################################################
+# COPY Things only needed for testing
+#########################################################################################################
+FROM alpine-libs as alpine-libs-test
+
+COPY --from=alpine-gxx-protobuf /protobuf/third_party/googletest /usr/local/googletest
diff --git a/login_server/Dockerfiles/Dockerfile.protoc b/login_server/Dockerfiles/Dockerfile.protoc
deleted file mode 100644
index 7aef56f62..000000000
--- a/login_server/Dockerfiles/Dockerfile.protoc
+++ /dev/null
@@ -1,30 +0,0 @@
-#########################################################################################################
-# Build protoc
-#########################################################################################################
-FROM gcc:7.5 as protoc3.9.1_build
-RUN git clone --recurse-submodules https://github.com/protocolbuffers/protobuf.git
-WORKDIR /protobuf
-
-RUN git checkout v3.9.1
-RUN ./autogen.sh
-RUN ./configure --enable-static=yes
-RUN make -j$(nproc)
-#RUN make check
-
-CMD ["./protobuf"]
-
-#########################################################################################################
-# Store protoc
-#########################################################################################################
-FROM alpine:3.10 as protoc
-
-COPY --from=protoc3.9.1_build /protobuf/src/.libs/protoc /usr/bin/
-COPY --from=protoc3.9.1_build /protobuf/src/.libs/libprotobuf.so.20.0.1 /usr/lib/libprotobuf.so.20
-COPY --from=protoc3.9.1_build /protobuf/src/.libs/libprotoc.so.20.0.1 /usr/lib/libprotoc.so.20
-COPY --from=protoc3.9.1_build /protobuf/src/google/protobuf/*.proto /usr/include/google/protobuf/
-COPY --from=protoc3.9.1_build /protobuf/src/google/protobuf/*.h /usr/include/google/protobuf/
-
-## build with:
-# docker build . -f Dockefile.protoc -t gradido/protoc:3.9.1
-## upload (login to docker hub on shell before):
-# docker push gradido/protoc:3.9.1
\ No newline at end of file
diff --git a/login_server/cmake/CodeCoverage.cmake b/login_server/cmake/CodeCoverage.cmake
new file mode 100644
index 000000000..62f64bf75
--- /dev/null
+++ b/login_server/cmake/CodeCoverage.cmake
@@ -0,0 +1,682 @@
+# Copyright (c) 2012 - 2017, Lars Bilke
+# All rights reserved.
+#
+# Redistribution and use in source and binary forms, with or without modification,
+# are permitted provided that the following conditions are met:
+#
+# 1. Redistributions of source code must retain the above copyright notice, this
+# list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above copyright notice,
+# this list of conditions and the following disclaimer in the documentation
+# and/or other materials provided with the distribution.
+#
+# 3. Neither the name of the copyright holder nor the names of its contributors
+# may be used to endorse or promote products derived from this software without
+# specific prior written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
+# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+# ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+#
+# CHANGES:
+#
+# 2012-01-31, Lars Bilke
+# - Enable Code Coverage
+#
+# 2013-09-17, Joakim Söderberg
+# - Added support for Clang.
+# - Some additional usage instructions.
+#
+# 2016-02-03, Lars Bilke
+# - Refactored functions to use named parameters
+#
+# 2017-06-02, Lars Bilke
+# - Merged with modified version from github.com/ufz/ogs
+#
+# 2019-05-06, Anatolii Kurotych
+# - Remove unnecessary --coverage flag
+#
+# 2019-12-13, FeRD (Frank Dana)
+# - Deprecate COVERAGE_LCOVR_EXCLUDES and COVERAGE_GCOVR_EXCLUDES lists in favor
+# of tool-agnostic COVERAGE_EXCLUDES variable, or EXCLUDE setup arguments.
+# - CMake 3.4+: All excludes can be specified relative to BASE_DIRECTORY
+# - All setup functions: accept BASE_DIRECTORY, EXCLUDE list
+# - Set lcov basedir with -b argument
+# - Add automatic --demangle-cpp in lcovr, if 'c++filt' is available (can be
+# overridden with NO_DEMANGLE option in setup_target_for_coverage_lcovr().)
+# - Delete output dir, .info file on 'make clean'
+# - Remove Python detection, since version mismatches will break gcovr
+# - Minor cleanup (lowercase function names, update examples...)
+#
+# 2019-12-19, FeRD (Frank Dana)
+# - Rename Lcov outputs, make filtered file canonical, fix cleanup for targets
+#
+# 2020-01-19, Bob Apthorpe
+# - Added gfortran support
+#
+# 2020-02-17, FeRD (Frank Dana)
+# - Make all add_custom_target()s VERBATIM to auto-escape wildcard characters
+# in EXCLUDEs, and remove manual escaping from gcovr targets
+#
+# 2021-01-19, Robin Mueller
+# - Add CODE_COVERAGE_VERBOSE option which will allow to print out commands which are run
+# - Added the option for users to set the GCOVR_ADDITIONAL_ARGS variable to supply additional
+# flags to the gcovr command
+#
+# 2020-05-04, Mihchael Davis
+# - Add -fprofile-abs-path to make gcno files contain absolute paths
+# - Fix BASE_DIRECTORY not working when defined
+# - Change BYPRODUCT from folder to index.html to stop ninja from complaining about double defines
+# USAGE:
+#
+# 1. Copy this file into your cmake modules path.
+#
+# 2. Add the following line to your CMakeLists.txt (best inside an if-condition
+# using a CMake option() to enable it just optionally):
+# include(CodeCoverage)
+#
+# 3. Append necessary compiler flags:
+# append_coverage_compiler_flags()
+#
+# 3.a (OPTIONAL) Set appropriate optimization flags, e.g. -O0, -O1 or -Og
+#
+# 4. If you need to exclude additional directories from the report, specify them
+# using full paths in the COVERAGE_EXCLUDES variable before calling
+# setup_target_for_coverage_*().
+# Example:
+# set(COVERAGE_EXCLUDES
+# '${PROJECT_SOURCE_DIR}/src/dir1/*'
+# '/path/to/my/src/dir2/*')
+# Or, use the EXCLUDE argument to setup_target_for_coverage_*().
+# Example:
+# setup_target_for_coverage_lcov(
+# NAME coverage
+# EXECUTABLE testrunner
+# EXCLUDE "${PROJECT_SOURCE_DIR}/src/dir1/*" "/path/to/my/src/dir2/*")
+#
+# 4.a NOTE: With CMake 3.4+, COVERAGE_EXCLUDES or EXCLUDE can also be set
+# relative to the BASE_DIRECTORY (default: PROJECT_SOURCE_DIR)
+# Example:
+# set(COVERAGE_EXCLUDES "dir1/*")
+# setup_target_for_coverage_gcovr_html(
+# NAME coverage
+# EXECUTABLE testrunner
+# BASE_DIRECTORY "${PROJECT_SOURCE_DIR}/src"
+# EXCLUDE "dir2/*")
+#
+# 5. Use the functions described below to create a custom make target which
+# runs your test executable and produces a code coverage report.
+#
+# 6. Build a Debug build:
+# cmake -DCMAKE_BUILD_TYPE=Debug ..
+# make
+# make my_coverage_target
+#
+
+include(CMakeParseArguments)
+
+option(CODE_COVERAGE_VERBOSE "Verbose information" FALSE)
+
+# Check prereqs
+find_program( GCOV_PATH gcov )
+find_program( LCOV_PATH NAMES lcov lcov.bat lcov.exe lcov.perl)
+find_program( FASTCOV_PATH NAMES fastcov fastcov.py )
+find_program( GENHTML_PATH NAMES genhtml genhtml.perl genhtml.bat )
+find_program( GCOVR_PATH gcovr PATHS ${CMAKE_SOURCE_DIR}/scripts/test)
+find_program( CPPFILT_PATH NAMES c++filt )
+
+if(NOT GCOV_PATH)
+ message(FATAL_ERROR "gcov not found! Aborting...")
+endif() # NOT GCOV_PATH
+
+get_property(LANGUAGES GLOBAL PROPERTY ENABLED_LANGUAGES)
+list(GET LANGUAGES 0 LANG)
+
+if("${CMAKE_${LANG}_COMPILER_ID}" MATCHES "(Apple)?[Cc]lang")
+ if("${CMAKE_${LANG}_COMPILER_VERSION}" VERSION_LESS 3)
+ message(FATAL_ERROR "Clang version must be 3.0.0 or greater! Aborting...")
+ endif()
+elseif(NOT CMAKE_COMPILER_IS_GNUCXX)
+ if("${CMAKE_Fortran_COMPILER_ID}" MATCHES "[Ff]lang")
+ # Do nothing; exit conditional without error if true
+ elseif("${CMAKE_Fortran_COMPILER_ID}" MATCHES "GNU")
+ # Do nothing; exit conditional without error if true
+ else()
+ message(FATAL_ERROR "Compiler is not GNU gcc! Aborting...")
+ endif()
+endif()
+
+set(COVERAGE_COMPILER_FLAGS "-g -fprofile-arcs -ftest-coverage"
+ CACHE INTERNAL "")
+if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)")
+ include(CheckCXXCompilerFlag)
+ check_cxx_compiler_flag(-fprofile-abs-path HAVE_fprofile_abs_path)
+ if(HAVE_fprofile_abs_path)
+ set(COVERAGE_COMPILER_FLAGS "${COVERAGE_COMPILER_FLAGS} -fprofile-abs-path")
+ endif()
+endif()
+
+set(CMAKE_Fortran_FLAGS_COVERAGE
+ ${COVERAGE_COMPILER_FLAGS}
+ CACHE STRING "Flags used by the Fortran compiler during coverage builds."
+ FORCE )
+set(CMAKE_CXX_FLAGS_COVERAGE
+ ${COVERAGE_COMPILER_FLAGS}
+ CACHE STRING "Flags used by the C++ compiler during coverage builds."
+ FORCE )
+set(CMAKE_C_FLAGS_COVERAGE
+ ${COVERAGE_COMPILER_FLAGS}
+ CACHE STRING "Flags used by the C compiler during coverage builds."
+ FORCE )
+set(CMAKE_EXE_LINKER_FLAGS_COVERAGE
+ ""
+ CACHE STRING "Flags used for linking binaries during coverage builds."
+ FORCE )
+set(CMAKE_SHARED_LINKER_FLAGS_COVERAGE
+ ""
+ CACHE STRING "Flags used by the shared libraries linker during coverage builds."
+ FORCE )
+mark_as_advanced(
+ CMAKE_Fortran_FLAGS_COVERAGE
+ CMAKE_CXX_FLAGS_COVERAGE
+ CMAKE_C_FLAGS_COVERAGE
+ CMAKE_EXE_LINKER_FLAGS_COVERAGE
+ CMAKE_SHARED_LINKER_FLAGS_COVERAGE )
+
+if(NOT CMAKE_BUILD_TYPE STREQUAL "Debug")
+ message(WARNING "Code coverage results with an optimised (non-Debug) build may be misleading")
+endif() # NOT CMAKE_BUILD_TYPE STREQUAL "Debug"
+
+if(CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_Fortran_COMPILER_ID STREQUAL "GNU")
+ link_libraries(gcov)
+endif()
+
+# Defines a target for running and collection code coverage information
+# Builds dependencies, runs the given executable and outputs reports.
+# NOTE! The executable should always have a ZERO as exit code otherwise
+# the coverage generation will not complete.
+#
+# setup_target_for_coverage_lcov(
+# NAME testrunner_coverage # New target name
+# EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
+# DEPENDENCIES testrunner # Dependencies to build first
+# BASE_DIRECTORY "../" # Base directory for report
+# # (defaults to PROJECT_SOURCE_DIR)
+# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
+# # to BASE_DIRECTORY, with CMake 3.4+)
+# NO_DEMANGLE # Don't demangle C++ symbols
+# # even if c++filt is found
+# )
+function(setup_target_for_coverage_lcov)
+
+ set(options NO_DEMANGLE)
+ set(oneValueArgs BASE_DIRECTORY NAME)
+ set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES LCOV_ARGS GENHTML_ARGS)
+ cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ if(NOT LCOV_PATH)
+ message(FATAL_ERROR "lcov not found! Aborting...")
+ endif() # NOT LCOV_PATH
+
+ if(NOT GENHTML_PATH)
+ message(FATAL_ERROR "genhtml not found! Aborting...")
+ endif() # NOT GENHTML_PATH
+
+ # Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
+ if(DEFINED Coverage_BASE_DIRECTORY)
+ get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
+ else()
+ set(BASEDIR ${PROJECT_SOURCE_DIR})
+ endif()
+
+ # Collect excludes (CMake 3.4+: Also compute absolute paths)
+ set(LCOV_EXCLUDES "")
+ foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_LCOV_EXCLUDES})
+ if(CMAKE_VERSION VERSION_GREATER 3.4)
+ get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
+ endif()
+ list(APPEND LCOV_EXCLUDES "${EXCLUDE}")
+ endforeach()
+ list(REMOVE_DUPLICATES LCOV_EXCLUDES)
+
+ # Conditional arguments
+ if(CPPFILT_PATH AND NOT ${Coverage_NO_DEMANGLE})
+ set(GENHTML_EXTRA_ARGS "--demangle-cpp")
+ endif()
+
+ # Setting up commands which will be run to generate coverage data.
+ # Cleanup lcov
+ set(LCOV_CLEAN_CMD
+ ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -directory .
+ -b ${BASEDIR} --zerocounters
+ )
+ # Create baseline to make sure untouched files show up in the report
+ set(LCOV_BASELINE_CMD
+ ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -c -i -d . -b
+ ${BASEDIR} -o ${Coverage_NAME}.base
+ )
+ # Run tests
+ set(LCOV_EXEC_TESTS_CMD
+ ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
+ )
+ # Capturing lcov counters and generating report
+ set(LCOV_CAPTURE_CMD
+ ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} --directory . -b
+ ${BASEDIR} --capture --output-file ${Coverage_NAME}.capture
+ )
+ # add baseline counters
+ set(LCOV_BASELINE_COUNT_CMD
+ ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} -a ${Coverage_NAME}.base
+ -a ${Coverage_NAME}.capture --output-file ${Coverage_NAME}.total
+ )
+ # filter collected data to final coverage report
+ set(LCOV_FILTER_CMD
+ ${LCOV_PATH} ${Coverage_LCOV_ARGS} --gcov-tool ${GCOV_PATH} --remove
+ ${Coverage_NAME}.total ${LCOV_EXCLUDES} --output-file ${Coverage_NAME}.info
+ )
+ # Generate HTML output
+ set(LCOV_GEN_HTML_CMD
+ ${GENHTML_PATH} ${GENHTML_EXTRA_ARGS} ${Coverage_GENHTML_ARGS} -o
+ ${Coverage_NAME} ${Coverage_NAME}.info
+ )
+
+
+ if(CODE_COVERAGE_VERBOSE)
+ message(STATUS "Executed command report")
+ message(STATUS "Command to clean up lcov: ")
+ string(REPLACE ";" " " LCOV_CLEAN_CMD_SPACED "${LCOV_CLEAN_CMD}")
+ message(STATUS "${LCOV_CLEAN_CMD_SPACED}")
+
+ message(STATUS "Command to create baseline: ")
+ string(REPLACE ";" " " LCOV_BASELINE_CMD_SPACED "${LCOV_BASELINE_CMD}")
+ message(STATUS "${LCOV_BASELINE_CMD_SPACED}")
+
+ message(STATUS "Command to run the tests: ")
+ string(REPLACE ";" " " LCOV_EXEC_TESTS_CMD_SPACED "${LCOV_EXEC_TESTS_CMD}")
+ message(STATUS "${LCOV_EXEC_TESTS_CMD_SPACED}")
+
+ message(STATUS "Command to capture counters and generate report: ")
+ string(REPLACE ";" " " LCOV_CAPTURE_CMD_SPACED "${LCOV_CAPTURE_CMD}")
+ message(STATUS "${LCOV_CAPTURE_CMD_SPACED}")
+
+ message(STATUS "Command to add baseline counters: ")
+ string(REPLACE ";" " " LCOV_BASELINE_COUNT_CMD_SPACED "${LCOV_BASELINE_COUNT_CMD}")
+ message(STATUS "${LCOV_BASELINE_COUNT_CMD_SPACED}")
+
+ message(STATUS "Command to filter collected data: ")
+ string(REPLACE ";" " " LCOV_FILTER_CMD_SPACED "${LCOV_FILTER_CMD}")
+ message(STATUS "${LCOV_FILTER_CMD_SPACED}")
+
+ message(STATUS "Command to generate lcov HTML output: ")
+ string(REPLACE ";" " " LCOV_GEN_HTML_CMD_SPACED "${LCOV_GEN_HTML_CMD}")
+ message(STATUS "${LCOV_GEN_HTML_CMD_SPACED}")
+ endif()
+
+ # Setup target
+ add_custom_target(${Coverage_NAME}
+ COMMAND ${LCOV_CLEAN_CMD}
+ COMMAND ${LCOV_BASELINE_CMD}
+ COMMAND ${LCOV_EXEC_TESTS_CMD}
+ COMMAND ${LCOV_CAPTURE_CMD}
+ COMMAND ${LCOV_BASELINE_COUNT_CMD}
+ COMMAND ${LCOV_FILTER_CMD}
+ COMMAND ${LCOV_GEN_HTML_CMD}
+
+ # Set output files as GENERATED (will be removed on 'make clean')
+ BYPRODUCTS
+ ${Coverage_NAME}.base
+ ${Coverage_NAME}.capture
+ ${Coverage_NAME}.total
+ ${Coverage_NAME}.info
+ ${Coverage_NAME}/index.html
+ WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
+ DEPENDS ${Coverage_DEPENDENCIES}
+ VERBATIM # Protect arguments to commands
+ COMMENT "Resetting code coverage counters to zero.\nProcessing code coverage counters and generating report."
+ )
+
+ # Show where to find the lcov info report
+ add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
+ COMMAND ;
+ COMMENT "Lcov code coverage info report saved in ${Coverage_NAME}.info."
+ )
+
+ # Show info where to find the report
+ add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
+ COMMAND ;
+ COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report."
+ )
+
+endfunction() # setup_target_for_coverage_lcov
+
+# Defines a target for running and collection code coverage information
+# Builds dependencies, runs the given executable and outputs reports.
+# NOTE! The executable should always have a ZERO as exit code otherwise
+# the coverage generation will not complete.
+#
+# setup_target_for_coverage_gcovr_xml(
+# NAME ctest_coverage # New target name
+# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
+# DEPENDENCIES executable_target # Dependencies to build first
+# BASE_DIRECTORY "../" # Base directory for report
+# # (defaults to PROJECT_SOURCE_DIR)
+# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
+# # to BASE_DIRECTORY, with CMake 3.4+)
+# )
+# The user can set the variable GCOVR_ADDITIONAL_ARGS to supply additional flags to the
+# GCVOR command.
+function(setup_target_for_coverage_gcovr_xml)
+
+ set(options NONE)
+ set(oneValueArgs BASE_DIRECTORY NAME)
+ set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
+ cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ if(NOT GCOVR_PATH)
+ message(FATAL_ERROR "gcovr not found! Aborting...")
+ endif() # NOT GCOVR_PATH
+
+ # Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
+ if(DEFINED Coverage_BASE_DIRECTORY)
+ get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
+ else()
+ set(BASEDIR ${PROJECT_SOURCE_DIR})
+ endif()
+
+ # Collect excludes (CMake 3.4+: Also compute absolute paths)
+ set(GCOVR_EXCLUDES "")
+ foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
+ if(CMAKE_VERSION VERSION_GREATER 3.4)
+ get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
+ endif()
+ list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
+ endforeach()
+ list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
+
+ # Combine excludes to several -e arguments
+ set(GCOVR_EXCLUDE_ARGS "")
+ foreach(EXCLUDE ${GCOVR_EXCLUDES})
+ list(APPEND GCOVR_EXCLUDE_ARGS "-e")
+ list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
+ endforeach()
+
+ # Set up commands which will be run to generate coverage data
+ # Run tests
+ set(GCOVR_XML_EXEC_TESTS_CMD
+ ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
+ )
+ # Running gcovr
+ set(GCOVR_XML_CMD
+ ${GCOVR_PATH} --xml -r ${BASEDIR} ${GCOVR_ADDITIONAL_ARGS} ${GCOVR_EXCLUDE_ARGS}
+ --object-directory=${PROJECT_BINARY_DIR} -o ${Coverage_NAME}.xml
+ )
+
+ if(CODE_COVERAGE_VERBOSE)
+ message(STATUS "Executed command report")
+
+ message(STATUS "Command to run tests: ")
+ string(REPLACE ";" " " GCOVR_XML_EXEC_TESTS_CMD_SPACED "${GCOVR_XML_EXEC_TESTS_CMD}")
+ message(STATUS "${GCOVR_XML_EXEC_TESTS_CMD_SPACED}")
+
+ message(STATUS "Command to generate gcovr XML coverage data: ")
+ string(REPLACE ";" " " GCOVR_XML_CMD_SPACED "${GCOVR_XML_CMD}")
+ message(STATUS "${GCOVR_XML_CMD_SPACED}")
+ endif()
+
+ add_custom_target(${Coverage_NAME}
+ COMMAND ${GCOVR_XML_EXEC_TESTS_CMD}
+ COMMAND ${GCOVR_XML_CMD}
+
+ BYPRODUCTS ${Coverage_NAME}.xml
+ WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
+ DEPENDS ${Coverage_DEPENDENCIES}
+ VERBATIM # Protect arguments to commands
+ COMMENT "Running gcovr to produce Cobertura code coverage report."
+ )
+
+ # Show info where to find the report
+ add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
+ COMMAND ;
+ COMMENT "Cobertura code coverage report saved in ${Coverage_NAME}.xml."
+ )
+endfunction() # setup_target_for_coverage_gcovr_xml
+
+# Defines a target for running and collection code coverage information
+# Builds dependencies, runs the given executable and outputs reports.
+# NOTE! The executable should always have a ZERO as exit code otherwise
+# the coverage generation will not complete.
+#
+# setup_target_for_coverage_gcovr_html(
+# NAME ctest_coverage # New target name
+# EXECUTABLE ctest -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
+# DEPENDENCIES executable_target # Dependencies to build first
+# BASE_DIRECTORY "../" # Base directory for report
+# # (defaults to PROJECT_SOURCE_DIR)
+# EXCLUDE "src/dir1/*" "src/dir2/*" # Patterns to exclude (can be relative
+# # to BASE_DIRECTORY, with CMake 3.4+)
+# )
+# The user can set the variable GCOVR_ADDITIONAL_ARGS to supply additional flags to the
+# GCVOR command.
+function(setup_target_for_coverage_gcovr_html)
+
+ set(options NONE)
+ set(oneValueArgs BASE_DIRECTORY NAME)
+ set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES)
+ cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ if(NOT GCOVR_PATH)
+ message(FATAL_ERROR "gcovr not found! Aborting...")
+ endif() # NOT GCOVR_PATH
+
+ # Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
+ if(DEFINED Coverage_BASE_DIRECTORY)
+ get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
+ else()
+ set(BASEDIR ${PROJECT_SOURCE_DIR})
+ endif()
+
+ # Collect excludes (CMake 3.4+: Also compute absolute paths)
+ set(GCOVR_EXCLUDES "")
+ foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_GCOVR_EXCLUDES})
+ if(CMAKE_VERSION VERSION_GREATER 3.4)
+ get_filename_component(EXCLUDE ${EXCLUDE} ABSOLUTE BASE_DIR ${BASEDIR})
+ endif()
+ list(APPEND GCOVR_EXCLUDES "${EXCLUDE}")
+ endforeach()
+ list(REMOVE_DUPLICATES GCOVR_EXCLUDES)
+
+ # Combine excludes to several -e arguments
+ set(GCOVR_EXCLUDE_ARGS "")
+ foreach(EXCLUDE ${GCOVR_EXCLUDES})
+ list(APPEND GCOVR_EXCLUDE_ARGS "-e")
+ list(APPEND GCOVR_EXCLUDE_ARGS "${EXCLUDE}")
+ endforeach()
+
+ # Set up commands which will be run to generate coverage data
+ # Run tests
+ set(GCOVR_HTML_EXEC_TESTS_CMD
+ ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS}
+ )
+ # Create folder
+ set(GCOVR_HTML_FOLDER_CMD
+ ${CMAKE_COMMAND} -E make_directory ${PROJECT_BINARY_DIR}/${Coverage_NAME}
+ )
+ # Running gcovr
+ set(GCOVR_HTML_CMD
+ ${GCOVR_PATH} --html --html-details -r ${BASEDIR} ${GCOVR_ADDITIONAL_ARGS}
+ ${GCOVR_EXCLUDE_ARGS} --object-directory=${PROJECT_BINARY_DIR}
+ -o ${Coverage_NAME}/index.html
+ )
+
+ if(CODE_COVERAGE_VERBOSE)
+ message(STATUS "Executed command report")
+
+ message(STATUS "Command to run tests: ")
+ string(REPLACE ";" " " GCOVR_HTML_EXEC_TESTS_CMD_SPACED "${GCOVR_HTML_EXEC_TESTS_CMD}")
+ message(STATUS "${GCOVR_HTML_EXEC_TESTS_CMD_SPACED}")
+
+ message(STATUS "Command to create a folder: ")
+ string(REPLACE ";" " " GCOVR_HTML_FOLDER_CMD_SPACED "${GCOVR_HTML_FOLDER_CMD}")
+ message(STATUS "${GCOVR_HTML_FOLDER_CMD_SPACED}")
+
+ message(STATUS "Command to generate gcovr HTML coverage data: ")
+ string(REPLACE ";" " " GCOVR_HTML_CMD_SPACED "${GCOVR_HTML_CMD}")
+ message(STATUS "${GCOVR_HTML_CMD_SPACED}")
+ endif()
+
+ add_custom_target(${Coverage_NAME}
+ COMMAND ${GCOVR_HTML_EXEC_TESTS_CMD}
+ COMMAND ${GCOVR_HTML_FOLDER_CMD}
+ COMMAND ${GCOVR_HTML_CMD}
+
+ BYPRODUCTS ${PROJECT_BINARY_DIR}/${Coverage_NAME}/index.html # report directory
+ WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
+ DEPENDS ${Coverage_DEPENDENCIES}
+ VERBATIM # Protect arguments to commands
+ COMMENT "Running gcovr to produce HTML code coverage report."
+ )
+
+ # Show info where to find the report
+ add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
+ COMMAND ;
+ COMMENT "Open ./${Coverage_NAME}/index.html in your browser to view the coverage report."
+ )
+
+endfunction() # setup_target_for_coverage_gcovr_html
+
+# Defines a target for running and collection code coverage information
+# Builds dependencies, runs the given executable and outputs reports.
+# NOTE! The executable should always have a ZERO as exit code otherwise
+# the coverage generation will not complete.
+#
+# setup_target_for_coverage_fastcov(
+# NAME testrunner_coverage # New target name
+# EXECUTABLE testrunner -j ${PROCESSOR_COUNT} # Executable in PROJECT_BINARY_DIR
+# DEPENDENCIES testrunner # Dependencies to build first
+# BASE_DIRECTORY "../" # Base directory for report
+# # (defaults to PROJECT_SOURCE_DIR)
+# EXCLUDE "src/dir1/" "src/dir2/" # Patterns to exclude.
+# NO_DEMANGLE # Don't demangle C++ symbols
+# # even if c++filt is found
+# SKIP_HTML # Don't create html report
+# )
+function(setup_target_for_coverage_fastcov)
+
+ set(options NO_DEMANGLE SKIP_HTML)
+ set(oneValueArgs BASE_DIRECTORY NAME)
+ set(multiValueArgs EXCLUDE EXECUTABLE EXECUTABLE_ARGS DEPENDENCIES FASTCOV_ARGS GENHTML_ARGS)
+ cmake_parse_arguments(Coverage "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN})
+
+ if(NOT FASTCOV_PATH)
+ message(FATAL_ERROR "fastcov not found! Aborting...")
+ endif()
+
+ if(NOT GENHTML_PATH)
+ message(FATAL_ERROR "genhtml not found! Aborting...")
+ endif()
+
+ # Set base directory (as absolute path), or default to PROJECT_SOURCE_DIR
+ if(Coverage_BASE_DIRECTORY)
+ get_filename_component(BASEDIR ${Coverage_BASE_DIRECTORY} ABSOLUTE)
+ else()
+ set(BASEDIR ${PROJECT_SOURCE_DIR})
+ endif()
+
+ # Collect excludes (Patterns, not paths, for fastcov)
+ set(FASTCOV_EXCLUDES "")
+ foreach(EXCLUDE ${Coverage_EXCLUDE} ${COVERAGE_EXCLUDES} ${COVERAGE_FASTCOV_EXCLUDES})
+ list(APPEND FASTCOV_EXCLUDES "${EXCLUDE}")
+ endforeach()
+ list(REMOVE_DUPLICATES FASTCOV_EXCLUDES)
+
+ # Conditional arguments
+ if(CPPFILT_PATH AND NOT ${Coverage_NO_DEMANGLE})
+ set(GENHTML_EXTRA_ARGS "--demangle-cpp")
+ endif()
+
+ # Set up commands which will be run to generate coverage data
+ set(FASTCOV_EXEC_TESTS_CMD ${Coverage_EXECUTABLE} ${Coverage_EXECUTABLE_ARGS})
+
+ set(FASTCOV_CAPTURE_CMD ${FASTCOV_PATH} ${Coverage_FASTCOV_ARGS} --gcov ${GCOV_PATH}
+ --search-directory ${BASEDIR}
+ --process-gcno
+ --lcov
+ --output ${Coverage_NAME}.info
+ --exclude ${FASTCOV_EXCLUDES}
+ --exclude ${FASTCOV_EXCLUDES}
+ )
+
+ if(Coverage_SKIP_HTML)
+ set(FASTCOV_HTML_CMD ";")
+ else()
+ set(FASTCOV_HTML_CMD ${GENHTML_PATH} ${GENHTML_EXTRA_ARGS} ${Coverage_GENHTML_ARGS}
+ -o ${Coverage_NAME} ${Coverage_NAME}.info
+ )
+ endif()
+
+ if(CODE_COVERAGE_VERBOSE)
+ message(STATUS "Code coverage commands for target ${Coverage_NAME} (fastcov):")
+
+ message(" Running tests:")
+ string(REPLACE ";" " " FASTCOV_EXEC_TESTS_CMD_SPACED "${FASTCOV_EXEC_TESTS_CMD}")
+ message(" ${FASTCOV_EXEC_TESTS_CMD_SPACED}")
+
+ message(" Capturing fastcov counters and generating report:")
+ string(REPLACE ";" " " FASTCOV_CAPTURE_CMD_SPACED "${FASTCOV_CAPTURE_CMD}")
+ message(" ${FASTCOV_CAPTURE_CMD_SPACED}")
+
+ if(NOT Coverage_SKIP_HTML)
+ message(" Generating HTML report: ")
+ string(REPLACE ";" " " FASTCOV_HTML_CMD_SPACED "${FASTCOV_HTML_CMD}")
+ message(" ${FASTCOV_HTML_CMD_SPACED}")
+ endif()
+ endif()
+
+ # Setup target
+ add_custom_target(${Coverage_NAME}
+
+ # Cleanup fastcov
+ COMMAND ${FASTCOV_PATH} ${Coverage_FASTCOV_ARGS} --gcov ${GCOV_PATH}
+ --search-directory ${BASEDIR}
+ --zerocounters
+
+ COMMAND ${FASTCOV_EXEC_TESTS_CMD}
+ COMMAND ${FASTCOV_CAPTURE_CMD}
+ COMMAND ${FASTCOV_HTML_CMD}
+
+ # Set output files as GENERATED (will be removed on 'make clean')
+ BYPRODUCTS
+ ${Coverage_NAME}.info
+ ${Coverage_NAME}/index.html # report directory
+
+ WORKING_DIRECTORY ${PROJECT_BINARY_DIR}
+ DEPENDS ${Coverage_DEPENDENCIES}
+ VERBATIM # Protect arguments to commands
+ COMMENT "Resetting code coverage counters to zero. Processing code coverage counters and generating report."
+ )
+
+ set(INFO_MSG "fastcov code coverage info report saved in ${Coverage_NAME}.info.")
+ if(NOT Coverage_SKIP_HTML)
+ string(APPEND INFO_MSG " Open ${PROJECT_BINARY_DIR}/${Coverage_NAME}/index.html in your browser to view the coverage report.")
+ endif()
+ # Show where to find the fastcov info report
+ add_custom_command(TARGET ${Coverage_NAME} POST_BUILD
+ COMMAND ${CMAKE_COMMAND} -E echo ${INFO_MSG}
+ )
+
+endfunction() # setup_target_for_coverage_fastcov
+
+function(append_coverage_compiler_flags)
+ set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
+ set(CMAKE_Fortran_FLAGS "${CMAKE_Fortran_FLAGS} ${COVERAGE_COMPILER_FLAGS}" PARENT_SCOPE)
+ message(STATUS "Appending code coverage compiler flags: ${COVERAGE_COMPILER_FLAGS}")
+endfunction() # append_coverage_compiler_flags
diff --git a/login_server/cmake/GetGitRevisionDescription.cmake b/login_server/cmake/GetGitRevisionDescription.cmake
new file mode 100644
index 000000000..1175e673a
--- /dev/null
+++ b/login_server/cmake/GetGitRevisionDescription.cmake
@@ -0,0 +1,141 @@
+# - Returns a version string from Git
+#
+# These functions force a re-configure on each git commit so that you can
+# trust the values of the variables in your build system.
+#
+# get_git_head_revision( [ ...])
+#
+# Returns the refspec and sha hash of the current head revision
+#
+# git_describe( [ ...])
+#
+# Returns the results of git describe on the source tree, and adjusting
+# the output so that it tests false if an error occurs.
+#
+# git_get_exact_tag( [ ...])
+#
+# Returns the results of git describe --exact-match on the source tree,
+# and adjusting the output so that it tests false if there was no exact
+# matching tag.
+#
+# Requires CMake 2.6 or newer (uses the 'function' command)
+#
+# Original Author:
+# 2009-2010 Ryan Pavlik
+# http://academic.cleardefinition.com
+# Iowa State University HCI Graduate Program/VRAC
+#
+# Copyright Iowa State University 2009-2010.
+# Distributed under the Boost Software License, Version 1.0.
+# (See accompanying file LICENSE_1_0.txt or copy at
+# http://www.boost.org/LICENSE_1_0.txt)
+
+if(__get_git_revision_description)
+ return()
+endif()
+set(__get_git_revision_description YES)
+
+# We must run the following at "include" time, not at function call time,
+# to find the path to this module rather than the path to a calling list file
+get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH)
+
+function(get_git_head_revision _refspecvar _hashvar)
+ set(GIT_PARENT_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
+ set(GIT_DIR "${GIT_PARENT_DIR}/.git")
+ while(NOT EXISTS "${GIT_DIR}") # .git dir not found, search parent directories
+ set(GIT_PREVIOUS_PARENT "${GIT_PARENT_DIR}")
+ get_filename_component(GIT_PARENT_DIR ${GIT_PARENT_DIR} PATH)
+ if(GIT_PARENT_DIR STREQUAL GIT_PREVIOUS_PARENT)
+ # We have reached the root directory, we are not in git
+ set(${_refspecvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
+ set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
+ return()
+ endif()
+ set(GIT_DIR "${GIT_PARENT_DIR}/.git")
+ endwhile()
+ # check if this is a submodule
+ if(NOT IS_DIRECTORY ${GIT_DIR})
+ file(READ ${GIT_DIR} submodule)
+ string(REGEX REPLACE "gitdir: (.*)\n$" "\\1" GIT_DIR_RELATIVE ${submodule})
+ get_filename_component(SUBMODULE_DIR ${GIT_DIR} PATH)
+
+ if (IS_ABSOLUTE ${GIT_DIR_RELATIVE})
+ set(GIT_DIR ${GIT_DIR_RELATIVE})
+ else()
+ get_filename_component(GIT_DIR ${SUBMODULE_DIR}/${GIT_DIR_RELATIVE} ABSOLUTE)
+ endif()
+
+ endif()
+ set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data")
+ if(NOT EXISTS "${GIT_DATA}")
+ file(MAKE_DIRECTORY "${GIT_DATA}")
+ endif()
+
+ if(NOT EXISTS "${GIT_DIR}/HEAD")
+ return()
+ endif()
+ set(HEAD_FILE "${GIT_DATA}/HEAD")
+ configure_file("${GIT_DIR}/HEAD" "${HEAD_FILE}" COPYONLY)
+
+ configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in"
+ "${GIT_DATA}/grabRef.cmake"
+ @ONLY)
+ include("${GIT_DATA}/grabRef.cmake")
+
+ set(${_refspecvar} "${HEAD_REF}" PARENT_SCOPE)
+ set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE)
+endfunction()
+
+function(git_describe _var)
+ if(NOT GIT_FOUND)
+ find_package(Git QUIET)
+ endif()
+ get_git_head_revision(refspec hash)
+ if(NOT GIT_FOUND)
+ set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
+ return()
+ endif()
+ if(NOT hash)
+ set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
+ return()
+ endif()
+
+ # TODO sanitize
+ #if((${ARGN}" MATCHES "&&") OR
+ # (ARGN MATCHES "||") OR
+ # (ARGN MATCHES "\\;"))
+ # message("Please report the following error to the project!")
+ # message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}")
+ #endif()
+
+ #message(STATUS "Arguments to execute_process: ${ARGN}")
+
+ execute_process(COMMAND
+ ${GIT_EXECUTABLE}
+ describe
+ ${hash}
+ ${ARGN}
+ WORKING_DIRECTORY
+ "${CMAKE_SOURCE_DIR}"
+ RESULT_VARIABLE
+ res
+ OUTPUT_VARIABLE
+ out
+ ERROR_QUIET
+ OUTPUT_STRIP_TRAILING_WHITESPACE)
+ if(NOT res EQUAL 0)
+ set(out "${out}-${res}-NOTFOUND")
+ endif()
+
+ set(${_var} "${out}" PARENT_SCOPE)
+endfunction()
+
+function(git_get_exact_tag _var)
+ git_describe(out --exact-match ${ARGN})
+ set(${_var} "${out}" PARENT_SCOPE)
+endfunction()
+
+function(git_get_tag _var)
+ git_describe(out --tags ${ARGN})
+ set(${_var} "${out}" PARENT_SCOPE)
+endfunction()
diff --git a/login_server/cmake/LICENSE_1_0.txt b/login_server/cmake/LICENSE_1_0.txt
new file mode 100644
index 000000000..36b7cd93c
--- /dev/null
+++ b/login_server/cmake/LICENSE_1_0.txt
@@ -0,0 +1,23 @@
+Boost Software License - Version 1.0 - August 17th, 2003
+
+Permission is hereby granted, free of charge, to any person or organization
+obtaining a copy of the software and accompanying documentation covered by
+this license (the "Software") to use, reproduce, display, distribute,
+execute, and transmit the Software, and to prepare derivative works of the
+Software, and to permit third-parties to whom the Software is furnished to
+do so, all subject to the following:
+
+The copyright notices in the Software and this entire statement, including
+the above license grant, this restriction and the following disclaimer,
+must be included in all copies of the Software, in whole or in part, and
+all derivative works of the Software, unless such copies or derivative
+works are solely in the form of machine-executable object code generated by
+a source language processor.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
+SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
+FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
+ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/login_server/cmake/README.md b/login_server/cmake/README.md
new file mode 100644
index 000000000..f61e85d03
--- /dev/null
+++ b/login_server/cmake/README.md
@@ -0,0 +1,72 @@
+Additional CMake Modules
+========================
+
+Introduction
+------------
+
+This is a collection of additional CMake modules.
+Most of them are from Ryan Pavlik ().
+
+How to Integrate
+----------------
+
+These modules are probably best placed wholesale into a "cmake" subdirectory
+of your project source.
+
+If you use Git, try installing [git-subtree][1],
+so you can easily use this repository for subtree merges, updating simply.
+
+For the initial checkout:
+
+ cd projectdir
+
+ git subtree add --squash --prefix=cmake git@github.com:bilke/cmake-modules.git master
+
+For updates:
+
+ cd projectdir
+
+ git subtree pull --squash --prefix=cmake git@github.com:bilke/cmake-modules.git master
+
+For pushing to upstream:
+
+ cd projectdir
+
+ git subtree push --prefix=cmake git@github.com:bilke/cmake-modules.git master
+
+
+How to Use
+----------
+
+At the minimum, all you have to do is add a line like this near the top
+of your root CMakeLists.txt file (but not before your project() call):
+
+ list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
+
+
+Licenses
+--------
+
+The modules that are written by Ryan Pavlik are all subject to this license:
+
+> Copyright Iowa State University 2009-2011
+>
+> Distributed under the Boost Software License, Version 1.0.
+>
+> (See accompanying file `LICENSE_1_0.txt` or copy at
+> )
+
+Modules based on those included with CMake as well as modules added by me (Lars
+Bilke) are under the OSI-approved **BSD** license, which is included in each of
+those modules. A few other modules are modified from other sources - when in
+doubt, look at the .cmake.
+
+Important License Note!
+-----------------------
+
+If you find this file inside of another project, rather at the top-level
+directory, you're in a separate project that is making use of these modules.
+That separate project can (and probably does) have its own license specifics.
+
+
+[1]: http://github.com/apenwarr/git-subtree "Git Subtree master"
diff --git a/login_server/dependencies/grpc b/login_server/dependencies/grpc
deleted file mode 160000
index 7d7e45676..000000000
--- a/login_server/dependencies/grpc
+++ /dev/null
@@ -1 +0,0 @@
-Subproject commit 7d7e4567625db7cfebf8969a225948097a3f9f89
diff --git a/login_server/dependencies/protobuf b/login_server/dependencies/protobuf
new file mode 160000
index 000000000..0b8d13a1d
--- /dev/null
+++ b/login_server/dependencies/protobuf
@@ -0,0 +1 @@
+Subproject commit 0b8d13a1d4cd9be16ed8a2230577aa9c296aa1ca
diff --git a/login_server/scripts/prepare_build.sh b/login_server/scripts/prepare_build.sh
index 8706e4139..fe9c70e46 100755
--- a/login_server/scripts/prepare_build.sh
+++ b/login_server/scripts/prepare_build.sh
@@ -11,5 +11,10 @@ cd build
cmake -DWITH_SSL=OFF ..
cd ../../
-
-
+if [! -d "./build" ] ; then
+ mkdir build
+fi
+cd build
+cmake -DCMAKE_BUILD_TYPE=Debug ..
+make -j$(nproc) protoc PageCompiler
+cmake ..
diff --git a/login_server/scripts/windows_parse_proto.sh b/login_server/scripts/windows_parse_proto.sh
index b01ae74d7..075cf6fbd 100644
--- a/login_server/scripts/windows_parse_proto.sh
+++ b/login_server/scripts/windows_parse_proto.sh
@@ -5,15 +5,9 @@ fi
if [ ! -d "../src/cpp/proto/gradido" ] ; then
mkdir ../src/cpp/proto/gradido
fi
-PROTOC_PATH=build/bin
-CPP_PLUGIN_PATH=build/bin
-$PROTOC_PATH/protoc.exe --cpp_out=../src/cpp/proto --proto_path=../src/proto ../src/proto/gradido/*.proto
+PROTOC_PATH=../build/dependencies/protobuf/cmake/bin/Debug
+
+$PROTOC_PATH/protoc.exe --cpp_out=../build/proto/gradido --proto_path=../src/proto ../src/proto/gradido/*.proto
-if [ ! -d "./src/cpp/proto/hedera" ] ; then
- mkdir ./src/cpp/proto/hedera
-fi
-
-GOOGLE_PROTOBUF_INCLUDES=../dependencies/grpc/third_party/protobuf/src
-$PROTOC_PATH/protoc.exe --plugin=protoc-gen-grpc=$CPP_PLUGIN_PATH/grpc_cpp_plugin.exe --cpp_out=../src/cpp/proto/hedera --grpc_out=../src/cpp/proto/hedera --proto_path=$GOOGLE_PROTOBUF_INCLUDES --proto_path=../src/proto/hedera/hedera-protobuf/src/main/proto ../src/proto/hedera/hedera-protobuf/src/main/proto/*.proto
diff --git a/login_server/skeema/gradido_login/crypto_keys.sql b/login_server/skeema/gradido_login/crypto_keys.sql
deleted file mode 100644
index 1e5d6bad8..000000000
--- a/login_server/skeema/gradido_login/crypto_keys.sql
+++ /dev/null
@@ -1,8 +0,0 @@
-CREATE TABLE `crypto_keys` (
- `id` int unsigned NOT NULL AUTO_INCREMENT,
- `private_key` varbinary(80) NOT NULL,
- `public_key` binary(32) NOT NULL,
- `crypto_key_type_id` int NOT NULL DEFAULT '0',
- PRIMARY KEY (`id`),
- UNIQUE(`public_key`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
diff --git a/login_server/skeema/gradido_login/hedera_accounts.sql b/login_server/skeema/gradido_login/hedera_accounts.sql
deleted file mode 100644
index 8ce24b54d..000000000
--- a/login_server/skeema/gradido_login/hedera_accounts.sql
+++ /dev/null
@@ -1,12 +0,0 @@
-CREATE TABLE `hedera_accounts` (
- `id` int unsigned NOT NULL AUTO_INCREMENT,
- `user_id` int unsigned NOT NULL,
- `account_hedera_id` int unsigned NOT NULL,
- `account_key_id` int unsigned NOT NULL,
- `balance` bigint unsigned NOT NULL DEFAULT '0',
- `network_type` int NOT NULL DEFAULT '0',
- `updated` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- PRIMARY KEY (`id`),
- UNIQUE KEY `account_hedera_id` (`account_hedera_id`),
- UNIQUE KEY `account_key_id` (`account_key_id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
diff --git a/login_server/skeema/gradido_login/hedera_ids.sql b/login_server/skeema/gradido_login/hedera_ids.sql
deleted file mode 100644
index b5fd26682..000000000
--- a/login_server/skeema/gradido_login/hedera_ids.sql
+++ /dev/null
@@ -1,7 +0,0 @@
-CREATE TABLE `hedera_ids` (
- `id` int unsigned NOT NULL AUTO_INCREMENT,
- `shardNum` bigint NOT NULL DEFAULT '0',
- `realmNum` bigint NOT NULL DEFAULT '0',
- `num` bigint NOT NULL,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
\ No newline at end of file
diff --git a/login_server/skeema/gradido_login/hedera_topics.sql b/login_server/skeema/gradido_login/hedera_topics.sql
deleted file mode 100644
index 43e2529ef..000000000
--- a/login_server/skeema/gradido_login/hedera_topics.sql
+++ /dev/null
@@ -1,16 +0,0 @@
-CREATE TABLE `hedera_topics` (
- `id` int unsigned NOT NULL AUTO_INCREMENT,
- `topic_hedera_id` int unsigned NOT NULL,
- `name` VARCHAR(255) NOT NULL DEFAULT '',
- `auto_renew_account_hedera_id` int unsigned DEFAULT NULL,
- `auto_renew_period` int unsigned NOT NULL DEFAULT '0',
- `group_id` int unsigned NOT NULL,
- `admin_key_id` int unsigned DEFAULT NULL,
- `submit_key_id` int unsigned DEFAULT NULL,
- `current_timeout` DATETIME NOT NULL DEFAULT '2000-01-01 00:00:00',
- `sequence_number` bigint unsigned DEFAULT '0',
- `running_hash` VARBINARY(64) DEFAULT NULL,
- `running_hash_version` int unsigned DEFAULT 0,
- `updated` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
- PRIMARY KEY (`id`)
-) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
diff --git a/login_server/skeema/gradido_login/node_servers.sql b/login_server/skeema/gradido_login/node_servers.sql
deleted file mode 100644
index 88e4d8ac3..000000000
--- a/login_server/skeema/gradido_login/node_servers.sql
+++ /dev/null
@@ -1,10 +0,0 @@
-CREATE TABLE `node_servers` (
- `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
- `url` VARCHAR(255) NOT NULL,
- `port` INT UNSIGNED NOT NULL,
- `group_id` INT UNSIGNED NULL DEFAULT '0',
- `server_type` INT UNSIGNED NOT NULL DEFAULT '0',
- `node_hedera_id` INT UNSIGNED NULL DEFAULT '0',
- `last_live_sign` DATETIME NOT NULL DEFAULT '2000-01-01 00:00:00',
- PRIMARY KEY (`id`)
-) ENGINE = InnoDB DEFAULT CHARSET=utf8mb4;
diff --git a/login_server/skeema/gradido_login/pending_tasks.sql b/login_server/skeema/gradido_login/pending_tasks.sql
index d6774bbe3..6b7570c0c 100644
--- a/login_server/skeema/gradido_login/pending_tasks.sql
+++ b/login_server/skeema/gradido_login/pending_tasks.sql
@@ -1,7 +1,6 @@
CREATE TABLE `pending_tasks` (
`id` int UNSIGNED NOT NULL AUTO_INCREMENT,
`user_id` int UNSIGNED DEFAULT 0,
- `hedera_id` int UNSIGNED DEFAULT 0,
`request` varbinary(2048) NOT NULL,
`created` datetime NOT NULL,
`finished` datetime DEFAULT '2000-01-01 000000',
diff --git a/login_server/skeema/gradido_login/users.sql b/login_server/skeema/gradido_login/users.sql
index 9de1bad49..bedb5c2d4 100644
--- a/login_server/skeema/gradido_login/users.sql
+++ b/login_server/skeema/gradido_login/users.sql
@@ -4,6 +4,7 @@ CREATE TABLE `users` (
`first_name` varchar(150) NOT NULL,
`last_name` varchar(255) DEFAULT '',
`username` varchar(255) DEFAULT '',
+ `description` text DEFAULT '',
`password` bigint unsigned DEFAULT '0',
`pubkey` binary(32) DEFAULT NULL,
`privkey` binary(80) DEFAULT NULL,
diff --git a/login_server/src/cpp/Crypto/Passphrase.cpp b/login_server/src/cpp/Crypto/Passphrase.cpp
index cad034673..6b3df0c5d 100644
--- a/login_server/src/cpp/Crypto/Passphrase.cpp
+++ b/login_server/src/cpp/Crypto/Passphrase.cpp
@@ -179,8 +179,8 @@ Poco::AutoPtr Passphrase::create(const Poco::UInt16 wordIndices[PHRA
return new Passphrase(clearPassphrase, wordSource);
}
-Poco::AutoPtr Passphrase::generate(const Mnemonic* wordSource)
-{
+Poco::AutoPtr Passphrase::generate(const Mnemonic* wordSource)
+{
auto em = ErrorManager::getInstance();
auto mm = MemoryManager::getInstance();
auto word_indices = mm->getFreeMemory(PHRASE_WORD_COUNT * sizeof(Poco::UInt16));
@@ -266,7 +266,7 @@ bool Passphrase::createWordIndices()
return false;
}
-
+
//DHASH key = DRMakeStringHash(passphrase);
size_t pass_phrase_size = mPassphraseString.size();
@@ -352,9 +352,9 @@ const Mnemonic* Passphrase::detectMnemonic(const std::string& passphrase, const
if (keyPair) {
user_public_key_hex = DataTypeConverter::pubkeyToHex(keyPair->getPublicKey());
- printf("user public key hex: %s\n", user_public_key_hex.data());
+ //printf("user public key hex: %s\n", user_public_key_hex.data());
}
-
+ std::string last_words_not_found[ServerConfig::Mnemonic_Types::MNEMONIC_MAX];
for (int i = 0; i < ServerConfig::Mnemonic_Types::MNEMONIC_MAX; i++) {
Mnemonic& m = ServerConfig::g_Mnemonic_WordLists[i];
bool existAll = true;
@@ -362,6 +362,8 @@ const Mnemonic* Passphrase::detectMnemonic(const std::string& passphrase, const
if (*it == "\0" || *it == "" || it->size() < 3) continue;
if (!m.isWordExist(*it)) {
existAll = false;
+ //printf("couldn't find word: %s\n", (*it).data());
+ last_words_not_found[i] = (*it);
// leave inner for-loop
break;
}
@@ -372,10 +374,14 @@ const Mnemonic* Passphrase::detectMnemonic(const std::string& passphrase, const
test_passphrase->createWordIndices();
auto key_pair = KeyPairEd25519::create(test_passphrase);
if (key_pair) {
- std::string current_key_pair = DataTypeConverter::pubkeyToHex(key_pair->getPublicKey());
- printf("public key hex to compare: %s\n", current_key_pair.data());
if (*key_pair != *keyPair) {
+#ifdef _TEST_BUILD // additional infos for debugging if error occure in test
+ printf("public key mismatch\n");
+ std::string generated_key_pair_hex = DataTypeConverter::pubkeyToHex(key_pair->getPublicKey());
+ std::string parameter_key_pair_hex = DataTypeConverter::pubkeyToHex(keyPair->getPublicKey());
+ printf("parameter: %s, generated: %s\n", parameter_key_pair_hex.data(), generated_key_pair_hex.data());
+#endif
delete key_pair;
continue;
}
@@ -386,6 +392,8 @@ const Mnemonic* Passphrase::detectMnemonic(const std::string& passphrase, const
}
return &ServerConfig::g_Mnemonic_WordLists[i];
}
+ //printf("last word not found: %s in %s\n", last_words_not_found[i].data(), ServerConfig::mnemonicTypeToString((ServerConfig::Mnemonic_Types)i));
}
+
return nullptr;
-}
\ No newline at end of file
+}
diff --git a/login_server/src/cpp/Crypto/SecretKeyCryptography.cpp b/login_server/src/cpp/Crypto/SecretKeyCryptography.cpp
index 8710a5b8c..5b30f74ad 100644
--- a/login_server/src/cpp/Crypto/SecretKeyCryptography.cpp
+++ b/login_server/src/cpp/Crypto/SecretKeyCryptography.cpp
@@ -34,10 +34,12 @@ SecretKeyCryptography::ResultType SecretKeyCryptography::createKey(const std::st
assert(app_secret);
Profiler timeUsed;
std::unique_lock _lock(mWorkingMutex);
+#ifndef _TEST_BUILD
if (timeUsed.millis() > 10) {
- printf("[AuthenticatedEncryption::createKey] wait %s on getting lock\n", timeUsed.string().data());
+ printf("[SecretKeyCryptography::createKey] wait %s on getting lock\n", timeUsed.string().data());
timeUsed.reset();
}
+#endif
// use hash512 because existing data where calculated with that, but could be also changed to hash256
auto hash512_salt = mm->getFreeMemory(crypto_hash_sha512_BYTES); // need at least crypto_pwhash_SALTBYTES 16U
@@ -49,10 +51,12 @@ SecretKeyCryptography::ResultType SecretKeyCryptography::createKey(const std::st
crypto_hash_sha512_update(&state, *app_secret, app_secret->size());
crypto_hash_sha512_final(&state, *hash512_salt);
+#ifndef _TEST_BUILD
if (timeUsed.millis() > 200) {
- printf("[AuthenticatedEncryption::createKey] %s calculating sha512\n", timeUsed.string().data());
+ printf("[SecretKeyCryptography::createKey] %s calculating sha512\n", timeUsed.string().data());
timeUsed.reset();
}
+#endif
//unsigned char* key = (unsigned char *)malloc(crypto_box_SEEDBYTES); // 32U
//ObfusArray* key = new ObfusArray(crypto_box_SEEDBYTES);
@@ -68,9 +72,11 @@ SecretKeyCryptography::ResultType SecretKeyCryptography::createKey(const std::st
return AUTH_CREATE_ENCRYPTION_KEY_FAILED;
}
+#ifndef _TEST_BUILD
if (timeUsed.millis() > 400) {
- printf("[AuthenticatedEncryption::createKey] %s calculating pwd hash\n", timeUsed.string().data());
+ printf("[SecretKeyCryptography::createKey] %s calculating pwd hash\n", timeUsed.string().data());
}
+#endif
// generate hash from key for compare
assert(sizeof(KeyHashed) >= crypto_shorthash_BYTES);
assert(ServerConfig::g_ServerCryptoKey);
diff --git a/login_server/src/cpp/Gradido_LoginServer.cpp b/login_server/src/cpp/Gradido_LoginServer.cpp
index c3819f951..c3199bc0a 100644
--- a/login_server/src/cpp/Gradido_LoginServer.cpp
+++ b/login_server/src/cpp/Gradido_LoginServer.cpp
@@ -9,7 +9,6 @@
#include "SingletonManager/SessionManager.h"
#include "SingletonManager/EmailManager.h"
#include "SingletonManager/PendingTasksManager.h"
-#include "SingletonManager/CronManager.h"
#include "controller/User.h"
@@ -168,7 +167,7 @@ int Gradido_LoginServer::main(const std::vector& args)
createConsoleFileAsyncLogger("emailLog", log_Path + "emailLog.txt");
// *************** load from config ********************************************
-
+
std::string cfg_Path = Poco::Path::config() + "grd_login/";
try {
if(mConfigPath != "") {
@@ -224,7 +223,7 @@ int Gradido_LoginServer::main(const std::vector& args)
errorLog.error("[Gradido_LoginServer::main] Poco Exception by register MySQL Connector: %s", ex.displayText());
return Application::EXIT_CONFIG;
}
-
+
auto conn = ConnectionManager::getInstance();
//conn->setConnection()
//printf("try connect login server mysql db\n");
@@ -255,7 +254,7 @@ int Gradido_LoginServer::main(const std::vector& args)
errorLog.error("[Gradido_LoginServer::main] error init server SSL Client");
return Application::EXIT_CONFIG;
}
-
+
// schedule email verification resend
controller::User::checkIfVerificationEmailsShouldBeResend(ServerConfig::g_CronJobsTimer);
controller::User::addMissingEmailHashes();
@@ -281,14 +280,12 @@ int Gradido_LoginServer::main(const std::vector& args)
// load pending tasks not finished in last session
PendingTasksManager::getInstance()->load();
int php_server_ping = config().getInt("phpServer.ping", 600000);
- CronManager::getInstance()->init(php_server_ping);
printf("[Gradido_LoginServer::main] started in %s\n", usedTime.string().data());
std::clog << "[Gradido_LoginServer::main] started in " << usedTime.string().data() << std::endl;
// wait for CTRL-C or kill
waitForTerminationRequest();
- CronManager::getInstance()->stop();
// Stop the HTTPServer
srv.stop();
diff --git a/login_server/src/cpp/HTTPInterface/PageRequestHandlerFactory.cpp b/login_server/src/cpp/HTTPInterface/PageRequestHandlerFactory.cpp
index 8edbd6e9d..47d7b8c9a 100644
--- a/login_server/src/cpp/HTTPInterface/PageRequestHandlerFactory.cpp
+++ b/login_server/src/cpp/HTTPInterface/PageRequestHandlerFactory.cpp
@@ -24,17 +24,11 @@
#include "DebugMnemonicPage.h"
#include "AdminCheckUserBackupPage.h"
#include "TranslatePassphrasePage.h"
-#include "PassphrasedTransactionPage.h"
#include "AdminUserPasswordResetPage.h"
#include "RegisterDirectPage.h"
#include "AdminGroupsPage.h"
-#include "AdminTopicPage.h"
-#include "AdminHederaAccountPage.h"
-#include "AdminNodeServerPage.h"
-#include "AdminNodeServerTestPage.h"
#include "DecodeTransactionPage.h"
-#include "RepairDefectPassphrasePage.h"
#include "../SingletonManager/SessionManager.h"
@@ -121,7 +115,7 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::createRequestHandler(c
// TODO: count invalid session requests from IP and block IP for some time to prevent brute force session hijacking
// or use log file and configure fail2ban for this to do
-
+
if (url_first_part == "/checkEmail") {
//return new CheckEmailPage(s);
//printf("url checkEmail\n");
@@ -147,12 +141,8 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::createRequestHandler(c
mLogging.information(dateTimeString + " decode");
return basicSetup(new DecodeTransactionPage(s), request, timeUsed);
}
- if (url_first_part == "/passphrased_transaction") {
- return basicSetup(new PassphrasedTransactionPage, request, timeUsed);
- }
- if (url_first_part == "/adminNodeServerTest") {
- return basicSetup(new AdminNodeServerTestPage, request, timeUsed);
- }
+
+
if (s) {
if (externReferer != "") {
@@ -178,9 +168,6 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::createRequestHandler(c
if (url_first_part == "/transform_passphrase") {
return basicSetup(new TranslatePassphrasePage(s), request, timeUsed);
}
- if (url_first_part == "/repairPassphrase") {
- return basicSetup(new RepairDefectPassphrasePage(s), request, timeUsed);
- }
if (userModel && userModel->getRole() == model::table::ROLE_ADMIN) {
if (url_first_part == "/adminRegister") {
return basicSetup(new RegisterAdminPage(s), request, timeUsed);
@@ -200,21 +187,12 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::createRequestHandler(c
if (url_first_part == "/groups") {
return basicSetup(new AdminGroupsPage(s), request, timeUsed);
}
- if (url_first_part == "/topic") {
- return basicSetup(new AdminTopicPage(s), request, timeUsed);
- }
- if (url_first_part == "/hedera_account") {
- return basicSetup(new AdminHederaAccountPage(s), request, timeUsed);
- }
- if (url_first_part == "/nodes") {
- return basicSetup(new AdminNodeServerPage(s), request, timeUsed);
- }
}
if(url_first_part == "/logout") {
sm->releaseSession(s);
// remove cookie(s)
-
+
//printf("session released\n");
return basicSetup(new LoginPage(nullptr), request, timeUsed);
}
@@ -223,7 +201,7 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::createRequestHandler(c
sm->releaseSession(s);
return basicSetup(new LoginPage(nullptr), request, timeUsed);
- }
+ }
}
auto sessionState = s->getSessionState();
//printf("session state: %s\n", s->getSessionStateString());
@@ -241,7 +219,7 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::createRequestHandler(c
if (url_first_part == "/login" || url_first_part == "/") {
return basicSetup(new LoginPage(s), request, timeUsed);
}
-
+
} else {
if (url_first_part == "/config") {
@@ -305,7 +283,7 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::handleCheckEmail(Sessi
response.addCookie(Poco::Net::HTTPCookie("user", std::to_string(cookie_id)));
*/
}
- else {
+ else {
//sm->releaseSession(session);
return basicSetup(new CheckEmailPage(session), request, timeUsed);
}
@@ -325,7 +303,7 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::handleCheckEmail(Sessi
//! -2 = critical error
//! 0 = ok
*/
- // update session, mark as verified
+ // update session, mark as verified
int retUpdateEmailVerification = session->updateEmailVerification(verificationCode);
printf("[%s] return from update email verification: %d\n", __FUNCTION__, retUpdateEmailVerification);
if (0 == retUpdateEmailVerification) {
@@ -340,7 +318,7 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::handleCheckEmail(Sessi
pageRequestHandler = new PassphrasePage(session);
}
return basicSetup(pageRequestHandler, request, timeUsed);
-
+
}
else if (1 == retUpdateEmailVerification) {
//auto user = session->getUser();
@@ -358,7 +336,7 @@ Poco::Net::HTTPRequestHandler* PageRequestHandlerFactory::handleCheckEmail(Sessi
else if (-2 == retUpdateEmailVerification) {
return basicSetup(new Error500Page(session), request, timeUsed);
}
-
+
}
if (session) {
sm->releaseSession(session);
diff --git a/login_server/src/cpp/JSONInterface/JsonCreateUser.cpp b/login_server/src/cpp/JSONInterface/JsonCreateUser.cpp
index 13ca5122f..64e112c27 100644
--- a/login_server/src/cpp/JSONInterface/JsonCreateUser.cpp
+++ b/login_server/src/cpp/JSONInterface/JsonCreateUser.cpp
@@ -15,6 +15,8 @@ Poco::JSON::Object* JsonCreateUser::handle(Poco::Dynamic::Var params)
std::string first_name;
std::string last_name;
std::string password;
+ std::string username;
+ std::string description;
bool login_after_register = false;
int emailType;
int group_id = 1;
@@ -36,18 +38,27 @@ Poco::JSON::Object* JsonCreateUser::handle(Poco::Dynamic::Var params)
paramJsonObject->get("first_name").convert(first_name);
paramJsonObject->get("last_name").convert(last_name);
paramJsonObject->get("emailType").convert(emailType);
+
auto group_id_obj = paramJsonObject->get("group_id");
+ auto username_obj = paramJsonObject->get("username");
+ auto description_obj = paramJsonObject->get("description");
if(!group_id_obj.isEmpty()) {
group_id_obj.convert(group_id);
}
-
+ if (!username_obj.isEmpty()) {
+ username_obj.convert(username);
+ }
+ if (!description_obj.isEmpty()) {
+ description_obj.convert(description);
+ }
if ((ServerConfig::g_AllowUnsecureFlags & ServerConfig::UNSECURE_PASSWORD_REQUESTS)) {
paramJsonObject->get("password").convert(password);
}
if (!paramJsonObject->isNull("login_after_register")) {
paramJsonObject->get("login_after_register").convert(login_after_register);
}
+
}
catch (Poco::Exception& ex) {
return stateError("json exception", ex.displayText());
@@ -85,6 +96,15 @@ Poco::JSON::Object* JsonCreateUser::handle(Poco::Dynamic::Var params)
group_was_not_set = true;
}
user = controller::User::create(email, first_name, last_name, group_id);
+ if (username.size() > 3) {
+ if (user->isUsernameAlreadyUsed(username)) {
+ return stateError("username already in use");
+ }
+ user->getModel()->setUsername(username);
+ }
+ if (description.size() > 3) {
+ user->getModel()->setDescription(description);
+ }
auto userModel = user->getModel();
Session* session = nullptr;
diff --git a/login_server/src/cpp/JSONInterface/JsonGetUserInfos.cpp b/login_server/src/cpp/JSONInterface/JsonGetUserInfos.cpp
index 2b1f229de..3bdafd283 100644
--- a/login_server/src/cpp/JSONInterface/JsonGetUserInfos.cpp
+++ b/login_server/src/cpp/JSONInterface/JsonGetUserInfos.cpp
@@ -121,6 +121,12 @@ Poco::JSON::Object* JsonGetUserInfos::handle(Poco::Dynamic::Var params)
else if (parameterString == "user.last_name") {
jsonUser.set("last_name", user_model->getLastName());
}
+ else if (parameterString == "user.username") {
+ jsonUser.set("username", user_model->getUsername());
+ }
+ else if (parameterString == "user.description") {
+ jsonUser.set("description", user_model->getDescription());
+ }
else if (parameterString == "user.disabled") {
jsonUser.set("disabled", user_model->isDisabled());
}
diff --git a/login_server/src/cpp/JSONInterface/JsonRequestHandlerFactory.cpp b/login_server/src/cpp/JSONInterface/JsonRequestHandlerFactory.cpp
index de6c57ed1..4f0e10d6f 100644
--- a/login_server/src/cpp/JSONInterface/JsonRequestHandlerFactory.cpp
+++ b/login_server/src/cpp/JSONInterface/JsonRequestHandlerFactory.cpp
@@ -13,7 +13,6 @@
#include "JsonCreateUser.h"
#include "JsonGetLogin.h"
#include "JsonUnknown.h"
-#include "JsonTransaction.h"
#include "JsonGetRunningUserTasks.h"
#include "JsonGetUsers.h"
#include "JsonLoginViaEmailVerificationCode.h"
@@ -28,7 +27,7 @@
#include "JsonSearch.h"
-JsonRequestHandlerFactory::JsonRequestHandlerFactory()
+JsonRequestHandlerFactory::JsonRequestHandlerFactory()
: mRemoveGETParameters("^/([a-zA-Z0-9_-]*)"), mLogging(Poco::Logger::get("requestLog"))
{
}
@@ -75,9 +74,6 @@ Poco::Net::HTTPRequestHandler* JsonRequestHandlerFactory::createRequestHandler(c
else if (url_first_part == "/checkSessionState") {
return new JsonCheckSessionState;
}
- else if (url_first_part == "/checkTransaction") {
- return new JsonTransaction;
- }
else if (url_first_part == "/createTransaction") {
return new JsonCreateTransaction;
}
@@ -86,7 +82,7 @@ Poco::Net::HTTPRequestHandler* JsonRequestHandlerFactory::createRequestHandler(c
}
else if (url_first_part == "/getUsers") {
return new JsonGetUsers;
- }
+ }
else if (url_first_part == "/networkInfos") {
return new JsonNetworkInfos;
}
@@ -136,7 +132,7 @@ Poco::Net::HTTPRequestHandler* JsonRequestHandlerFactory::createRequestHandler(c
else if (url_first_part == "/logout") {
return new JsonLogout(client_host);
}
-
+
return new JsonUnknown;
}
diff --git a/login_server/src/cpp/JSONInterface/JsonTransaction.cpp b/login_server/src/cpp/JSONInterface/JsonTransaction.cpp
deleted file mode 100644
index 1e7f7844e..000000000
--- a/login_server/src/cpp/JSONInterface/JsonTransaction.cpp
+++ /dev/null
@@ -1,171 +0,0 @@
-#include "JsonTransaction.h"
-#include "Poco/URI.h"
-#include "Poco/Dynamic/Struct.h"
-
-#include "../SingletonManager/SessionManager.h"
-#include "../ServerConfig.h"
-
-Poco::JSON::Object* JsonTransaction::handle(Poco::Dynamic::Var params)
-{
- Poco::JSON::Object* result = new Poco::JSON::Object;
- int session_id = 0;
-
- // if is json object
- if (params.type() == typeid(Poco::JSON::Object::Ptr)) {
- Poco::JSON::Object::Ptr paramJsonObject = params.extract();
-
- try {
- /// Throws a RangeException if the value does not fit
- /// into the result variable.
- /// Throws a NotImplementedException if conversion is
- /// not available for the given type.
- /// Throws InvalidAccessException if Var is empty.
- paramJsonObject->get("session_id").convert(session_id);
- auto sm = SessionManager::getInstance();
- if (session_id != 0) {
- auto session = sm->getSession(session_id);
- if (!session) {
- result->set("state", "error");
- result->set("msg", "session not found");
- return result;
- }
-
- int balance = 0;
-
- if (!paramJsonObject->isNull("balance")) {
- paramJsonObject->get("balance").convert(balance);
- if (balance) {
- auto nu = session->getNewUser();
- if (!nu.isNull()) {
- nu->setBalance(balance);
- }
- }
- }
-
- std::string transactionBase64String;
- Poco::Dynamic::Var transaction_base64 = paramJsonObject->get("transaction_base64");
- int alreadyEnlisted = 0;
- bool auto_sign = false;
- auto auto_sign_json = paramJsonObject->get("auto_sign");
- if (!auto_sign_json.isEmpty()) {
- auto_sign_json.convert(auto_sign);
- }
-
- if (transaction_base64.isString()) {
- paramJsonObject->get("transaction_base64").convert(transactionBase64String);
-
- if (!session->startProcessingTransaction(transactionBase64String, auto_sign)) {
- if (auto_sign) {
- auto errorJson = session->getErrorsArray();
- result->set("state", "error");
- result->set("msg", "error processing transaction");
- result->set("details", errorJson);
- return result;
- }
- auto lastError = session->getLastError();
- if (lastError) delete lastError;
- result->set("state", "error");
- result->set("msg", "already enlisted");
- return result;
- }
-
- } else {
- Poco::DynamicStruct ds = *paramJsonObject;
- int alreadyEnlisted = 0;
-
- for (int i = 0; i < ds["transaction_base64"].size(); i++) {
- ds["transaction_base64"][i].convert(transactionBase64String);
- if (!session->startProcessingTransaction(transactionBase64String, auto_sign)) {
- auto lastError = session->getLastError();
- if (lastError) delete lastError;
- alreadyEnlisted++;
- }
- }
-
- if (alreadyEnlisted > 0) {
- result->set("state", "warning");
- result->set("msg", std::to_string(alreadyEnlisted) + " already enlisted");
- return result;
- }
- }
-
-
-
- result->set("state", "success");
- return result;
- }
-
- }
- catch (Poco::Exception& ex) {
- printf("[JsonTransaction::handle] try to use params as jsonObject: %s\n", ex.displayText().data());
- result->set("state", "error");
- result->set("msg", "json exception");
- result->set("details", ex.displayText());
- return result;
- }
- }
- else if (params.isVector()) {
- const Poco::URI::QueryParameters queryParams = params.extract();
- auto transactionIT = queryParams.begin();
- for (auto it = queryParams.begin(); it != queryParams.end(); it++) {
- if (it->first == "session_id") {
- session_id = stoi(it->second);
- //break;
- }
- else if (it->first == "transaction_base64") {
- transactionIT = it;
- }
- }
- if (session_id) {
- auto sm = SessionManager::getInstance();
- auto session = sm->getSession(session_id);
- if (!session) {
- result->set("state", "error");
- result->set("msg", "session not found");
- return result;
- }
- if (!session->startProcessingTransaction(transactionIT->second)) {
- auto lastError = session->getLastError();
- if (lastError) delete lastError;
- result->set("state", "error");
- result->set("msg", "already enlisted");
- return result;
- }
- result->set("state", "success");
- return result;
- }
- else {
- result->set("state", "error");
- result->set("msg", "session id not set");
- return result;
- }
- }
- else if (params.isStruct()) {
- result->set("state", "error");
- result->set("msg", "struct not implemented yet");
- }
- else if (params.isArray()) {
- result->set("state", "error");
- result->set("msg", "array not implemented yet");
- }
- else if (params.isList()) {
- result->set("state", "error");
- result->set("msg", "list not implemented yet");
- }
- else if (params.isString()) {
- result->set("state", "error");
- result->set("msg", "string not implemented yet");
- }
- else if (params.isDeque()) {
- result->set("state", "error");
- result->set("meg", "deque not implemented yet");
- }
- else {
-
- result->set("state", "error");
- result->set("msg", "format not implemented");
- result->set("details", std::string(params.type().name()));
- }
-
- return result;
-}
diff --git a/login_server/src/cpp/JSONInterface/JsonTransaction.h b/login_server/src/cpp/JSONInterface/JsonTransaction.h
deleted file mode 100644
index 95e9885be..000000000
--- a/login_server/src/cpp/JSONInterface/JsonTransaction.h
+++ /dev/null
@@ -1,19 +0,0 @@
-#ifndef __JSON_INTERFACE_JSON_TRANSACTION_
-#define __JSON_INTERFACE_JSON_TRANSACTION_
-
-#include "JsonRequestHandler.h"
-
-class Session;
-
-class JsonTransaction : public JsonRequestHandler
-{
-public:
- Poco::JSON::Object* handle(Poco::Dynamic::Var params);
-
-protected:
- bool startProcessingTransaction(Session* session, const std::string& transactionBase64);
-
-
-};
-
-#endif // __JSON_INTERFACE_JSON_TRANSACTION_
\ No newline at end of file
diff --git a/login_server/src/cpp/JSONInterface/JsonUnsecureLogin.cpp b/login_server/src/cpp/JSONInterface/JsonUnsecureLogin.cpp
index 0d151b1c3..59e33e5d0 100644
--- a/login_server/src/cpp/JSONInterface/JsonUnsecureLogin.cpp
+++ b/login_server/src/cpp/JSONInterface/JsonUnsecureLogin.cpp
@@ -21,6 +21,7 @@ Poco::JSON::Object* JsonUnsecureLogin::handle(Poco::Dynamic::Var params)
// incoming
std::string email;
+ std::string username;
std::string password;
// if is json object
@@ -32,8 +33,17 @@ Poco::JSON::Object* JsonUnsecureLogin::handle(Poco::Dynamic::Var params)
/// not available for the given type.
/// Throws InvalidAccessException if Var is empty.
try {
- paramJsonObject->get("email").convert(email);
+ //paramJsonObject->get("email").convert(email);
paramJsonObject->get("password").convert(password);
+ auto email_obj = paramJsonObject->get("email");
+ auto username_obj = paramJsonObject->get("username");
+
+ if (!email_obj.isEmpty()) {
+ email_obj.convert(email);
+ }
+ if (!username_obj.isEmpty()) {
+ username_obj.convert(username);
+ }
}
catch (Poco::Exception& ex) {
return stateError("json exception", ex.displayText());
@@ -43,13 +53,24 @@ Poco::JSON::Object* JsonUnsecureLogin::handle(Poco::Dynamic::Var params)
return stateError("parameter format unknown");
}
-
- if (!email.size() || !sm->isValid(email, VALIDATE_EMAIL)) {
- return stateError("invalid or empty email");
+ if (!email.size() && !username.size()) {
+ return stateError("no email or username given");
}
+
auto user = controller::User::create();
- if (1 != user->load(email)) {
- return stateError("user with email not found", email);
+ if (email.size()) {
+ if (!sm->isValid(email, VALIDATE_EMAIL)) {
+ return stateError("invalid email");
+ }
+ if (1 != user->load(email)) {
+ return stateError("user with email not found", email);
+ }
+ }
+ else if (username.size() > 0) {
+ if (1 != user->load(username)) {
+ return stateError("user with username not found", username);
+ }
+ email = user->getModel()->getEmail();
}
NotificationList pwd_errors;
diff --git a/login_server/src/cpp/JSONInterface/JsonUpdateUserInfos.cpp b/login_server/src/cpp/JSONInterface/JsonUpdateUserInfos.cpp
index 40ec44b16..7db31df33 100644
--- a/login_server/src/cpp/JSONInterface/JsonUpdateUserInfos.cpp
+++ b/login_server/src/cpp/JSONInterface/JsonUpdateUserInfos.cpp
@@ -86,6 +86,32 @@ Poco::JSON::Object* JsonUpdateUserInfos::handle(Poco::Dynamic::Var params)
extractet_values++;
}
}
+ else if ("User.username" == name && value.size() > 3) {
+ if (!value.isString()) {
+ jsonErrorsArray.add("User.username isn't a string");
+ }
+ else {
+ auto new_username = value.toString();
+ if (user_model->getUsername() != new_username) {
+ if (user->isUsernameAlreadyUsed(new_username)) {
+ jsonErrorsArray.add("username already used");
+ }
+ else {
+ user_model->setUsername(new_username);
+ extractet_values++;
+ }
+ }
+ }
+ }
+ else if ("User.description" == name && value.size() > 3) {
+ if (!value.isString()) {
+ jsonErrorsArray.add("description isn't a string");
+ }
+ else {
+ user_model->setDescription(value.toString());
+ extractet_values++;
+ }
+ }
else if ("User.disabled" == name) {
if (value.isBoolean()) {
bool disabled;
diff --git a/login_server/src/cpp/ServerConfig.cpp b/login_server/src/cpp/ServerConfig.cpp
index dc5dbcecf..a453cc956 100644
--- a/login_server/src/cpp/ServerConfig.cpp
+++ b/login_server/src/cpp/ServerConfig.cpp
@@ -21,7 +21,6 @@
#include "Poco/DateTimeFormatter.h"
#include "Poco/Environment.h"
-#include "model/table/HederaAccount.h"
using Poco::Net::SSLManager;
@@ -62,22 +61,19 @@ namespace ServerConfig {
std::string g_gRPCRelayServerFullURL;
MemoryBin* g_CryptoAppSecret = nullptr;
AllowUnsecure g_AllowUnsecureFlags = NOT_UNSECURE;
- HederaConsensusMessageFormat g_ConsensusMessageFormat = HEDERA_CONSENSUS_FORMAT_BINARY;
- HederaNetworkType g_HederaNetworkType = HEDERA_TESTNET;
- Poco::Timespan g_HederaDefaultTimeout;
-#ifdef __linux__
-#include
+#ifdef __linux__
+#include
#include
#include
-#include
-#include
+#include
+#include
#include
-#endif //#ifdef __linux__
+#endif //#ifdef __linux__
std::string getHostIpString()
{
-#ifdef __linux__
+#ifdef __linux__
struct ifaddrs * ifAddrStruct = NULL;
struct ifaddrs * ifa = NULL;
void * tmpAddrPtr = NULL;
@@ -107,7 +103,7 @@ namespace ServerConfig {
}
if (ifAddrStruct != NULL) freeifaddrs(ifAddrStruct);
return ipAddressString;
-#else //__linux__
+#else //__linux__
std::string ipAddressString = "";
auto host = Poco::Net::DNS::thisHost();
for (auto it = host.addresses().begin(); it != host.addresses().end(); it++) {
@@ -126,10 +122,10 @@ namespace ServerConfig {
//break;
}
return ipAddressString;
-#endif // __linux__
+#endif // __linux__
}
- bool replaceZeroIPWithLocalhostIP(std::string& url)
+ bool replaceZeroIPWithLocalhostIP(std::string& url)
{
auto pos = url.find("0.0.0.0", 0);
if (pos != std::string::npos) {
@@ -138,7 +134,7 @@ namespace ServerConfig {
url.replace(pos, 7, ipAddressString);
}
}
-
+
//printf("ipaddress: %s\n", ipAddress.data());
return true;
@@ -157,22 +153,6 @@ namespace ServerConfig {
return SERVER_TYPE_PRODUCTION;
}
- HederaConsensusMessageFormat getHederaConsensusMessageFormatFromString(const std::string& hederaConsensusMessageFormatString)
- {
- if ("json" == hederaConsensusMessageFormatString) {
- return HEDERA_CONSENSUS_FORMAT_JSON;
- }
- if ("binary" == hederaConsensusMessageFormatString || "bin" == hederaConsensusMessageFormatString) {
- return HEDERA_CONSENSUS_FORMAT_BINARY;
- }
- if ("base64" == hederaConsensusMessageFormatString) {
- return HEDERA_CONSENSUS_FORMAT_BASE64_URLSAVE_NO_PADDING;
- }
- return HEDERA_CONSENSUS_FORMAT_BINARY;
- }
-
-
-
bool loadMnemonicWordLists()
{
@@ -227,7 +207,7 @@ namespace ServerConfig {
g_ServerCryptoKey = new ObfusArray(realBinSize, key);
g_ServerKeySeed = new ObfusArray(9*8);
Poco::Int64 i1 = randombytes_random();
- Poco::Int64 i2 = randombytes_random();
+ Poco::Int64 i2 = randombytes_random();
g_ServerKeySeed->put(0, i1 | (i2 << 8));
//g_ServerAdminPublic = cfg.getString("crypto.server_admin_public");
@@ -245,20 +225,12 @@ namespace ServerConfig {
replaceZeroIPWithLocalhostIP(g_php_serverPath);
g_php_serverHost = cfg.getString("phpServer.host", "");
replaceZeroIPWithLocalhostIP(g_php_serverHost);
- //g_ServerSetupType
+ //g_ServerSetupType
auto serverSetupTypeString = cfg.getString("ServerSetupType", "");
g_ServerSetupType = getServerSetupTypeFromString(serverSetupTypeString);
g_devDefaultGroup = cfg.getString("dev.default_group", "");
- auto hedera_consensus_message_format_string = cfg.getString("hedera.consensus.message_format", "bin");
- g_ConsensusMessageFormat = getHederaConsensusMessageFormatFromString(hedera_consensus_message_format_string);
-
- auto hedera_network_type_string = cfg.getString("hedera.nettype", "Testnet");
- g_HederaNetworkType = model::table::HederaAccount::hederaNetworkTypeFromString(hedera_network_type_string);
- if (HEDERA_UNKNOWN == g_HederaNetworkType) {
- g_HederaNetworkType = HEDERA_TESTNET;
- }
// app secret for encrypt user private keys
// TODO: encrypt with server admin key
@@ -284,8 +256,7 @@ namespace ServerConfig {
if (cfg.getInt("unsecure.allow_all_passwords", 0) == 1) {
g_AllowUnsecureFlags = (AllowUnsecure)(g_AllowUnsecureFlags | UNSECURE_ALLOW_ALL_PASSWORDS);
}
-
- g_HederaDefaultTimeout = cfg.getInt("hedera.default_timeout", 5);
+
g_gRPCRelayServerFullURL = cfg.getString("grpc.server", "");
@@ -338,8 +309,8 @@ namespace ServerConfig {
try {
#ifdef POCO_NETSSL_WIN
g_SSL_CLient_Context = new Context(Context::CLIENT_USE, "cacert.pem", Context::VERIFY_RELAXED, Context::OPT_DEFAULTS);
-#else
-
+#else
+
g_SSL_CLient_Context = new Context(Context::CLIENT_USE, "", "", Poco::Path::config() + "grd_login/cacert.pem", Context::VERIFY_RELAXED, 9, true, "ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
#endif
} catch(Poco::Exception& ex) {
@@ -391,7 +362,7 @@ namespace ServerConfig {
Poco::LocalDateTime now;
std::string dateTimeStr = Poco::DateTimeFormatter::format(now, Poco::DateTimeFormat::ISO8601_FORMAT);
- file << dateTimeStr << std::endl;
+ file << dateTimeStr << std::endl;
for (std::string line; std::getline(datas, line); ) {
file << line << std::endl;
@@ -400,4 +371,4 @@ namespace ServerConfig {
file.close();
mutex.unlock();
}
-}
\ No newline at end of file
+}
diff --git a/login_server/src/cpp/ServerConfig.h b/login_server/src/cpp/ServerConfig.h
index 2ae0b6c3d..5608a638e 100644
--- a/login_server/src/cpp/ServerConfig.h
+++ b/login_server/src/cpp/ServerConfig.h
@@ -48,21 +48,6 @@ namespace ServerConfig {
UNSECURE_ALLOW_ALL_PASSWORDS = 8
};
- enum HederaConsensusMessageFormat {
- HEDERA_CONSENSUS_FORMAT_BINARY,
- HEDERA_CONSENSUS_FORMAT_JSON,
- HEDERA_CONSENSUS_FORMAT_BASE64_URLSAVE_NO_PADDING
- };
-
- enum HederaNetworkType {
- HEDERA_MAINNET,
- HEDERA_TESTNET,
- HEDERA_NET_COUNT,
- HEDERA_UNKNOWN
- };
-
-
-
extern Mnemonic g_Mnemonic_WordLists[MNEMONIC_MAX];
@@ -92,16 +77,13 @@ namespace ServerConfig {
extern std::string g_gRPCRelayServerFullURL;
extern MemoryBin* g_CryptoAppSecret;
extern AllowUnsecure g_AllowUnsecureFlags;
- extern HederaConsensusMessageFormat g_ConsensusMessageFormat;
- extern HederaNetworkType g_HederaNetworkType;
- extern Poco::Timespan g_HederaDefaultTimeout;
bool loadMnemonicWordLists();
bool initServerCrypto(const Poco::Util::LayeredConfiguration& cfg);
bool initEMailAccount(const Poco::Util::LayeredConfiguration& cfg);
bool initSSLClientContext();
-
+
void writeToFile(std::istream& datas, std::string fileName);
@@ -109,4 +91,4 @@ namespace ServerConfig {
};
-#endif //__GRADIDO_LOGIN_SERVER_SERVER_CONFIG__
\ No newline at end of file
+#endif //__GRADIDO_LOGIN_SERVER_SERVER_CONFIG__
diff --git a/login_server/src/cpp/SingletonManager/ConnectionManager.cpp b/login_server/src/cpp/SingletonManager/ConnectionManager.cpp
index 5e5bc4935..48db3d29d 100644
--- a/login_server/src/cpp/SingletonManager/ConnectionManager.cpp
+++ b/login_server/src/cpp/SingletonManager/ConnectionManager.cpp
@@ -57,6 +57,7 @@ bool ConnectionManager::setConnectionsFromConfig(const Poco::Util::LayeredConfig
dbConfig << "user=" << config.getString(firstKeyPart + ".db.user", "root") << ";";
dbConfig << "password=" << config.getString(firstKeyPart + ".db.password", "") << ";";
dbConfig << "auto-reconnect=true";
+ std::clog << "try connect with: " << dbConfig.str() << std::endl;
setConnection(dbConfig.str(), type);
diff --git a/login_server/src/cpp/SingletonManager/CronManager.cpp b/login_server/src/cpp/SingletonManager/CronManager.cpp
deleted file mode 100644
index 893cb7040..000000000
--- a/login_server/src/cpp/SingletonManager/CronManager.cpp
+++ /dev/null
@@ -1,200 +0,0 @@
-#include "CronManager.h"
-#include "../lib/JsonRequest.h"
-
-#include "../ServerConfig.h"
-
-
-
-CronManager::CronManager()
- : mInitalized(false), mMainTimer(1000, 600000)
-{
-
-}
-
-CronManager::~CronManager()
-{
- Poco::ScopedLock _lock(mMainWorkMutex);
-
- mMainTimer.stop();
- mInitalized = false;
-
-}
-
-CronManager* CronManager::getInstance()
-{
- static CronManager one;
- return &one;
-}
-
-bool CronManager::init(long defaultPeriodicIntervallMilliseconds/* = 600000*/)
-{
- Poco::ScopedLock _lock(mMainWorkMutex);
- mInitalized = true;
- controller::NodeServer::load(model::table::NODE_SERVER_GRADIDO_COMMUNITY);
-
- mDefaultIntervalMilliseconds = defaultPeriodicIntervallMilliseconds;
- mMainTimer.setPeriodicInterval(defaultPeriodicIntervallMilliseconds);
- Poco::TimerCallback callback(*this, &CronManager::runUpdateStep);
- mMainTimer.start(callback);
-
- return true;
-}
-
-void CronManager::stop()
-{
- Poco::ScopedLock _lock(mMainWorkMutex);
- mInitalized = false;
- mMainTimer.stop();
-}
-
-void CronManager::runUpdateStep(Poco::Timer& timer)
-{
- auto current = Poco::DateTime();
- //printf("%s [CronManager::runUpdateStep] \n", Poco::DateTimeFormatter::format(current, "%d.%m.%y %H:%M:%S.%i").data());
- Poco::ScopedLock _lock(mMainWorkMutex);
- if (!mInitalized) {
- return;
- }
- mNodeServersToPingMutex.lock();
- for (auto it = mNodeServersToPing.begin(); it != mNodeServersToPing.end(); it++)
- {
- // TODO: Make sure that task not already running, for example if community server needs more time for processing that between calls
- // or with schedule update run to short time between calls
- UniLib::controller::TaskPtr ping_node_server_task(new PingServerTask(*it));
- ping_node_server_task->scheduleTask(ping_node_server_task);
- }
- mNodeServersToPingMutex.unlock();
-
- mTimestampsMutex.lock();
- //printf("update timestamp sizes: %d\n", mUpdateTimestamps.size());
- bool timerRestarted = false;
-
- if (mUpdateTimestamps.size() > 0)
- {
- Poco::Timestamp now;
- // update maximal once per second
- now += Poco::Timespan(1, 0);
- while (mUpdateTimestamps.size() > 0 && mUpdateTimestamps.front() < now) {
- // printf("remove update time in past: %d\n", mUpdateTimestamps.front().epochTime());
- mUpdateTimestamps.pop_front();
- }
- if (mUpdateTimestamps.size() > 0) {
- Poco::Timespan next_run = mUpdateTimestamps.front() - now;
- //printf("timer restart called with: %d\n", next_run.seconds());
- //mMainTimer.setPeriodicInterval(next_run.totalMilliseconds());
- mMainTimer.restart(next_run.totalMilliseconds());
- mUpdateTimestamps.pop_front();
- timerRestarted = true;
- }
- }
-
- if (!timerRestarted && mMainTimer.getPeriodicInterval() != mDefaultIntervalMilliseconds) {
- //printf("reset to default interval\n");
- mMainTimer.setPeriodicInterval(mDefaultIntervalMilliseconds);
- //mMainTimer.restart(mDefaultIntervalMilliseconds);
- }
- mTimestampsMutex.unlock();
- //printf("[CronManager::runUpdateStep] end\n");
-}
-
-void CronManager::scheduleUpdateRun(Poco::Timespan timespanInFuture)
-{
- Poco::Timestamp timestamp;
- timestamp += timespanInFuture;
-
- mTimestampsMutex.lock();
- //printf("[CronManager::scheduleUpdateRun] push:\n%d\n", timestamp.epochTime());
- mUpdateTimestamps.push_back(timestamp);
- mUpdateTimestamps.sort();
- auto frontTimestamp = mUpdateTimestamps.front();
- auto backTimestamp = mUpdateTimestamps.back();
- //printf("[CronManager::scheduleUpdateRun] front timestamp and back timestamp:\n%d\n%d\n", frontTimestamp.epochTime(), backTimestamp.epochTime());
- //printf("current: \n%d\n", Poco::Timestamp().epochTime());
- Poco::Timespan next_run = mUpdateTimestamps.front() - Poco::Timestamp();
-
- Poco::DateTime now;
- std::string now_string = Poco::DateTimeFormatter::format(now, "%d.%m.%y %H:%M:%S.%i");
- //printf("%s [CronManager::scheduleUpdateRun] next run in %d seconds, %d millis (intervall: %d, default: %d)\n",
- //now_string.data(), next_run.seconds(), next_run.milliseconds(), mMainTimer.getPeriodicInterval(), mDefaultIntervalMilliseconds);
- if (next_run.seconds() > 0 && mMainTimer.getPeriodicInterval() == mDefaultIntervalMilliseconds) {
- if (mMainWorkMutex.tryLock(100)) {
- mMainTimer.restart(next_run.totalMilliseconds());
- mUpdateTimestamps.pop_front();
- mMainWorkMutex.unlock();
- }
- }
-
- mTimestampsMutex.unlock();
- //printf("[CronManager::scheduleUpdateRun] end\n");
-}
-
-
-void CronManager::addNodeServerToPing(Poco::AutoPtr nodeServer)
-{
- if (nodeServer.isNull() || !nodeServer->getModel()) {
- return;
- }
- if (isNodeServerInList(nodeServer)) {
- return;
- }
- mNodeServersToPingMutex.lock();
- mNodeServersToPing.push_back(nodeServer);
- mNodeServersToPingMutex.unlock();
-
-}
-void CronManager::removeNodeServerToPing(Poco::AutoPtr nodeServer)
-{
- if (nodeServer.isNull() || !nodeServer->getModel()) {
- return;
- }
- mNodeServersToPingMutex.lock();
- int node_server_id = nodeServer->getModel()->getID();
- for (auto it = mNodeServersToPing.begin(); it != mNodeServersToPing.end(); it++) {
- if ((*it)->getModel()->getID() == node_server_id) {
- mNodeServersToPing.erase(it);
- break;
- }
- }
- mNodeServersToPingMutex.unlock();
-}
-
-bool CronManager::isNodeServerInList(Poco::AutoPtr nodeServer)
-{
- bool result = false;
- mNodeServersToPingMutex.lock();
- int node_server_id = nodeServer->getModel()->getID();
- for (auto it = mNodeServersToPing.begin(); it != mNodeServersToPing.end(); it++) {
- if ((*it)->getModel()->getID() == node_server_id) {
- result = true;
- break;
- }
- }
- mNodeServersToPingMutex.unlock();
- return false;
-}
-
-// ***********************************************************************************************************
-PingServerTask::PingServerTask(Poco::AutoPtr nodeServer)
- : CPUTask(ServerConfig::g_CPUScheduler), mNodeServer(nodeServer)
-{
-
-}
-
-PingServerTask::~PingServerTask()
-{
-
-}
-
-int PingServerTask::run()
-{
- //return 0;
- auto current = Poco::DateTime();
- if (model::table::NODE_SERVER_GRADIDO_COMMUNITY == mNodeServer->getModel()->getNodeServerType()) {
- std::string url_port = mNodeServer->getModel()->getUrlWithPort();
- printf("%s [PingServerTask::run] call update for %s\n", Poco::DateTimeFormatter::format(current, "%d.%m.%y %H:%M:%S.%i").data(), url_port.data());
-
- auto json_request = mNodeServer->createJsonRequest();
- json_request.request("updateReadNode");
- }
- return 0;
-}
\ No newline at end of file
diff --git a/login_server/src/cpp/SingletonManager/CronManager.h b/login_server/src/cpp/SingletonManager/CronManager.h
deleted file mode 100644
index e7ff73114..000000000
--- a/login_server/src/cpp/SingletonManager/CronManager.h
+++ /dev/null
@@ -1,66 +0,0 @@
-#ifndef __GRADIDO_LOGIN_SERVER_SINGLETON_MANAGER_CRON_MANAGER_H
-#define __GRADIDO_LOGIN_SERVER_SINGLETON_MANAGER_CRON_MANAGER_H
-
-#include "Poco/Timer.h"
-#include "../controller/NodeServer.h"
-#include "../tasks/CPUTask.h"
-
-
-/*!
- * \author: Dario Rekowski
- *
- * \date: 2020-11-03
- *
- * \brief: Manager for "Cron"-like Tasks.
- *
- * Ping for example community server to get new blocks from nodes
- * or Hedera Tasks to (re)try receiving Transaction Receipts
- *
- */
-class CronManager
-{
-public:
- ~CronManager();
-
- static CronManager* getInstance();
-
- bool init(long defaultPeriodicIntervallMilliseconds = 600000);
- void stop();
-
- void runUpdateStep(Poco::Timer& timer);
- void scheduleUpdateRun(Poco::Timespan timespanInFuture);
-
-
- void addNodeServerToPing(Poco::AutoPtr nodeServer);
- void removeNodeServerToPing(Poco::AutoPtr nodeServer);
-
-protected:
- CronManager();
-
- bool isNodeServerInList(Poco::AutoPtr nodeServer);
- bool mInitalized;
-
- Poco::Timer mMainTimer;
- std::list> mNodeServersToPing;
- std::list mUpdateTimestamps;
- Poco::FastMutex mNodeServersToPingMutex;
- Poco::FastMutex mMainWorkMutex;
- Poco::FastMutex mTimestampsMutex;
- long mDefaultIntervalMilliseconds;
-};
-
-class PingServerTask : public UniLib::controller::CPUTask
-{
-public:
- PingServerTask(Poco::AutoPtr nodeServer);
- virtual ~PingServerTask();
-
- const char* getResourceType() const { return "PingServerTask"; }
-
- int run();
-
-protected:
- Poco::AutoPtr mNodeServer;
-};
-
-#endif //__GRADIDO_LOGIN_SERVER_SINGLETON_MANAGER_CRON_MANAGER_H
\ No newline at end of file
diff --git a/login_server/src/cpp/controller/CryptoKey.cpp b/login_server/src/cpp/controller/CryptoKey.cpp
deleted file mode 100644
index 338ad05a4..000000000
--- a/login_server/src/cpp/controller/CryptoKey.cpp
+++ /dev/null
@@ -1,150 +0,0 @@
-
-#include "CryptoKey.h"
-#include "../SingletonManager/ErrorManager.h"
-#include "../lib/DataTypeConverter.h"
-
-namespace controller {
-
- CryptoKey::CryptoKey(model::table::CryptoKey* dbModel)
- {
- mDBModel = dbModel;
- }
-
- CryptoKey::~CryptoKey()
- {
-
- }
-
- Poco::AutoPtr CryptoKey::create(const KeyPairHedera* hederaKeyPair, Poco::AutoPtr user, bool saveEncrypted/* = true*/)
- {
- auto mm = MemoryManager::getInstance();
-
- MemoryBin* private_key = nullptr;
- auto public_key = hederaKeyPair->getPublicKeyCopy();
-
- model::table::KeyType key_type;
- if (saveEncrypted) {
- key_type = model::table::KEY_TYPE_ED25519_HEDERA_ENCRYPTED;
- private_key = hederaKeyPair->getCryptedPrivKey(user->getPassword());
- }
- else {
- key_type = model::table::KEY_TYPE_ED25519_HEDERA_CLEAR;
- private_key = hederaKeyPair->getPrivateKeyCopy();
- }
- auto db = new model::table::CryptoKey(private_key, public_key, key_type);
-
- mm->releaseMemory(private_key);
- mm->releaseMemory(public_key);
-
- auto cryptoKey = new CryptoKey(db);
- return Poco::AutoPtr(cryptoKey);
- }
-
- Poco::AutoPtr CryptoKey::load(int id)
- {
- auto db = new model::table::CryptoKey();
- if (1 == db->loadFromDB("id", id)) {
- auto cryptoKey = new CryptoKey(db);
- return Poco::AutoPtr(cryptoKey);
- }
- return nullptr;
- }
-
- Poco::AutoPtr CryptoKey::load(MemoryBin* publicKey)
- {
- return load(*publicKey, publicKey->size());
- }
-
- Poco::AutoPtr CryptoKey::load(const unsigned char* publicKey, size_t size)
- {
- assert(publicKey);
- assert(size);
-
- Poco::Data::BLOB public_key_blob(publicKey, size);
- auto db = new model::table::CryptoKey();
- auto count = db->loadFromDB("public_key", public_key_blob);
- if (!count) return nullptr;
- if (1 == count) return new CryptoKey(db);
-
- auto em = ErrorManager::getInstance();
- em->addError(new Error("CryptoKey::load", "found more than one crypto key with same public key"));
- em->sendErrorsAsEmail();
- return nullptr;
- }
-
- std::unique_ptr CryptoKey::getKeyPair(Poco::AutoPtr user) const
- {
- auto model = getModel();
- assert(model);
-
- if (!model->isEncrypted()) {
- return getKeyPair();
- }
-
- if (!model->hasPrivateKey()) {
- printf("[CryptoKey::getKeyPair] return null, no private key\n");
- return nullptr;
- }
-
- auto password = user->getPassword();
- auto mm = MemoryManager::getInstance();
- if (!password) {
- printf("[CryptoKey::getKeyPair] return null, password empty\n");
- }
- MemoryBin* clearPrivateKey = nullptr;
- auto encrypted_private_key = model->getPrivateKey();
- //auto encrypted_private_key_hex_string = DataTypeConverter::binToHex(encrypted_private_key);
- //printf("[CryptoKey::getKeyPair] encrypted private key hex: %s\n", encrypted_private_key_hex_string.data());
- if (password->decrypt(model->getPrivateKey(), &clearPrivateKey) != SecretKeyCryptography::AUTH_DECRYPT_OK) {
- printf("[CryptoKey::getKeyPair] return null, error decrypting\n");
- return nullptr;
- }
- auto key_pair = std::make_unique(clearPrivateKey->data(), clearPrivateKey->size(), model->getPublicKey(), model->getPublicKeySize());
- mm->releaseMemory(clearPrivateKey);
- return key_pair;
- }
-
- std::unique_ptr CryptoKey::getKeyPair() const
- {
- auto model = getModel();
- assert(model);
- if (!model->hasPrivateKey() || model->isEncrypted()) {
- printf("[CryptoKey::getKeyPair] no private key or encrypted\n");
- return nullptr;
- }
-
-
- return std::make_unique(model->getPrivateKey(), model->getPublicKey(), model->getPublicKeySize());
- }
-
- bool CryptoKey::changeEncryption(Poco::AutoPtr user)
- {
- auto key_pair = getKeyPair(user);
- if (!key_pair || !key_pair->hasPrivateKey()) {
- addError(new Error("Crypto Key", "key pair or private key was null"));
- return false;
- }
- auto model = getModel();
- auto mm = MemoryManager::getInstance();
- // update key type
- model->changeKeyTypeToggleEncrypted();
- MemoryBin* private_key = nullptr;
- if (model->isEncrypted()) {
- private_key = key_pair->getCryptedPrivKey(user->getPassword());
- }
- else {
- private_key = key_pair->getPrivateKeyCopy();
- }
- if (!private_key) {
- addError(new Error("Crypto Key", " private_key not get"));
- return false;
- }
- model->setPrivateKey(private_key);
- // save changes into db
- model->updatePrivkeyAndKeyType();
-
- mm->releaseMemory(private_key);
- return true;
- }
-}
-
diff --git a/login_server/src/cpp/controller/CryptoKey.h b/login_server/src/cpp/controller/CryptoKey.h
deleted file mode 100644
index ddd2a7435..000000000
--- a/login_server/src/cpp/controller/CryptoKey.h
+++ /dev/null
@@ -1,50 +0,0 @@
-#ifndef GRADIDO_LOGIN_SERVER_CONTROLLER_CRYPTO_KEY_INCLUDE
-#define GRADIDO_LOGIN_SERVER_CONTROLLER_CRYPTO_KEY_INCLUDE
-
-#include "../model/table/CryptoKey.h"
-#include "../Crypto/KeyPairHedera.h"
-
-#include "Poco/SharedPtr.h"
-
-#include "TableControllerBase.h"
-#include "User.h"
-
-
-
-namespace controller {
-
- class HederaAccount;
-
- class CryptoKey : public TableControllerBase, public NotificationList
- {
- friend HederaAccount;
- public:
-
- ~CryptoKey();
-
- static Poco::AutoPtr create(const KeyPairHedera* hederaKeyPair, Poco::AutoPtr user, bool saveEncrypted = true);
-
- //! if returned ptr is NULL, dataset not found
- static Poco::AutoPtr load(int id);
- static Poco::AutoPtr load(MemoryBin* publicKey);
- static Poco::AutoPtr load(const unsigned char* publicKey, size_t size);
-
- inline bool deleteFromDB() { return mDBModel->deleteFromDB(); }
-
- inline Poco::AutoPtr getModel() { return _getModel(); }
- inline const model::table::CryptoKey* getModel() const { return _getModel(); }
-
- std::unique_ptr getKeyPair(Poco::AutoPtr user) const;
- std::unique_ptr getKeyPair() const;
-
-
-
- protected:
-
- bool changeEncryption(Poco::AutoPtr user);
- CryptoKey(model::table::CryptoKey* dbModel);
-
- };
-}
-
-#endif //GRADIDO_LOGIN_SERVER_CONTROLLER_CRYPTO_KEY_INCLUDE
\ No newline at end of file
diff --git a/login_server/src/cpp/controller/HederaAccount.cpp b/login_server/src/cpp/controller/HederaAccount.cpp
deleted file mode 100644
index e6e4e490e..000000000
--- a/login_server/src/cpp/controller/HederaAccount.cpp
+++ /dev/null
@@ -1,294 +0,0 @@
-
-#include "HederaAccount.h"
-#include "NodeServer.h"
-#include "CryptoKey.h"
-#include "../model/hedera/Query.h"
-//#include "../model/hedera/Tr"
-#include "HederaRequest.h"
-
-#include "../SingletonManager/ErrorManager.h"
-
-using namespace Poco::Data::Keywords;
-
-namespace controller {
-
- HederaAccount::HederaAccount(model::table::HederaAccount* dbModel)
- {
- mDBModel = dbModel;
- }
-
- HederaAccount::~HederaAccount()
- {
- }
-
- Poco::AutoPtr HederaAccount::create(int user_id, int account_hedera_id, int account_key_id, Poco::UInt64 balance/* = 0*/, ServerConfig::HederaNetworkType type/* = HEDERA_MAINNET*/)
- {
- auto db = new model::table::HederaAccount(user_id, account_hedera_id, account_key_id, balance, type);
- auto group = new HederaAccount(db);
- return Poco::AutoPtr(group);
- }
-
- std::vector> HederaAccount::load(const std::string& fieldName, int fieldValue)
- {
- auto db = new model::table::HederaAccount();
- auto hedera_account_list = db->loadFromDB(fieldName, fieldValue, 2);
- std::vector> resultVector;
- resultVector.reserve(hedera_account_list.size());
- for (auto it = hedera_account_list.begin(); it != hedera_account_list.end(); it++) {
- //mHederaID
- auto db = new model::table::HederaAccount(*it);
- auto hedera_account = new HederaAccount(db);
- resultVector.push_back(hedera_account);
- }
- return resultVector;
- }
-
- Poco::AutoPtr HederaAccount::load(int id)
- {
- auto db = new model::table::HederaAccount();
- if (1 == db->loadFromDB("id", id)) {
- return new HederaAccount(db);
- }
- db->release();
- return nullptr;
- }
-
- Poco::AutoPtr HederaAccount::getHederaId()
- {
- if (mHederaID.isNull()) {
- mHederaID = HederaId::load(getModel()->getAccountHederaId());
- }
- return mHederaID;
- }
-
- Poco::AutoPtr HederaAccount::load(Poco::AutoPtr hederaId)
- {
- if (!hederaId->isExistInDB()) return nullptr;
-
- auto db = new model::table::HederaAccount();
- auto result_count = db->loadFromDB("account_hedera_id", hederaId->getModel()->getID());
- if (1 == result_count) {
- return new HederaAccount(db);
- }
- // maybe change later to using error manager and send email
- printf("[HederaAccount::load] result_count not expected: %d\n", result_count);
- return nullptr;
- }
-
- Poco::AutoPtr HederaAccount::pick(ServerConfig::HederaNetworkType networkType, bool encrypted/* = false*/, int user_id/* = 0*/)
- {
- auto cm = ConnectionManager::getInstance();
- auto session = cm->getConnection(CONNECTION_MYSQL_LOGIN_SERVER);
- Poco::Data::Statement select(session);
-
- Poco::Tuple result_tuple;
- int crypto_key_type = encrypted ? model::table::KEY_TYPE_ED25519_HEDERA_ENCRYPTED : model::table::KEY_TYPE_ED25519_HEDERA_CLEAR;
- int network_type_int = (int)networkType;
-
- select
- << "SELECT account.id, account.user_id, account.account_hedera_id, account.account_key_id, account.balance, i.shardNum, i.realmNum, i.num "
- << "FROM hedera_accounts as account "
- << "JOIN hedera_ids as i ON(i.id = account_hedera_id) "
- << "JOIN crypto_keys as k ON(k.id = account.account_key_id) "
- << "WHERE account.network_type = ? "
- << "AND k.crypto_key_type_id = ? ";
-
- if (user_id > 0) {
- select << " AND account.user_id = ? ";
- }
- select << "ORDER BY RAND() LIMIT 1 "
- , into(result_tuple), use(network_type_int) , use(crypto_key_type);
-
- if (user_id > 0) {
- select, use(user_id);
- }
-
- try {
- select.executeAsync();
- select.wait();
- auto result_count = select.rowsExtracted();
- if (1 == result_count) {
- auto db = new model::table::HederaAccount(
- result_tuple.get<1>(), result_tuple.get<2>(), result_tuple.get<3>(),
- result_tuple.get<4>(), networkType
- );
- db->setID(result_tuple.get<0>());
- Poco::AutoPtr hedera_account(new HederaAccount(db));
- auto hedera_id_db = new model::table::HederaId(result_tuple.get<5>(), result_tuple.get<6>(), result_tuple.get<7>());
- Poco::AutoPtr hedera_id(new HederaId(hedera_id_db));
- hedera_account->setHederaId(hedera_id);
- return hedera_account;
- }
- else if(result_count > 1) {
- printf("[HederaAccount::pick] extracted rows not like expected\n");
- }
- }
- catch (Poco::Exception& ex) {
- auto em = ErrorManager::getInstance();
- static const char* function_name = "HederaAccount::pick";
- printf("exception: %s\n", ex.displayText().data());
- em->addError(new ParamError(function_name, "mysql error: ", ex.displayText()));
- em->addError(new ParamError(function_name, "network type: ", networkType));
- em->addError(new ParamError(function_name, "encrypted: ", (int)encrypted));
- em->sendErrorsAsEmail();
- }
-
- return nullptr;
-
- }
-
- std::vector> HederaAccount::listAll()
- {
- auto db = new model::table::HederaAccount();
- std::vector group_list;
- // throw an unresolved external symbol error
- group_list = db->loadAllFromDB();
-
- // work around for not working call to loadAllFromDB
- /*auto cm = ConnectionManager::getInstance();
-
- Poco::Data::Statement select(cm->getConnection(CONNECTION_MYSQL_LOGIN_SERVER));
-
- select << "SELECT id, alias, name, url, description FROM " << db->getTableName()
- , Poco::Data::Keywords::into(group_list);
-
- size_t resultCount = 0;
- try {
- resultCount = select.execute();
- }
- catch (Poco::Exception& ex) {
- printf("[Group::listAll] poco exception: %s\n", ex.displayText().data());
- }
- //*/ //work around end
- std::vector> resultVector;
-
- resultVector.reserve(group_list.size());
- for (auto it = group_list.begin(); it != group_list.end(); it++) {
- Poco::AutoPtr group_ptr(new HederaAccount(new model::table::HederaAccount(*it)));
- resultVector.push_back(group_ptr);
- }
- return resultVector;
- }
-
- Poco::AutoPtr HederaAccount::getCryptoKey() const
- {
- auto model = getModel();
- return controller::CryptoKey::load(model->getCryptoKeyId());
- }
-
- bool HederaAccount::hederaAccountGetBalance(Poco::AutoPtr user)
- {
- static const char* functionName = "HederaAccount::updateBalanceFromHedera";
-
- if (user.isNull() || !user->getModel()) {
- printf("[%s] invalid user\n", functionName);
- return false;
- }
-
- auto account_model = getModel();
- auto hedera_node = NodeServer::pick(account_model->networkTypeToNodeServerType(account_model->getNetworkType()));
- if (hedera_node.url == "") {
- addError(new Error("Hedera Node", "no hedera node found"));
- return false;
- }
- auto crypto_key = controller::CryptoKey::load(account_model->getCryptoKeyId());
- if (crypto_key.isNull()) {
- addError(new Error("Keys", "could not found crypto key for account"));
- printf("[%s] error, crypto key with id: %d not found\n", functionName, account_model->getCryptoKeyId());
- return false;
- }
- auto hedera_key_pair = crypto_key->getKeyPair(user);
- if (!hedera_key_pair) {
- addError(new Error("Keys", "error decrypting private key"));
- printf("[%s] error decrypting private key with id: %d, with user: %d\n", functionName, account_model->getCryptoKeyId(), user->getModel()->getID());
- return false;
- }
-
- auto query = model::hedera::Query::getBalance(getHederaId(), hedera_node);
-
- if (!query) {
- printf("[%s] error creating query\n", functionName);
- }
- query->sign(std::move(hedera_key_pair));
-
- HederaRequest request;
- model::hedera::Response response;
- try {
- if (HEDERA_REQUEST_RETURN_OK == request.request(query, &response) && proto::OK == response.getResponseCode()) {
- account_model->updateIntoDB("balance", response.getAccountBalance());
- }
- else {
- addError(new Error("Hedera", "Hedera request failed"));
- addError(new ParamError("Hedera", "Hedera Response Code", proto::ResponseCodeEnum_Name(response.getResponseCode())));
- }
- //request.requestViaPHPRelay(query);
- }
- catch (Poco::Exception& ex) {
- printf("[HederaAccount::updateBalanceFromHedera] exception calling hedera request: %s\n", ex.displayText().data());
- }
-
- if (0 == errorCount() && 0 == request.errorCount()) {
- return true;
- }
- getErrors(&request);
-
- return false;
- }
-
- bool HederaAccount::hederaAccountCreate(int autoRenewPeriodSeconds, double initialBalance)
- {
- auto account_model = getModel();
- auto new_key_pair = KeyPairHedera::create();
- auto transaction_body = createTransactionBody();
- //CryptoCreateTransaction(const unsigned char* publicKey, Poco::UInt64 initialBalance, int autoRenewPeriod);
- model::hedera::CryptoCreateTransaction create_transaction(new_key_pair->getPublicKey(), initialBalance, autoRenewPeriodSeconds);
- transaction_body->setCryptoCreate(create_transaction);
-
-
- return false;
- }
-
- bool HederaAccount::changeEncryption(Poco::AutoPtr user)
- {
- assert(!user.isNull() && user->getModel());
- auto model = getModel();
- assert(!model.isNull());
-
- if (user->getModel()->getID() != model->getUserId()) {
- addError(new Error("Hedera Account", "wrong user"));
- return false;
- }
- auto crypto_key = controller::CryptoKey::load(model->getCryptoKeyId());
- if (crypto_key.isNull()) {
- addError(new Error("Hedera Account", "couldn't find crypto key"));
- return false;
- }
- bool result = crypto_key->changeEncryption(user);
- getErrors(crypto_key);
- return result;
-
- }
-
- std::unique_ptr HederaAccount::createTransactionBody()
- {
- auto account_model = getModel();
- auto hedera_node = NodeServer::pick(account_model->networkTypeToNodeServerType(account_model->getNetworkType()));
- auto hedera_id = getHederaId();
- if (hedera_id.isNull()) {
- return nullptr;
- }
- return std::make_unique(mHederaID, hedera_node);
- }
-
-
- std::string HederaAccount::toShortSelectOptionName()
- {
- std::stringstream ss;
- auto model = getModel();
- ss << model::table::HederaAccount::hederaNetworkTypeToString((ServerConfig::HederaNetworkType)model->getNetworkType()) << " ";
- ss << getHederaId()->getModel()->toString() << " " << ((double)model->getBalance() / 100000000.0) << " Hbar";
- return ss.str();
- }
-
-}
-
diff --git a/login_server/src/cpp/controller/HederaAccount.h b/login_server/src/cpp/controller/HederaAccount.h
deleted file mode 100644
index 9490b4bfb..000000000
--- a/login_server/src/cpp/controller/HederaAccount.h
+++ /dev/null
@@ -1,56 +0,0 @@
-#ifndef GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_ACCOUNT_INCLUDE
-#define GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_ACCOUNT_INCLUDE
-
-#include "HederaId.h"
-#include "User.h"
-#include "../model/table/HederaAccount.h"
-
-#include "../model/hedera/TransactionBody.h"
-
-#include "Poco/SharedPtr.h"
-
-#include "TableControllerBase.h"
-#include "CryptoKey.h"
-
-namespace controller {
- class HederaAccount : public TableControllerBase, public NotificationList
- {
- public:
- ~HederaAccount();
-
- static Poco::AutoPtr create(int user_id, int account_hedera_id, int account_key_id, Poco::UInt64 balance = 0, ServerConfig::HederaNetworkType type = ServerConfig::HEDERA_MAINNET);
-
- static std::vector> load(const std::string& fieldName, int fieldValue);
- static Poco::AutoPtr load(int id);
- static Poco::AutoPtr load(Poco::AutoPtr hederaId);
- static std::vector> listAll();
- //! \brief for picking a account for paying transaction, mostly consensusSendMessage
- static Poco::AutoPtr pick(ServerConfig::HederaNetworkType networkType, bool encrypted = false, int user_id = 0);
-
- inline bool deleteFromDB() { return mDBModel->deleteFromDB(); }
-
- std::string toShortSelectOptionName();
-
- inline Poco::AutoPtr getModel() { return _getModel(); }
- inline const model::table::HederaAccount* getModel() const { return _getModel(); }
-
- inline void setHederaId(Poco::AutoPtr hederaId) { mHederaID = hederaId; }
- Poco::AutoPtr getHederaId();
-
- Poco::AutoPtr getCryptoKey() const;
-
- bool hederaAccountGetBalance(Poco::AutoPtr user);
- bool hederaAccountCreate(int autoRenewPeriodSeconds, double initialBalance);
- bool changeEncryption(Poco::AutoPtr user);
-
- //! \brief create Transaction body with this hedera account as operator
- std::unique_ptr createTransactionBody();
-
- protected:
-
- HederaAccount(model::table::HederaAccount* dbModel);
- Poco::AutoPtr mHederaID;
- };
-}
-
-#endif //GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_ACCOUNT_INCLUDE
diff --git a/login_server/src/cpp/controller/HederaId.cpp b/login_server/src/cpp/controller/HederaId.cpp
deleted file mode 100644
index 3e7da7319..000000000
--- a/login_server/src/cpp/controller/HederaId.cpp
+++ /dev/null
@@ -1,127 +0,0 @@
-#include "HederaId.h"
-#include "../SingletonManager/ErrorManager.h"
-#include "../SingletonManager/SessionManager.h"
-
-#include "../lib/DataTypeConverter.h"
-
-using namespace Poco::Data::Keywords;
-
-namespace controller {
-
- HederaId::HederaId(model::table::HederaId* dbModel)
- {
- mDBModel = dbModel;
- }
-
- HederaId::~HederaId()
- {
-
- }
-
- Poco::AutoPtr HederaId::create(Poco::UInt64 shardNum, Poco::UInt64 realmNum, Poco::UInt64 num)
- {
- auto db = new model::table::HederaId(shardNum, realmNum, num);
-
- auto hedera_id = new HederaId(db);
- return Poco::AutoPtr(hedera_id);
- }
-
- Poco::AutoPtr HederaId::create(std::string hederaIdString)
- {
- auto sm = SessionManager::getInstance();
- if (!sm->isValid(hederaIdString, VALIDATE_HEDERA_ID)) {
- return nullptr;
- }
- std::vector number_strings;
- std::istringstream f(hederaIdString);
- std::string s;
- while (getline(f, s, '.')) {
- std::cout << s << std::endl;
- number_strings.push_back(s);
- }
- Poco::UInt64 numbers[3];
- for (int i = 0; i < 3; i++) {
- unsigned long long temp_number;
- if (DataTypeConverter::NUMBER_PARSE_OKAY != DataTypeConverter::strToInt(number_strings[i], temp_number)) {
- return nullptr;
- }
- numbers[i] = temp_number;
- }
- auto db = new model::table::HederaId(numbers[0], numbers[1], numbers[2]);
-
- auto hedera_id = new HederaId(db);
- return Poco::AutoPtr(hedera_id);
- }
-
- Poco::AutoPtr HederaId::load(int id)
- {
- auto db = new model::table::HederaId();
- if (1 == db->loadFromDB("id", id)) {
- auto cryptoKey = new HederaId(db);
- return Poco::AutoPtr(cryptoKey);
- }
- return nullptr;
- }
-
- Poco::AutoPtr HederaId::find(int groupId, ServerConfig::HederaNetworkType networkType)
- {
- auto cm = ConnectionManager::getInstance();
- auto session = cm->getConnection(CONNECTION_MYSQL_LOGIN_SERVER);
- model::table::HederaIdTuple result_tuple;
- int network_type_int = (int)networkType;
-
- Poco::Data::Statement select(session);
- select << "SELECT h.id, h.shardNum, h.realmNum, h.num FROM hedera_ids as h "
- << "JOIN hedera_topics as topic ON(topic.topic_hedera_id = h.id) "
- << "JOIN hedera_accounts as account ON(account.id = topic.auto_renew_account_hedera_id) "
- << "WHERE topic.group_id = ? AND account.network_type = ?"
- , into(result_tuple), use(groupId), use(network_type_int);
-
- try {
- select.executeAsync();
- select.wait();
- auto result_count = select.rowsExtracted();
- if (1 == result_count) {
- return new HederaId(new model::table::HederaId(result_tuple));
- }
- else if(result_count > 1) {
- printf("[HederaId::find] result_count other as expected: %d\n", result_count);
- }
- }
- catch (Poco::Exception& ex) {
- auto em = ErrorManager::getInstance();
- static const char* function_name = "HederaId::find";
- em->addError(new ParamError(function_name, "mysql error: ", ex.displayText()));
- em->addError(new ParamError(function_name, "group id: ", groupId));
- em->addError(new ParamError(function_name, "network type: ", (int)networkType));
- em->sendErrorsAsEmail();
- }
- return nullptr;
- }
-
- void HederaId::copyToProtoAccountId(proto::AccountID* protoAccountId) const
- {
- auto model = getModel();
- protoAccountId->set_shardnum(model->getShardNum());
- protoAccountId->set_realmnum(model->getRealmNum());
- protoAccountId->set_accountnum(model->getNum());
- }
-
- void HederaId::copyToProtoTopicId(proto::TopicID* protoTopicId) const
- {
- auto model = getModel();
- protoTopicId->set_shardnum(model->getShardNum());
- protoTopicId->set_realmnum(model->getRealmNum());
- protoTopicId->set_topicnum(model->getNum());
- }
-
- bool HederaId::isExistInDB()
- {
- auto model = getModel();
- if (model->getID() > 0) return true;
- //std::vector loadFromDB(const std::vector& fieldNames, const std::vector& fieldValues, MysqlConditionType conditionType = MYSQL_CONDITION_AND, int expectedResults = 0);
- model->isExistInDB();
- return model->getID() != 0;
-
- }
-}
\ No newline at end of file
diff --git a/login_server/src/cpp/controller/HederaId.h b/login_server/src/cpp/controller/HederaId.h
deleted file mode 100644
index fb43cd82b..000000000
--- a/login_server/src/cpp/controller/HederaId.h
+++ /dev/null
@@ -1,46 +0,0 @@
-#ifndef GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_ID_INCLUDE
-#define GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_ID_INCLUDE
-
-#include "../model/table/HederaId.h"
-#include "../model/table/HederaAccount.h"
-
-#include "Poco/SharedPtr.h"
-
-#include "TableControllerBase.h"
-
-#include "proto/hedera/BasicTypes.pb.h"
-
-namespace controller {
- class HederaAccount;
- class HederaId : public TableControllerBase
- {
- friend HederaAccount;
- public:
-
- ~HederaId();
-
- static Poco::AutoPtr create(Poco::UInt64 shardNum, Poco::UInt64 realmNum, Poco::UInt64 num);
- static Poco::AutoPtr create(std::string hederaIdString);
-
- static Poco::AutoPtr load(int id);
- //! \return hedera topic id for group and network type (should exist only one)
- static Poco::AutoPtr find(int groupId, ServerConfig::HederaNetworkType networkType);
-
- bool isExistInDB();
-
- inline bool deleteFromDB() { return mDBModel->deleteFromDB(); }
-
- inline Poco::AutoPtr getModel() { return _getModel(); }
- inline const model::table::HederaId* getModel() const { return _getModel(); }
-
- void copyToProtoAccountId(proto::AccountID* protoAccountId) const;
- void copyToProtoTopicId(proto::TopicID* protoTopicId) const;
-
-
- protected:
- HederaId(model::table::HederaId* dbModel);
-
- };
-}
-
-#endif //GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_ID_INCLUDE
diff --git a/login_server/src/cpp/controller/HederaRequest.cpp b/login_server/src/cpp/controller/HederaRequest.cpp
deleted file mode 100644
index 9a01d3bc1..000000000
--- a/login_server/src/cpp/controller/HederaRequest.cpp
+++ /dev/null
@@ -1,174 +0,0 @@
-#include "HederaRequest.h"
-#include "../proto/hedera/CryptoService.grpc.pb.h"
-#include "../proto/hedera/ConsensusService.grpc.pb.h"
-
-#include "../lib/DataTypeConverter.h"
-
-#include
-#include
-#include
-#include
-#include
-
-
-HederaRequest::HederaRequest()
-{
-
-}
-
-HederaRequest::~HederaRequest()
-{
-
-}
-
-HederaRequestReturn HederaRequest::request(model::hedera::Query* query, model::hedera::Response* response, Poco::UInt64 fee/* = 0*/)
-{
- auto channel = grpc::CreateChannel(query->getConnectionString(), grpc::InsecureChannelCredentials());
-
- grpc::ClientContext context;
- std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() +
- std::chrono::milliseconds(5000);
- context.set_deadline(deadline);
- //grpc::CompletionQueue cq;
-
- auto proto_query = query->getProtoQuery();
-
- auto proto_query_serialized = proto_query->SerializeAsString();
- //auto query_hex_string = DataTypeConverter::binToHex((unsigned char*)proto_query_serialized.data(), proto_query_serialized.size());
- //printf("[HederaRequest::request] query as hex: %s\n", query_hex_string.data());
-
- auto proto_response = response->getResponsePtr();
- auto connect_string = query->getConnectionString();
-
- grpc::Status status;
- std::string queryName;
-
- if (proto_query->has_cryptogetaccountbalance())
- {
- auto stub = proto::CryptoService::NewStub(channel);
- // crypto account get balance currently hasn't fees
- query->setResponseType(proto::ANSWER_ONLY);
-
- queryName = "crypte get balance";
- status = stub->cryptoGetBalance(&context, *proto_query, proto_response);
-
- }
- else if (proto_query->has_consensusgettopicinfo())
- {
- auto stub = proto::ConsensusService::NewStub(channel);
-
- queryName = "consensus topic get info";
- status = stub->getTopicInfo(&context, *proto_query, proto_response);
-
- }
- else if (proto_query->has_transactiongetreceipt()) {
- auto stub = proto::CryptoService::NewStub(channel);
-
- queryName = "crypto transaction get receipt";
- status = stub->getTransactionReceipts(&context, *proto_query, proto_response);
- }
- else if (proto_query->has_transactiongetrecord()) {
- auto stub = proto::CryptoService::NewStub(channel);
-
- queryName = "crypto transaction get record";
- status = stub->getTxRecordByTxID(&context, *proto_query, proto_response);
-
- }
- else {
- addError(new Error("Hedera Request", "unknown or empty query"));
- return HEDERA_REQUEST_UNKNOWN_QUERY;
- }
- if (status.ok())
- {
- auto response_code = response->getResponseCode();
- if (response_code) {
- addError(new ParamError("Hedera Request", "precheck code: ", proto::ResponseCodeEnum_Name(response_code)));
- return HEDERA_REQUEST_PRECHECK_ERROR;
- }
- else {
- return HEDERA_REQUEST_RETURN_OK;
- }
-
- }
- else if("" != queryName)
- {
- addError(new ParamError("Hedera Request", "query name: ", queryName));
- addError(new ParamError("Hedera Request", "error message: ", status.error_message()));
- addError(new ParamError("Hedera Request", "details: ", status.error_details()));
- return HEDERA_REQUEST_RETURN_ERROR;
- }
- return HEDERA_REQUEST_UNKNOWN_QUERY;
-}
-
-
-HederaRequestReturn HederaRequest::request(model::hedera::Transaction* transaction, model::hedera::Response* response)
-{
- auto channel = grpc::CreateChannel(transaction->getConnectionString(), grpc::InsecureChannelCredentials());
-
- grpc::ClientContext context;
- std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() +
- std::chrono::milliseconds(5000);
- context.set_deadline(deadline);
-
- return HEDERA_REQUEST_RETURN_OK;
-}
-
-HederaRequestReturn HederaRequest::request(model::hedera::Transaction* transaction, HederaTask* task)
-{
- assert(transaction && task);
- auto channel = grpc::CreateChannel(transaction->getConnectionString(), grpc::InsecureChannelCredentials());
-
- grpc::ClientContext context;
- std::chrono::system_clock::time_point deadline = std::chrono::system_clock::now() +
- std::chrono::milliseconds(5000);
- context.set_deadline(deadline);
- auto transaction_type = transaction->getType();
- task->setTransactionId(transaction->getTransactionId());
- if (model::hedera::TRANSACTION_CONSENSUS_SUBMIT_MESSAGE == transaction_type ||
- model::hedera::TRANSACTION_CONSENSUS_CREATE_TOPIC == transaction_type) {
- auto stub = proto::ConsensusService::NewStub(channel);
- grpc::Status status;
- std::string service_name;
- if (model::hedera::TRANSACTION_CONSENSUS_SUBMIT_MESSAGE == transaction_type) {
- status = stub->submitMessage(&context, *transaction->getTransaction(), task->getTransactionResponse()->getProtoResponse());
- service_name = "submitMessage";
- }
- else if (model::hedera::TRANSACTION_CONSENSUS_CREATE_TOPIC == transaction_type) {
- status = stub->createTopic(&context, *transaction->getTransaction(), task->getTransactionResponse()->getProtoResponse());
- service_name = "createTopic";
- }
- if (status.ok()) {
- return HEDERA_REQUEST_RETURN_OK;
- }
- else {
- addError(new ParamError("Hedera Request", "consensus service error message:", status.error_message()));
- addError(new ParamError("Hedera Request", "service name", service_name));
- addError(new ParamError("Hedera Request", "details: ", status.error_details()));
- return HEDERA_REQUEST_RETURN_ERROR;
- }
- }
-
- addError(new ParamError("Hedera Request", "not implementet or unknown transaction type", transaction_type));
- return HEDERA_REQUEST_UNKNOWN_TRANSACTION;
-}
-
-#include "Poco/JSON/Object.h"
-#include "../lib/JsonRequest.h"
-
-HederaRequestReturn HederaRequest::requestViaPHPRelay(model::hedera::Query* query)
-{
- JsonRequest phpRelay("***REMOVED***", 88);
- Poco::Net::NameValueCollection parameters;
- std::string query_string = query->getProtoQuery()->SerializeAsString();
- //auto query_base64 = DataTypeConverter::binToBase64((const unsigned char*)query_string.data(), query_string.size(), sodium_base64_VARIANT_URLSAFE_NO_PADDING);
- //auto findPos = query_string.find_first_of("\u");
- auto query_hex = DataTypeConverter::binToHex((const unsigned char*)query_string.data(), query_string.size());
- parameters.set("content", query_hex.substr(0, query_hex.size()-1));
- parameters.set("server", query->getConnectionString());
- parameters.set("method", "getBalance");
- parameters.set("service", "crypto");
- phpRelay.requestGRPCRelay(parameters);
- //phpRelay.request("")
-
- return HEDERA_REQUEST_RETURN_OK;
-}
\ No newline at end of file
diff --git a/login_server/src/cpp/controller/HederaRequest.h b/login_server/src/cpp/controller/HederaRequest.h
deleted file mode 100644
index 51606f2b0..000000000
--- a/login_server/src/cpp/controller/HederaRequest.h
+++ /dev/null
@@ -1,53 +0,0 @@
-#ifndef __GRADIDO_LOGIN_SERVER_LIB_HEDERA_REQUEST_
-#define __GRADIDO_LOGIN_SERVER_LIB_HEDERA_REQUEST_
-/*!
-*
-* \author: Dario Rekowski
-*
-* \date: 31.08.2020
-*
-* \brief: Class for Hedera Requests
-*
-*/
-
-#include "../controller/NodeServer.h"
-#include "../model/hedera/Query.h"
-#include "../model/hedera/TransactionGetReceiptQuery.h"
-#include "../model/hedera/Transaction.h"
-#include "../model/hedera/Response.h"
-#include "../model/hedera/TransactionResponse.h"
-#include "../tasks/HederaTask.h"
-
-enum HederaRequestReturn
-{
- HEDERA_REQUEST_RETURN_OK,
- HEDERA_REQUEST_RETURN_PARSE_ERROR,
- HEDERA_REQUEST_PRECHECK_ERROR,
- HEDERA_REQUEST_RETURN_ERROR,
- HEDERA_REQUEST_UNKNOWN_TRANSACTION,
- HEDERA_REQUEST_UNKNOWN_QUERY,
- HEDERA_REQUEST_CONNECT_ERROR
-};
-
-// NodeServerConnection
-class HederaRequest : public NotificationList
-{
-public:
- HederaRequest();
- ~HederaRequest();
-
- HederaRequestReturn request(model::hedera::Query* query, model::hedera::Response* response, Poco::UInt64 fee = 0);
- HederaRequestReturn request(model::hedera::Transaction* transaction, model::hedera::Response* response);
- //!
- //! \param task goes into HederaTaskManager and will be run after transaction
- HederaRequestReturn request(model::hedera::Transaction* transaction, HederaTask* task);
- //! for testing, didn't work server say invalid json :/
- HederaRequestReturn requestViaPHPRelay(model::hedera::Query* query);
-
-protected:
-
-};
-
-
-#endif //__GRADIDO_LOGIN_SERVER_LIB_HEDERA_REQUEST_
-//
\ No newline at end of file
diff --git a/login_server/src/cpp/controller/HederaTopic.cpp b/login_server/src/cpp/controller/HederaTopic.cpp
deleted file mode 100644
index 36793a732..000000000
--- a/login_server/src/cpp/controller/HederaTopic.cpp
+++ /dev/null
@@ -1,235 +0,0 @@
-#include "HederaTopic.h"
-//#include "../model/hedera/Transaction.h"
-#include "HederaRequest.h"
-#include "../lib/Success.h"
-
-#include "../model/hedera/ConsensusCreateTopic.h"
-#include "../model/hedera/Transaction.h"
-
-#include "../SingletonManager/PendingTasksManager.h"
-
-namespace controller {
- HederaTopic::HederaTopic(model::table::HederaTopic* dbModel)
- {
- mDBModel = dbModel;
- }
- HederaTopic::~HederaTopic()
- {
-
- }
-
- Poco::AutoPtr HederaTopic::create(const std::string& name, int autoRenewAccountId, int autoRenewPeriod, int groupId)
- {
- auto db = new model::table::HederaTopic(name, autoRenewAccountId, autoRenewPeriod, groupId);
-
- auto hedera_topic = new HederaTopic(db);
- return Poco::AutoPtr(hedera_topic);
- }
-
- std::vector> HederaTopic::listAll()
- {
- auto db = new model::table::HederaTopic();
- std::vector topic_list;
- // throw an unresolved external symbol error
- topic_list = db->loadAllFromDB();
-
- std::vector> resultVector;
-
- resultVector.reserve(topic_list.size());
- for (auto it = topic_list.begin(); it != topic_list.end(); it++) {
- Poco::AutoPtr topic_ptr(new HederaTopic(new model::table::HederaTopic(*it)));
- resultVector.push_back(topic_ptr);
- }
-
- return resultVector;
- }
-
- Poco::AutoPtr HederaTopic::load(int id)
- {
- auto db = new model::table::HederaTopic;
- if (1 == db->loadFromDB("id", id)) {
- return new HederaTopic(db);
- }
- return nullptr;
- }
-
- Poco::AutoPtr HederaTopic::getTopicHederaId()
- {
- if (mTopicHederaId.isNull()) {
- mTopicHederaId = HederaId::load(getModel()->getTopicHederaId());
- }
- return mTopicHederaId;
- }
-
- Poco::AutoPtr HederaTopic::getAutoRenewAccount()
- {
- if (mAutoRenewAccount.isNull()) {
- mAutoRenewAccount = HederaAccount::load(getModel()->getAutoRenewAccountId());
- }
- return mAutoRenewAccount;
- }
-
- bool HederaTopic::getTopicInfosFromHedera(Poco::AutoPtr topicHederaId, Poco::AutoPtr user, model::hedera::Response& response)
- {
- auto payer_account = controller::HederaAccount::pick(ServerConfig::g_HederaNetworkType);
- auto node_server = NodeServer::pick(payer_account->getModel()->getNetworkType(), getModel()->getGroupId());
-
- if (topicHederaId.isNull()) {
- addError(new Error("Hedera Topic", "no hedera topic id exist"));
- return false;
- }
- auto query = model::hedera::Query::getTopicInfo(topicHederaId, payer_account->getHederaId(), node_server);
- query->setResponseType(proto::COST_ANSWER);
- HederaRequest request;
- query->sign(payer_account->getCryptoKey()->getKeyPair(user));
- if (HEDERA_REQUEST_RETURN_OK == request.request(query, &response)) {
- auto queryCost = response.getQueryCost();
- printf("query cost: %d\n", queryCost);
-
- query->setTransactionFee(queryCost);
- query->setResponseType(proto::ANSWER_ONLY);
- query->sign(payer_account->getCryptoKey()->getKeyPair(user));
-
-
- if (HEDERA_REQUEST_RETURN_OK == request.request(query, &response)) {
- return true;
- }
- else {
- addError(new Error("Hedera Query", "Error by query for consensus get topic info"));
- }
-
- }
- else {
- addError(new Error("Hedera Query", "Error by getting costs for consensus get topic info"));
- }
- getErrors(&request);
- return false;
-
- }
-
- bool HederaTopic::updateWithGetTopicInfos(Poco::AutoPtr user)
- {
-
- model::hedera::Response response;
- if (!getTopicInfosFromHedera(getTopicHederaId(), user, response)) {
- return false;
- }
-
- auto consensus_topic_info = response.getConsensusTopicInfo();
- //addNotification(new ParamSuccess("consensus get topic info", "memo: ", consensus_topic_info->getMemo()));
- //addNotification(new ParamSuccess("consensus get topic info", "string: ", consensus_topic_info->toStringHtml()));
- auto model = getModel();
- model->setAutoRenewPeriod(consensus_topic_info->getAutoRenewPeriod().seconds());
- model->setCurrentTimeout(consensus_topic_info->getExpirationTime());
- model->setSequeceNumber(consensus_topic_info->getSequenceNumber());
-
-
- std::string fieldNames[] = { "auto_renew_period", "current_timeout", "sequence_number" };
- if (model->updateIntoDB(
- fieldNames,
- model->getAutoRenewPeriod(),
- model->getCurrentTimeout(),
- model->getSequenceNumber()
- ) > 1) {
- addError(new Error("DB", "error saving changes in DB"));
- getErrors(model);
- return false;
- }
- return true;
-
- }
-
- Poco::AutoPtr HederaTopic::loadFromHedera(Poco::AutoPtr hederaId, Poco::UInt32 groupId, Poco::AutoPtr user)
- {
- auto db = new model::table::HederaTopic();
- auto hedera_topic = new HederaTopic(db);
-
- model::hedera::Response response;
- if (!hedera_topic->getTopicInfosFromHedera(hederaId, user, response)) {
- delete hedera_topic;
- return nullptr;
- }
-
- auto consensus_topic_info = response.getConsensusTopicInfo();
- //addNotification(new ParamSuccess("consensus get topic info", "memo: ", consensus_topic_info->getMemo()));
- //addNotification(new ParamSuccess("consensus get topic info", "string: ", consensus_topic_info->toStringHtml()));
- auto group_name = consensus_topic_info->getMemo();
- auto groups = controller::Group::load(group_name);
- db->setTopicHederaID(hederaId->getModel()->getID());
- db->setName(group_name);
- if (1 == groups.size()) {
- db->setGroupId(groups[0]->getModel()->getID());
- }
- else if (groupId > 0) {
- db->setGroupId(groupId);
- }
- db->setAutoRenewPeriod(consensus_topic_info->getAutoRenewPeriod().seconds());
- db->setCurrentTimeout(consensus_topic_info->getExpirationTime());
- db->setSequeceNumber(consensus_topic_info->getSequenceNumber());
-
- return Poco::AutoPtr(hedera_topic);
- }
-
- Poco::AutoPtr HederaTopic::createTopic(Poco::AutoPtr operatorAccount, Poco::AutoPtr user)
- {
- static const char* function_name = "HederaTopic::createTopic";
- printf("[HederaTopic::createTopic]\n");
- auto model = getModel();
- if (!model->getID()) {
- addError(new Error(function_name, "no db entry for topic created, id is missing"));
- return nullptr;
- }
- Poco::AutoPtr autoRenewAccountId(nullptr);
- if (model->getAutoRenewAccountId()) {
- //autoRenewAccountId = controller::HederaId::load(model->getAutoRenewAccountId());
- }
- model::hedera::ConsensusCreateTopic hederaCreateTopic(autoRenewAccountId, model->getAutoRenewPeriod());
- auto hederaTransactionBody = operatorAccount->createTransactionBody();
- if (model->getName() != "") {
- hederaCreateTopic.setMemo(model->getName());
- }
- if (!hederaTransactionBody->setCreateTopic(hederaCreateTopic)) {
- addError(new Error(function_name, "error validating create topic transaction"));
- return nullptr;
- }
- model::hedera::Transaction hederaTransaction;
- if (!hederaTransaction.sign(operatorAccount->getCryptoKey()->getKeyPair(user), std::move(hederaTransactionBody))) {
- addError(new Error(function_name, "error signing hedera transaction"));
- return nullptr;
- }
-
- auto proto_transaction = hederaTransaction.getTransaction();
-
-
- Poco::AutoPtr receiptTask(new HederaTask(&hederaTransaction));
- auto receipt_task_model = receiptTask->getModel();
- receipt_task_model->setParentPendingTaskId(model->getID());
- receipt_task_model->setUserId(user->getModel()->getID());
-
- HederaRequest request;
- printf("[HederaTopic::createTopic] before calling request\n");
- auto result = request.request(&hederaTransaction, receiptTask.get());
- if (HEDERA_REQUEST_RETURN_OK == result) {
- if (proto::OK == receiptTask->getTransactionResponse()->getPrecheckCode()) {
- auto pt = PendingTasksManager::getInstance();
- printf("[HederaTopic::createTopic] before add task\n");
- pt->addTask(receiptTask);
- printf("[HederaTopic::createTopic] before start timer\n");
- receiptTask->startTimer();
- return receiptTask;
- }
- else {
- addError(new ParamError(function_name, "precheck code error", receiptTask->getTransactionResponse()->getPrecheckCodeString()));
-
- return nullptr;
- }
- }
- else {
- addError(new Error(function_name, "error in hedera request"));
- return nullptr;
- }
-
- }
-
-
-}
\ No newline at end of file
diff --git a/login_server/src/cpp/controller/HederaTopic.h b/login_server/src/cpp/controller/HederaTopic.h
deleted file mode 100644
index 2808794ee..000000000
--- a/login_server/src/cpp/controller/HederaTopic.h
+++ /dev/null
@@ -1,58 +0,0 @@
-#ifndef __GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_TOPIC_H
-#define __GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_TOPIC_H
-
-/*!
-*
-* \author: Dario Rekowski
-*
-* \date: 03.09.2020
-*
-* \brief: Class for Hedera Topic, connct db table with hedera object
-*
-*/
-#include "TableControllerBase.h"
-#include "../model/table/HederaTopic.h"
-#include "../model/hedera/Response.h"
-#include "HederaId.h"
-#include "HederaAccount.h"
-
-#include "../tasks/HederaTask.h"
-
-namespace controller {
- class HederaTopic : public TableControllerBase, public NotificationList
- {
- public:
-
- ~HederaTopic();
-
- static Poco::AutoPtr create(const std::string& name, int autoRenewAccountId, int autoRenewPeriod, int groupId);
- static Poco::AutoPtr loadFromHedera(Poco::AutoPtr hederaId, Poco::UInt32 groupId, Poco::AutoPtr user);
- static std::vector> listAll();
- static Poco::AutoPtr load(int id);
-
-
- bool updateWithGetTopicInfos(Poco::AutoPtr user);
-
-
- inline bool deleteFromDB() { return mDBModel->deleteFromDB(); }
- Poco::AutoPtr getTopicHederaId();
- Poco::AutoPtr getAutoRenewAccount();
-
- //! \brief hedera call to create a hedera topic
- Poco::AutoPtr createTopic(Poco::AutoPtr operatorAccount, Poco::AutoPtr user);
-
- inline Poco::AutoPtr getModel() { return _getModel(); }
-
-
- protected:
- HederaTopic(model::table::HederaTopic* dbModel);
-
- bool getTopicInfosFromHedera(Poco::AutoPtr topicHederaId, Poco::AutoPtr user, model::hedera::Response& response);
-
- Poco::AutoPtr mTopicHederaId;
- Poco::AutoPtr mAutoRenewAccount;
-
- };
-}
-
-#endif //__GRADIDO_LOGIN_SERVER_CONTROLLER_HEDERA_TOPIC_H
diff --git a/login_server/src/cpp/controller/NodeServer.cpp b/login_server/src/cpp/controller/NodeServer.cpp
deleted file mode 100644
index 9ae570e66..000000000
--- a/login_server/src/cpp/controller/NodeServer.cpp
+++ /dev/null
@@ -1,208 +0,0 @@
-#include "NodeServer.h"
-#include "../SingletonManager/ErrorManager.h"
-#include "../SingletonManager/ConnectionManager.h"
-#include "../SingletonManager/CronManager.h"
-#include "Poco/RegularExpression.h"
-
-namespace controller {
-
- Poco::RegularExpression g_filterHttp("^https?://");
-
- std::string NodeServerConnection::getUriWithPort() const
- {
- std::string protocol;
- g_filterHttp.extract(url, protocol);
- return url.substr(protocol.size()) + ":" + std::to_string(port);
- }
-
- std::string NodeServerConnection::getUri() const
- {
- std::string protocol;
- g_filterHttp.extract(url, protocol);
- return url.substr(protocol.size());
- }
-
-
-
-
- NodeServer::NodeServer(model::table::NodeServer* dbModel)
- {
- mDBModel = dbModel;
- if (model::table::NODE_SERVER_GRADIDO_COMMUNITY == dbModel->getNodeServerType()) {
- CronManager::getInstance()->addNodeServerToPing(Poco::AutoPtr(this, true));
- }
- }
-
- NodeServer::~NodeServer()
- {
-
- }
-
- bool NodeServer::deleteFromDB()
- {
- auto result = mDBModel->deleteFromDB();
- if (result && model::table::NODE_SERVER_GRADIDO_COMMUNITY == getModel()->getNodeServerType()) {
- CronManager::getInstance()->removeNodeServerToPing(Poco::AutoPtr(this, true));
- }
- return result;
- }
-
- Poco::AutoPtr NodeServer::create(const std::string& url, int port, int groupId, model::table::NodeServerType type, int nodeHederaId)
- {
- auto db = new model::table::NodeServer(url, port, groupId, type, nodeHederaId);
- auto group = new NodeServer(db);
- return Poco::AutoPtr(group);
- }
-
- Poco::AutoPtr NodeServer::load(int id)
- {
- auto db = new model::table::NodeServer();
- if (1 == db->loadFromDB("id", id)) {
- return new NodeServer(db);
- }
- return nullptr;
- }
-
- std::vector> NodeServer::load(model::table::NodeServerType type, int group_id/* = 0*/)
- {
- auto db = new model::table::NodeServer();
- std::vector node_server_list;
-
- if (type == model::table::NODE_SERVER_HEDERA_MAINNET_NODE || type == model::table::NODE_SERVER_HEDERA_TESTNET_NODE)
- {
- node_server_list = db->loadFromDB("server_type", type, 4);
- }
- else if (type == model::table::NODE_SERVER_GRADIDO_NODE || type == model::table::NODE_SERVER_GRADIDO_COMMUNITY)
- {
- if (group_id)
- {
- node_server_list = db->loadFromDB(
- { "server_type", "group_id" },
- { type, group_id },
- model::table::MYSQL_CONDITION_AND
- );
- }
- else
- {
- node_server_list = db->loadFromDB("server_type", type, 4);
- }
- }
- //auto node_server_list = db->loadFromDB("alias", alias, 0);
-
- std::vector> resultVector;
- resultVector.reserve(node_server_list.size());
- for (auto it = node_server_list.begin(); it != node_server_list.end(); it++) {
- resultVector.push_back(new NodeServer(new model::table::NodeServer(*it)));
- }
- return resultVector;
- }
-
- /*
- SELECT * FROM table_name
- ORDER BY RAND()
- LIMIT 1;
- */
- NodeServerConnection NodeServer::pick(ServerConfig::HederaNetworkType type, int group_id /*= 0*/)
- {
- model::table::NodeServerType node_server_type = model::table::NODE_SERVER_NONE;
- if (ServerConfig::HEDERA_MAINNET) node_server_type = model::table::NODE_SERVER_HEDERA_MAINNET_NODE;
- else if (ServerConfig::HEDERA_TESTNET) node_server_type = model::table::NODE_SERVER_HEDERA_TESTNET_NODE;
- return pick(node_server_type, group_id);
- }
- NodeServerConnection NodeServer::pick(model::table::NodeServerType type, int group_id/* = 0*/)
- {
- auto cm = ConnectionManager::getInstance();
- auto session = cm->getConnection(CONNECTION_MYSQL_LOGIN_SERVER);
- NodeServerConnection result;
- int hedera_node_id = 0;
-
- Poco::Data::Statement select(session);
- select << "SELECT url, port";
-
- if (model::table::NodeServerIsHederaNode(type)) {
- select << ", node_hedera_id";
- }
- select << " from node_servers where server_type = ? ORDER BY RAND() LIMIT 1"
- , Poco::Data::Keywords::into(result.url)
- , Poco::Data::Keywords::into(result.port);
- if (model::table::NodeServerIsHederaNode(type)) {
- select, Poco::Data::Keywords::into(hedera_node_id);
- }
- select , Poco::Data::Keywords::bind((int)type);
- try {
- if (1 == select.execute()) {
- if (model::table::NodeServerIsHederaNode(type)) {
- result.hederaId = controller::HederaId::load(hedera_node_id);
- }
- return result;
- }
- }
- catch (Poco::Exception& ex) {
- auto em = ErrorManager::getInstance();
- const char* functionName = "NodeServer::pick";
- em->addError(new ParamError(functionName, "mysql error by pick: ", ex.message()));
- em->addError(new ParamError(functionName, "server type: ", model::table::NodeServer::nodeServerTypeToString(type)));
- em->addError(new ParamError(functionName, "group id", group_id));
- em->sendErrorsAsEmail();
- }
- return result;
-
- }
-
- std::vector> NodeServer::listAll()
- {
- auto cm = ConnectionManager::getInstance();
- auto session = cm->getConnection(CONNECTION_MYSQL_LOGIN_SERVER);
- Poco::Data::Statement select(session);
- std::vector rows;
- // typedef Poco::Tuple NodeServerFullTuple;
- select << "SELECT n.id, n.url, n.port, n.group_id, n.server_type, n.node_hedera_id, h.shardNum, h.realmNum, h.num, n.last_live_sign "
- << "FROM node_servers as n "
- << "LEFT JOIN hedera_ids as h ON h.id = n.node_hedera_id"
- , Poco::Data::Keywords::into(rows);
-
- try {
- select.executeAsync();
- select.wait();
- }
- catch (Poco::Exception& ex) {
- auto em = ErrorManager::getInstance();
- const char* functionName = "NodeServer::listAll";
- em->addError(new ParamError(functionName, "mysql error by list all: ", ex.message()));
- em->sendErrorsAsEmail();
- }
- std::vector> results;
- for (auto it = rows.begin(); it != rows.end(); it++) {
- //NodeServer(const std::string& url, int port, int groupId, NodeServerType type, int nodeHederaId);
- auto row = *it;
- model::table::NodeServer* db = new model::table::NodeServer(
- row.get<1>(), row.get<2>(), row.get<3>(), (model::table::NodeServerType)row.get<4>(), row.get<5>()
- );
- db->setLastLiveSign(row.get<9>());
- db->setID(row.get<0>());
- Poco::AutoPtr node_server(new NodeServer(db));
- node_server->setHederaId(controller::HederaId::create(
- row.get<6>(), row.get<7>(), row.get<8>()
- ));
- results.push_back(node_server);
-
- }
- return results;
-
- }
-
- JsonRequest NodeServer::createJsonRequest()
- {
- auto model = getModel();
- NodeServerConnection connection(model->getUrl(), model->getPort());
- return JsonRequest(connection.getUri(), model->getPort());
- }
-
- std::string NodeServer::getBaseUri()
- {
- auto model = getModel();
- NodeServerConnection connection(model->getUrl(), model->getPort());
- return connection.getUri();
- }
-
-}
\ No newline at end of file
diff --git a/login_server/src/cpp/controller/NodeServer.h b/login_server/src/cpp/controller/NodeServer.h
deleted file mode 100644
index d91cc3612..000000000
--- a/login_server/src/cpp/controller/NodeServer.h
+++ /dev/null
@@ -1,66 +0,0 @@
-#ifndef GRADIDO_LOGIN_SERVER_CONTROLLER_NODE_SERVER_INCLUDE
-#define GRADIDO_LOGIN_SERVER_CONTROLLER_NODE_SERVER_INCLUDE
-
-#include "../model/table/NodeServer.h"
-#include "../controller/HederaId.h"
-#include "../lib/JsonRequest.h"
-
-#include "Poco/SharedPtr.h"
-
-#include "TableControllerBase.h"
-
-namespace controller {
-
- struct NodeServerConnection
- {
- NodeServerConnection(const std::string& _url, int _port) : url(_url), port(_port) {}
- NodeServerConnection() :port(0) {};
-
- // with http:// or https://
- inline std::string getUrlWithPort() const { return url + ":" + std::to_string(port); }
-
- // without http:// or https://
- std::string getUriWithPort() const;
- std::string getUri() const;
-
- bool isValid() { return url != "" && port; }
- std::string url;
- int port;
-
- Poco::AutoPtr hederaId;
- };
-
- typedef Poco::Tuple NodeServerFullTuple;
-
- class NodeServer : public TableControllerBase
- {
- public:
-
- ~NodeServer();
-
- static Poco::AutoPtr create(const std::string& url, int port, int groupId, model::table::NodeServerType type, int nodeHederaId);
-
- //! \param group_id is zero take everyone
- static std::vector> load(model::table::NodeServerType type, int group_id = 0);
- static Poco::AutoPtr load(int id);
- static std::vector> listAll();
- // pick server randomly
- static NodeServerConnection pick(ServerConfig::HederaNetworkType type, int group_id = 0);
- static NodeServerConnection pick(model::table::NodeServerType type, int group_id = 0);
- bool deleteFromDB();
-
- inline Poco::AutoPtr getModel() { return _getModel(); }
-
- inline void setHederaId(Poco::AutoPtr hederaId) { mHederaID = hederaId; }
- inline Poco::AutoPtr getHederaId() { return mHederaID; }
-
- std::string getBaseUri();
- JsonRequest createJsonRequest();
- protected:
- NodeServer(model::table::NodeServer* dbModel);
- Poco::AutoPtr mHederaID;
-
- };
-}
-
-#endif //GRADIDO_LOGIN_SERVER_CONTROLLER_NODE_SERVER_INCLUDE
\ No newline at end of file
diff --git a/login_server/src/cpp/controller/PendingTask.cpp b/login_server/src/cpp/controller/PendingTask.cpp
index c759803c0..ad158b581 100644
--- a/login_server/src/cpp/controller/PendingTask.cpp
+++ b/login_server/src/cpp/controller/PendingTask.cpp
@@ -1,7 +1,6 @@
#include "PendingTask.h"
#include "../model/gradido/Transaction.h"
-#include "../tasks/HederaTask.h"
#include "../SingletonManager/PendingTasksManager.h"
#include "../SingletonManager/ErrorManager.h"
@@ -37,7 +36,7 @@ namespace controller {
resultVector.push_back(loadCorrectDerivedClass(new model::table::PendingTask(*it)));
}
return resultVector;
-
+
}
@@ -57,9 +56,7 @@ namespace controller {
if (dbModel->isGradidoTransaction()) {
return model::gradido::Transaction::load(dbModel);
}
- else if (dbModel->isGradidoTransaction()) {
- return HederaTask::load(dbModel);
- }
+
return nullptr;
}
@@ -70,7 +67,7 @@ namespace controller {
// throw an unresolved external symbol error
task_list = db->loadAllFromDB();
-
+
//*/ //work around end
std::vector> resultVector;
@@ -85,7 +82,7 @@ namespace controller {
bool PendingTask::deleteFromDB()
{
Poco::ScopedLock _lock(mWorkMutex);
- auto result = mDBModel->deleteFromDB();
+ auto result = mDBModel->deleteFromDB();
return result;
}
@@ -109,7 +106,7 @@ namespace controller {
Poco::ScopedLock _lock(mWorkMutex);
static const char* function_name = "PendingTask::startTimer";
auto em = ErrorManager::getInstance();
-
+
if (isTimeoutTask()) {
auto next_run_time = getNextRunTime();
if (next_run_time >= Poco::DateTime()) {
@@ -136,7 +133,7 @@ namespace controller {
Poco::TimerCallback callback(*this, &PendingTask::calledFromTimer);
mTimer.start(callback);
}
-
+
}
void PendingTask::calledFromTimer(Poco::Timer& timer)
{
@@ -205,4 +202,4 @@ namespace controller {
}
return -1;
}
-}
\ No newline at end of file
+}
diff --git a/login_server/src/cpp/controller/User.cpp b/login_server/src/cpp/controller/User.cpp
index 7eeeef642..cd71da96b 100644
--- a/login_server/src/cpp/controller/User.cpp
+++ b/login_server/src/cpp/controller/User.cpp
@@ -7,7 +7,6 @@
#include "../SingletonManager/ErrorManager.h"
#include "../SingletonManager/SingletonTaskObserver.h"
-#include "NodeServer.h"
#include "Group.h"
#include "../lib/DataTypeConverter.h"
@@ -24,7 +23,7 @@ namespace controller {
: mPassword(nullptr), mGradidoKeyPair(nullptr), mCanDecryptPrivateKey(false), mGradidoCurrentBalance(0)
{
mDBModel = dbModel;
-
+
}
User::~User()
@@ -49,20 +48,20 @@ namespace controller {
auto user = new User(db);
return Poco::AutoPtr(user);
}
-
+
std::vector User::search(const std::string& searchString, const std::string& accountState /* = "all" */)
{
-
+
auto sm = SessionManager::getInstance();
auto cm = ConnectionManager::getInstance();
auto db = new model::table::User();
static const char* functionName = "User::search";
-
+
std::string globalSearch = "%" + searchString + "%";
std::vector resultFromDB;
if (accountState == "email not activated") {
-
+
std::vector fieldNames = { "first_name", "last_name", "email", "email_checked" };
auto session = cm->getConnection(CONNECTION_MYSQL_LOGIN_SERVER);
std::vector results;
@@ -106,6 +105,12 @@ namespace controller {
}
+ bool User::isUsernameAlreadyUsed(const std::string& username)
+ {
+ auto db = getModel();
+ return db->loadFromDB({ "username", "group_id" }, username, db->getGroupId(), model::table::MYSQL_CONDITION_AND) > 0;
+ }
+
int User::load(const unsigned char* pubkey_array)
{
Poco::Data::BLOB pubkey(pubkey_array, 32);
@@ -117,6 +122,14 @@ namespace controller {
Poco::Data::BLOB email_hash(*emailHash, crypto_generichash_BYTES);
return getModel()->loadFromDB("email_hash", email_hash);
}
+ size_t User::load(const std::string& emailOrUsername)
+ {
+ auto model = getModel();
+ if (1 == model->loadFromDB("email", emailOrUsername)) {
+ return 1;
+ }
+ return model->loadFromDB("username", emailOrUsername);
+ }
Poco::AutoPtr User::sload(int user_id)
{
auto db = new model::table::User();
@@ -127,7 +140,7 @@ namespace controller {
auto user = new User(db);
return Poco::AutoPtr(user);
}
-
+
void User::reload()
{
getModel()->loadFromDB("id", getModel()->getID());
@@ -147,15 +160,15 @@ namespace controller {
auto pubkey = getModel()->getPublicKey();
- if (pubkey)
+ if (pubkey)
{
auto pubkeyHex = mm->getFreeMemory(65);
memset(*pubkeyHex, 0, 65);
sodium_bin2hex(*pubkeyHex, 65, pubkey, 32);
mPublicHex = (char*)*pubkeyHex;
- mm->releaseMemory(pubkeyHex);
+ mm->releaseMemory(pubkeyHex);
}
-
+
unlock();
return mPublicHex;
}
@@ -185,7 +198,7 @@ namespace controller {
return 2;
}
auto observer = SingletonTaskObserver::getInstance();
-
+
std::unique_lock _lock(mSharedMutex);
assert(mPassword.isNull());
@@ -201,7 +214,7 @@ namespace controller {
observer->removeTask(email_hash, TASK_OBSERVER_PASSWORD_CREATION);
- if (authenticated_encryption->getKeyHashed() == model->getPasswordHashed())
+ if (authenticated_encryption->getKeyHashed() == model->getPasswordHashed())
{
// printf("[User::login] password key hashed is the same as saved password hash\n");
MemoryBin* clear_private_key = nullptr;
@@ -212,7 +225,7 @@ namespace controller {
if (!model->hasPrivateKeyEncrypted()) {
return 1;
}
- else
+ else
{
if (SecretKeyCryptography::AUTH_DECRYPT_OK == authenticated_encryption->decrypt(model->getPrivateKeyEncrypted(), &clear_private_key)) {
if (mGradidoKeyPair) {
@@ -247,7 +260,7 @@ namespace controller {
}
}
-
+
// password didn't match
//printf("password hashed key: %ull, model pwd hashed keys: %ull\n", authenticated_encryption->getKeyHashed(), model->getPasswordHashed());
//printf("password: %d\n", (int)(mPassword.get()));
@@ -285,12 +298,12 @@ namespace controller {
}
- int User::setNewPassword(Poco::AutoPtr passwd)
+ int User::setNewPassword(Poco::AutoPtr passwd)
{
std::unique_lock _lock(mSharedMutex);
auto model = getModel();
- if (!mPassword.isNull() && !passwd.isNull())
+ if (!mPassword.isNull() && !passwd.isNull())
{
// if keys matched
if (mPassword->isTheSame(passwd)) {
@@ -301,16 +314,16 @@ namespace controller {
//if (!mGradidoKeyPair) mGradidoKeyPair = new KeyPairEd25519;
MemoryBin* clear_private_key = nullptr;
if (SecretKeyCryptography::AUTH_DECRYPT_OK == mPassword->decrypt(model->getPrivateKeyEncrypted(), &clear_private_key)) {
- if (mGradidoKeyPair && mGradidoKeyPair->isTheSame(clear_private_key) != 0)
+ if (mGradidoKeyPair && mGradidoKeyPair->isTheSame(clear_private_key) != 0)
{
- delete mGradidoKeyPair;
+ delete mGradidoKeyPair;
mGradidoKeyPair = nullptr;
}
- if (!mGradidoKeyPair)
+ if (!mGradidoKeyPair)
{
mGradidoKeyPair = new KeyPairEd25519(clear_private_key);
}
-
+
// check if saved pubkey and from private key extracted pubkey match
if (*mGradidoKeyPair != model->getPublicKey()) {
delete mGradidoKeyPair;
@@ -358,7 +371,7 @@ namespace controller {
continue;
}
auto key_pair = user_backup->createGradidoKeyPair();
-
+
if (key_pair->isTheSame(user_model->getPublicKey())) {
if (createdKeyPair) {
*createdKeyPair = key_pair;
@@ -425,7 +438,7 @@ namespace controller {
<< "LEFT JOIN email_opt_in as v ON(u.id = v.user_id) "
<< "where u.email_checked = ? "
<< "AND v.resend_count <= ? "
- << "ORDER BY u.id, v.created " ,
+ << "ORDER BY u.id, v.created " ,
Poco::Data::Keywords::use(email_checked), Poco::Data::Keywords::use(resend_count), Poco::Data::Keywords::into(results)
;
int result_count = 0;
@@ -499,7 +512,7 @@ namespace controller {
auto session = cm->getConnection(CONNECTION_MYSQL_LOGIN_SERVER);
Poco::Data::Statement select(session);
std::vector> results;
-
+
select << "select id, email from users "
<< "where email_hash IS NULL "
, Poco::Data::Keywords::into(results)
@@ -553,42 +566,25 @@ namespace controller {
printf("[%s] return saved group base Url: %s\n", function_name, mGroupBaseUrl.data());
return mGroupBaseUrl;
}
-
+
auto model = getModel();
if (!model->getGroupId()) {
printf("[%s] return ServerConfig::g_php_serverPath because no group id\n", function_name);
return ServerConfig::g_php_serverPath;
}
- auto servers = controller::NodeServer::load(model::table::NODE_SERVER_GRADIDO_COMMUNITY, model->getGroupId());
- if (!servers.size()) {
- auto group = controller::Group::load(model->getGroupId());
- if (!group.isNull()) {
- auto group_model = group->getModel();
- if (ServerConfig::g_ServerSetupType == ServerConfig::SERVER_TYPE_TEST) {
- mGroupBaseUrl = "http://" + group_model->getUrl() + group_model->getHome();
- }
- else {
- mGroupBaseUrl = "https://" + group_model->getUrl() + group_model->getHome();
- }
- printf("[%s] return group base Url: %s from Group\n", function_name, mGroupBaseUrl.data());
- return mGroupBaseUrl;
- }
- return ServerConfig::g_php_serverPath;
- }
- if (servers.size() > 1) {
- auto em = ErrorManager::getInstance();
- em->addError(new ParamError(function_name, "error, more than one community server found for group", model->getGroupId()));
- em->sendErrorsAsEmail();
- return ServerConfig::g_php_serverPath;
- }
- if (ServerConfig::g_ServerSetupType == ServerConfig::SERVER_TYPE_TEST) {
- mGroupBaseUrl = "http://" + servers[0]->getBaseUri();
- }
- else {
- mGroupBaseUrl = "https://" + servers[0]->getBaseUri();
- }
- printf("[%s] return group base Url: %s from NodeServer\n", function_name, mGroupBaseUrl.data());
- return mGroupBaseUrl;
+ auto group = controller::Group::load(model->getGroupId());
+ if (!group.isNull()) {
+ auto group_model = group->getModel();
+ if (ServerConfig::g_ServerSetupType == ServerConfig::SERVER_TYPE_TEST) {
+ mGroupBaseUrl = "http://" + group_model->getUrl() + group_model->getHome();
+ }
+ else {
+ mGroupBaseUrl = "https://" + group_model->getUrl() + group_model->getHome();
+ }
+ printf("[%s] return group base Url: %s from Group\n", function_name, mGroupBaseUrl.data());
+ return mGroupBaseUrl;
+ }
+ return ServerConfig::g_php_serverPath;
}
Poco::AutoPtr User::getGroup()
diff --git a/login_server/src/cpp/controller/User.h b/login_server/src/cpp/controller/User.h
index 649fc1742..ecbac086f 100644
--- a/login_server/src/cpp/controller/User.h
+++ b/login_server/src/cpp/controller/User.h
@@ -47,6 +47,8 @@ namespace controller {
static std::vector search(const std::string& searchString, const std::string& accountState = "all");
+ bool isUsernameAlreadyUsed(const std::string& username);
+
//! \brief go through whole db and search users with email_checked = false and schedule resend 7 days after email_opt_in created date
//!
//! Should be only called by server start, later it aren't necessary, because register function schedule resend tasks by himself.
@@ -68,7 +70,7 @@ namespace controller {
//! \return 0 matching entry found
int tryLoadPassphraseUserBackup(KeyPairEd25519** createdKeyPair = nullptr);
- inline size_t load(const std::string& email) { return getModel()->loadFromDB("email", email); }
+ size_t load(const std::string& emailOrUsername);
//! \brief try to load user from db via user_id
//! \return count of found rows, should be 1 or 0
inline size_t load(int user_id) { return getModel()->loadFromDB("id", user_id); }
diff --git a/login_server/src/cpp/lib/DataTypeConverter.cpp b/login_server/src/cpp/lib/DataTypeConverter.cpp
index f99100a2e..523a6ee74 100644
--- a/login_server/src/cpp/lib/DataTypeConverter.cpp
+++ b/login_server/src/cpp/lib/DataTypeConverter.cpp
@@ -19,17 +19,17 @@ namespace DataTypeConverter
result = stoi(input);
return NUMBER_PARSE_OKAY;
}
- catch (const std::invalid_argument& ia)
+ catch (const std::invalid_argument& ia)
{
printf("[strToInt] exception: invalid argument: %s\n", ia.what());
return NUMBER_PARSE_INVALID_ARGUMENT;
}
- catch (const std::out_of_range& oor)
+ catch (const std::out_of_range& oor)
{
printf("[strToInt] exception: out or range: %s\n", oor.what());
return NUMBER_PARSE_OUT_OF_RANGE;
}
- catch (const std::logic_error & ler)
+ catch (const std::logic_error & ler)
{
printf("[strToInt] exception: logical error: %s\n", ler.what());
return NUMBER_PARSE_LOGIC_ERROR;
@@ -198,13 +198,13 @@ namespace DataTypeConverter
return bin;
}
-
+
std::string binToBase64(const unsigned char* data, size_t size, int variant /*= sodium_base64_VARIANT_ORIGINAL*/)
{
auto mm = MemoryManager::getInstance();
-
+
size_t encodedSize = sodium_base64_encoded_len(size, variant);
auto base64 = mm->getFreeMemory(encodedSize);
memset(*base64, 0, encodedSize);
@@ -295,12 +295,6 @@ namespace DataTypeConverter
return result;
}
- Poco::Timestamp convertFromProtoTimestamp(const proto::Timestamp& timestamp)
- {
- // microseconds
- google::protobuf::int64 microseconds = timestamp.seconds() * (google::protobuf::int64)10e5 + (google::protobuf::int64)(timestamp.nanos()) / (google::protobuf::int64)10e2;
- return microseconds;
- }
Poco::Timestamp convertFromProtoTimestamp(const proto::gradido::Timestamp& timestamp)
{
@@ -309,13 +303,6 @@ namespace DataTypeConverter
return microseconds;
}
- void convertToProtoTimestamp(const Poco::Timestamp pocoTimestamp, proto::Timestamp* protoTimestamp)
- {
- auto microsecondsTotal = pocoTimestamp.epochMicroseconds();
- auto secondsTotal = pocoTimestamp.epochTime();
- protoTimestamp->set_seconds(secondsTotal);
- protoTimestamp->set_nanos((microsecondsTotal - secondsTotal * pocoTimestamp.resolution()) * 1000);
- }
void convertToProtoTimestamp(const Poco::Timestamp pocoTimestamp, proto::gradido::Timestamp* protoTimestamp)
{
@@ -333,11 +320,6 @@ namespace DataTypeConverter
}
- Poco::Timespan convertFromProtoDuration(const proto::Duration& duration)
- {
- return Poco::Timespan(duration.seconds(), 0);
- }
-
int replaceBase64WithHex(Poco::JSON::Object::Ptr json)
{
//g_rexExpBase64
@@ -356,7 +338,7 @@ namespace DataTypeConverter
count_replacements += replaceBase64WithHex(local_json);
json->set(it->first, local_json);
}
- else if (it->second.isString())
+ else if (it->second.isString())
{
if (it->first == "amount") continue;
auto field_value = it->second.extract();
@@ -383,7 +365,7 @@ namespace DataTypeConverter
for (Poco::JSON::Array::ValueVec::const_iterator it = json->begin(); it != json->end(); it++)
{
if (json->isObject(it)) {
-
+
auto local_json = it->extract();
count_replacements += replaceBase64WithHex(local_json);
json->set(count, local_json);
@@ -414,14 +396,14 @@ namespace DataTypeConverter
std::string replaceNewLineWithBr(std::string& in)
{
-
+
std::string::size_type pos = 0; // Must initialize
while ((pos = in.find("\r\n", pos)) != std::string::npos) {
in.replace(pos, 2, "
");
}
pos = 0;
while ((pos = in.find("\n", pos)) != std::string::npos) {
- in.replace(pos, 1, "
");
+ in.replace(pos, 1, "
");
}
pos = 0;
while ((pos = in.find(" ", pos)) != std::string::npos) {
@@ -429,4 +411,4 @@ namespace DataTypeConverter
}
return in;
}
-}
\ No newline at end of file
+}
diff --git a/login_server/src/cpp/lib/DataTypeConverter.h b/login_server/src/cpp/lib/DataTypeConverter.h
index d61944081..2c2b7d222 100644
--- a/login_server/src/cpp/lib/DataTypeConverter.h
+++ b/login_server/src/cpp/lib/DataTypeConverter.h
@@ -11,8 +11,6 @@
#include "Poco/JSON/Array.h"
#include "../SingletonManager/LanguageManager.h"
-#include "proto/hedera/Timestamp.pb.h"
-#include "proto/hedera/Duration.pb.h"
#include "proto/gradido/BasicTypes.pb.h"
#include "sodium.h"
@@ -58,15 +56,12 @@ namespace DataTypeConverter {
//! \brief convert duration in string showing seconds, minutes, hours or days
std::string convertTimespanToLocalizedString(Poco::Timespan duration, LanguageCatalog* lang);
- Poco::Timestamp convertFromProtoTimestamp(const proto::Timestamp& timestamp);
Poco::Timestamp convertFromProtoTimestamp(const proto::gradido::Timestamp& timestamp);
- void convertToProtoTimestamp(const Poco::Timestamp pocoTimestamp, proto::Timestamp* protoTimestamp);
void convertToProtoTimestamp(const Poco::Timestamp pocoTimestamp, proto::gradido::Timestamp* protoTimestamp);
Poco::Timestamp convertFromProtoTimestampSeconds(const proto::gradido::TimestampSeconds& timestampSeconds);
inline void convertToProtoTimestampSeconds(const Poco::Timestamp pocoTimestamp, proto::gradido::TimestampSeconds* protoTimestampSeconds) {
protoTimestampSeconds->set_seconds(pocoTimestamp.epochTime());
}
- Poco::Timespan convertFromProtoDuration(const proto::Duration& duration);
//! \brief go through json object and replace every string entry in base64 format into hex format
//! \return count of replaced strings
diff --git a/login_server/src/cpp/lib/Error.cpp b/login_server/src/cpp/lib/Error.cpp
index 9897d7930..a341c4466 100644
--- a/login_server/src/cpp/lib/Error.cpp
+++ b/login_server/src/cpp/lib/Error.cpp
@@ -7,6 +7,12 @@ Error::Error(const char* functionName, const char* message)
}
+Error::Error(const char* functionName, const std::string& message)
+ : Notification(functionName, message)
+{
+
+}
+
Error::~Error()
{
diff --git a/login_server/src/cpp/lib/Error.h b/login_server/src/cpp/lib/Error.h
index 34199034f..0994d3ae5 100644
--- a/login_server/src/cpp/lib/Error.h
+++ b/login_server/src/cpp/lib/Error.h
@@ -19,6 +19,7 @@ class Error : public Notification
{
public:
Error(const char* functionName, const char* message);
+ Error(const char* functionName, const std::string& message);
~Error();
const char* getFunctionName() { return mFunctionName.data(); }
@@ -39,6 +40,8 @@ public:
: Error(functionName, message), mParam(param) {}
ParamError(const char* functionName, const char* message, const std::string& param)
: Error(functionName, message), mParam(param) {}
+ ParamError(const char* functionName, const std::string& message, const std::string& param)
+ : Error(functionName, message), mParam(param) {}
ParamError(const char* functioName, const char* message, int param)
: Error(functioName, message) {
diff --git a/login_server/src/cpp/lib/Notification.cpp b/login_server/src/cpp/lib/Notification.cpp
index 15d622923..f2fb628d1 100644
--- a/login_server/src/cpp/lib/Notification.cpp
+++ b/login_server/src/cpp/lib/Notification.cpp
@@ -4,4 +4,10 @@ Notification::Notification(const char* functionName, const char* message)
: mFunctionName(functionName), mMessage(message)
{
+}
+
+Notification::Notification(const char* functionName, const std::string& message)
+ : mFunctionName(functionName), mMessage(message)
+{
+
}
\ No newline at end of file
diff --git a/login_server/src/cpp/lib/Notification.h b/login_server/src/cpp/lib/Notification.h
index 419b861bc..39a712aa6 100644
--- a/login_server/src/cpp/lib/Notification.h
+++ b/login_server/src/cpp/lib/Notification.h
@@ -7,6 +7,7 @@ class Notification
{
public:
Notification(const char* functionName, const char* message);
+ Notification(const char* functionName, const std::string& message);
const char* getFunctionName() { return mFunctionName.data(); }
const char* getMessage() { return mMessage.data(); }
diff --git a/login_server/src/cpp/main.cpp b/login_server/src/cpp/main.cpp
index 24b6f15cf..da382094b 100644
--- a/login_server/src/cpp/main.cpp
+++ b/login_server/src/cpp/main.cpp
@@ -13,7 +13,6 @@
#include "model/table/EmailOptIn.h"
#include "Poco/DateTimeParser.h"
-#include
#ifndef _TEST_BUILD
@@ -52,18 +51,16 @@ int main(int argc, char** argv)
return -3;
}
printf("[Gradido_LoginServer::main] passed important tests\n");
- grpc_init();
Gradido_LoginServer app;
try {
auto result = app.run(argc, argv);
- grpc_shutdown();
return result;
}
catch (Poco::Exception& ex) {
printf("[Gradido_LoginServer::main] exception by starting server: %s\n", ex.displayText().data());
}
return -1;
-
+
}
-#endif
\ No newline at end of file
+#endif
diff --git a/login_server/src/cpp/model/Session.cpp b/login_server/src/cpp/model/Session.cpp
index c200cdc74..f50fa87df 100644
--- a/login_server/src/cpp/model/Session.cpp
+++ b/login_server/src/cpp/model/Session.cpp
@@ -14,7 +14,6 @@
#include "../tasks/PrepareEmailTask.h"
#include "../tasks/SendEmailTask.h"
-#include "../tasks/SigningTransaction.h"
#include "../tasks/AuthenticatedEncryptionCreateKeyTask.h"
#include "../tasks/VerificationEmailResendTask.h"
@@ -53,8 +52,8 @@ Session::~Session()
unlock();
reset();
}
-
-
+
+
//printf("[Session::~Session] finished \n");
}
@@ -70,24 +69,21 @@ void Session::reset()
// watch out
//updateTimeout();
mLastActivity = Poco::DateTime();
-
+
mState = SESSION_STATE_EMPTY;
-
+
mPassphrase = "";
mLastExternReferer = "";
mClientLoginIP = Poco::Net::IPAddress();
unlock();
- // reset transactions
- mCurrentActiveProcessingTransaction = nullptr;
- mProcessingTransactions.clear();
//printf("[Session::reset] finished\n");
}
int Session::isActive()
{
- int ret = 0;
+ int ret = 0;
try {
mWorkMutex.tryLock(100);
}
@@ -95,7 +91,7 @@ int Session::isActive()
return -1;
}
ret = (int)mActive;
- unlock();
+ unlock();
return ret;
}
@@ -108,21 +104,21 @@ bool Session::isDeadLocked()
return false;
}
catch (Poco::Exception& ex) {
-
+
}
return true;
}
bool Session::setActive(bool active)
-{
+{
try {
mWorkMutex.tryLock(100);
}
catch (Poco::TimeoutException &ex) {
return false;
}
- mActive = active;
- unlock();
+ mActive = active;
+ unlock();
return true;
}
@@ -187,13 +183,13 @@ bool Session::adminCreateUser(const std::string& first_name, const std::string&
addError(new Error(gettext("Email Verification Code"), gettext("Fehler beim speichern!")));
return false;
}
-
-
+
+
EmailManager::getInstance()->addEmail(new model::Email(email_verification_code, newUser, model::EMAIL_ADMIN_USER_VERIFICATION_CODE));
std::unique_lock _lock(mSharedMutex);
mEmailVerificationCodeObject = email_verification_code;
-
+
return true;
}
@@ -223,7 +219,7 @@ bool Session::createUserDirect(const std::string& first_name, const std::string&
addError(new Error(gettext("E-Mail"), gettext("Bitte gebe eine gültige E-Mail Adresse an.")), false);
return false;
}
-
+
if (!sm->checkPwdValidation(password, this, mLanguageCatalog)) {
return false;
}
@@ -247,7 +243,7 @@ bool Session::createUserDirect(const std::string& first_name, const std::string&
auto user_model = mNewUser->getModel();
user_model->insertIntoDB(true);
auto user_id = user_model->getID();
-
+
// one retry in case of connection error
if (!user_id) {
user_model->insertIntoDB(true);
@@ -317,17 +313,17 @@ int Session::updateEmailVerification(Poco::UInt64 emailVerificationCode)
// new mutex, will replace the Poco Mutex complete in the future
std::unique_lock _lock_shared(mSharedMutex);
Profiler usedTime;
-
+
auto em = ErrorManager::getInstance();
if (mEmailVerificationCodeObject.isNull()) {
em->addError(new Error(funcName, "email verification object is zero"));
em->sendErrorsAsEmail();
-
+
return -2;
}
auto email_verification_code_model = mEmailVerificationCodeObject->getModel();
assert(email_verification_code_model);
- if(email_verification_code_model->getCode() == emailVerificationCode)
+ if(email_verification_code_model->getCode() == emailVerificationCode)
{
// load correct user from db
if (mNewUser.isNull() || !mNewUser->getModel() || mNewUser->getModel()->getID() != email_verification_code_model->getUserId()) {
@@ -335,7 +331,7 @@ int Session::updateEmailVerification(Poco::UInt64 emailVerificationCode)
if (1 != mNewUser->load(email_verification_code_model->getUserId())) {
em->addError(new ParamError(funcName, "user load didn't return 1 with user_id ", email_verification_code_model->getUserId()));
em->sendErrorsAsEmail();
-
+
return -2;
}
}
@@ -344,14 +340,14 @@ int Session::updateEmailVerification(Poco::UInt64 emailVerificationCode)
assert(user_model);
bool first_email_activation = false;
auto verification_type = email_verification_code_model->getType();
- if (model::table::EMAIL_OPT_IN_REGISTER == verification_type ||
+ if (model::table::EMAIL_OPT_IN_REGISTER == verification_type ||
model::table::EMAIL_OPT_IN_EMPTY == verification_type ||
model::table::EMAIL_OPT_IN_REGISTER_DIRECT == verification_type) {
first_email_activation = true;
}
if (first_email_activation && user_model->isEmailChecked()) {
addError(new Error(gettext("E-Mail Verification"), gettext("Du hast dein Konto bereits aktiviert!")), false);
-
+
return 1;
}
if (first_email_activation) {
@@ -363,13 +359,13 @@ int Session::updateEmailVerification(Poco::UInt64 emailVerificationCode)
}
// no find all active sessions
-
+
updateState(SESSION_STATE_EMAIL_VERIFICATION_CODE_CHECKED);
return 0;
}
if (email_verification_code_model->getType() == model::table::EMAIL_OPT_IN_RESET_PASSWORD) {
-
+
if (mEmailVerificationCodeObject->deleteFromDB()) {
mEmailVerificationCodeObject.assign(nullptr);
}
@@ -385,18 +381,18 @@ int Session::updateEmailVerification(Poco::UInt64 emailVerificationCode)
em->addError(new Error(funcName, "invalid code path"));
em->sendErrorsAsEmail();
-
+
return -2;
-
+
}
else {
addError(new Error(gettext("E-Mail Verification"), gettext("Falscher Code für aktiven Login")));
//printf("[%s] time: %s\n", funcName, usedTime.string().data());
-
+
return -1;
}
//printf("[%s] time: %s\n", funcName, usedTime.string().data());
-
+
return 0;
}
@@ -409,7 +405,7 @@ int Session::sendResetPasswordEmail(Poco::AutoPtr user, bool p
std::unique_lock _lock(mSharedMutex);
// creating email verification code also for user without passphrase
- // first check if already exist
+ // first check if already exist
// check if email was already send shortly before
bool frequent_resend = false;
bool email_already_send = false;
@@ -450,7 +446,7 @@ int Session::sendResetPasswordEmail(Poco::AutoPtr user, bool p
int Session::comparePassphraseWithSavedKeys(const std::string& inputPassphrase, const Mnemonic* wordSource)
{
-
+
static const char* functionName = "Session::comparePassphraseWithSavedKeys";
if (!wordSource) {
addError(new Error(functionName, "wordSource is empty"));
@@ -495,137 +491,6 @@ int Session::comparePassphraseWithSavedKeys(const std::string& inputPassphrase,
return 0;
}
-bool Session::startProcessingTransaction(const std::string& proto_message_base64, bool autoSign/* = false*/)
-{
- static const char* funcName = "Session::startProcessingTransaction";
- lock(funcName);
- HASH hs = ProcessingTransaction::calculateHash(proto_message_base64);
- // check if it is already running or waiting
- for (auto it = mProcessingTransactions.begin(); it != mProcessingTransactions.end(); it++) {
- if (it->isNull()) {
- it = mProcessingTransactions.erase(it);
- }
- if (hs == (*it)->getHash()) {
- addError(new Error(funcName, "transaction already in list"));
- unlock();
- return false;
- }
- }
-
- Languages lang = LANG_DE;
- if (!mNewUser.isNull()) {
- lang = LanguageManager::languageFromString(mNewUser->getModel()->getLanguageKey());
- }
- auto user_model = mNewUser->getModel();
- Poco::AutoPtr processorTask(
- new ProcessingTransaction(
- proto_message_base64,
- DRMakeStringHash(user_model->getEmail().data()),
- lang
- )
- );
- if (autoSign && (ServerConfig::g_AllowUnsecureFlags & ServerConfig::UNSECURE_AUTO_SIGN_TRANSACTIONS) == ServerConfig::UNSECURE_AUTO_SIGN_TRANSACTIONS) {
- if (processorTask->run() != 0) {
- getErrors(processorTask);
- unlock();
- return false;
- }
- Poco::AutoPtr signingTransaction(new SigningTransaction(processorTask, mNewUser));
- //signingTransaction->scheduleTask(signingTransaction);
- if (signingTransaction->run() != 0) {
- getErrors(signingTransaction);
- unlock();
- return false;
- }
-
- }
- else {
- processorTask->scheduleTask(processorTask);
- mProcessingTransactions.push_back(processorTask);
- }
- unlock();
- return true;
-
-}
-
-Poco::AutoPtr Session::getNextReadyTransaction(size_t* working/* = nullptr*/)
-{
- lock("Session::getNextReadyTransaction");
- if (working) {
- *working = 0;
- }
- else if (!mCurrentActiveProcessingTransaction.isNull())
- {
- unlock();
- return mCurrentActiveProcessingTransaction;
- }
- for (auto it = mProcessingTransactions.begin(); it != mProcessingTransactions.end(); it++) {
- if (working && !(*it)->isTaskFinished()) {
- (*working)++;
- }
- if (mCurrentActiveProcessingTransaction.isNull() && (*it)->isTaskFinished()) {
- if (!working) {
- mCurrentActiveProcessingTransaction = *it;
- unlock();
- return mCurrentActiveProcessingTransaction;
- }
- // no early exit
- else {
- mCurrentActiveProcessingTransaction = *it;
- }
-
- }
- }
- unlock();
- return mCurrentActiveProcessingTransaction;
-}
-
-bool Session::finalizeTransaction(bool sign, bool reject)
-{
- int result = -1;
- lock("Session::finalizeTransaction");
- if (mCurrentActiveProcessingTransaction.isNull()) {
- unlock();
- return false;
- }
- mProcessingTransactions.remove(mCurrentActiveProcessingTransaction);
-
- if (!reject) {
- if (sign) {
- Poco::AutoPtr signingTransaction(new SigningTransaction(mCurrentActiveProcessingTransaction, mNewUser));
- //signingTransaction->scheduleTask(signingTransaction);
- result = signingTransaction->run();
- }
- }
- mCurrentActiveProcessingTransaction.assign(nullptr);
- unlock();
- return result == 0;
-}
-
-size_t Session::getProcessingTransactionCount()
-{
- size_t count = 0;
- lock("Session::getProcessingTransactionCount");
-
- for (auto it = mProcessingTransactions.begin(); it != mProcessingTransactions.end(); it++) {
-
- (*it)->lock();
- if ((*it)->errorCount() > 0) {
- (*it)->sendErrorsAsEmail();
- (*it)->unlock();
- it = mProcessingTransactions.erase(it);
- if (it == mProcessingTransactions.end()) break;
- }
- else {
- (*it)->unlock();
- }
-
- }
- count = mProcessingTransactions.size();
- unlock();
- return count;
-}
-
UserState Session::loadUser(const std::string& email, const std::string& password)
{
static const char* functionName = "Session::loadUser";
@@ -657,11 +522,11 @@ UserState Session::loadUser(const std::string& email, const std::string& passwor
}
//printf("before get model\n");
auto user_model = mNewUser->getModel();
- if (user_model && user_model->isDisabled()) {
+ if (user_model && user_model->isDisabled()) {
return USER_DISABLED;
}
if (mNewUser->getUserState() >= USER_LOADED_FROM_DB) {
-
+
NotificationList pwd_errors;
auto lm = LanguageManager::getInstance();
auto lang_key = mNewUser->getModel()->getLanguageKey();
@@ -677,9 +542,9 @@ UserState Session::loadUser(const std::string& email, const std::string& passwor
int loginResult = mNewUser->login(password);
int exitCount = 0;
- if (loginResult == -3)
+ if (loginResult == -3)
{
- do
+ do
{
Poco::Thread::sleep(100);
loginResult = mNewUser->login(password);
@@ -702,7 +567,7 @@ UserState Session::loadUser(const std::string& email, const std::string& passwor
return USER_PASSWORD_ENCRYPTION_IN_PROCESS;
}
}
-
+
if (-1 == loginResult)
{
addError(new Error(functionName, "error in user data set, saved pubkey didn't match extracted pubkey from private key"));
@@ -711,7 +576,7 @@ UserState Session::loadUser(const std::string& email, const std::string& passwor
//unlock();
//return USER_KEYS_DONT_MATCH;
}
- if (0 == loginResult)
+ if (0 == loginResult)
{
return USER_PASSWORD_INCORRECT;
}
@@ -724,9 +589,9 @@ UserState Session::loadUser(const std::string& email, const std::string& passwor
auto user_backups = controller::UserBackup::load(user_model->getID());
for (auto it = user_backups.begin(); it != user_backups.end(); it++) {
auto key = std::unique_ptr((*it)->createGradidoKeyPair());
- if (key->isTheSame(user_model->getPublicKey()))
+ if (key->isTheSame(user_model->getPublicKey()))
{
-
+
// set valid key pair
if (1 == mNewUser->setGradidoKeyPair(key.release())) {
// save new encrypted private key
@@ -742,7 +607,7 @@ UserState Session::loadUser(const std::string& email, const std::string& passwor
}
}
}
-
+
}
else {
Poco::Thread::sleep(ServerConfig::g_FakeLoginSleepTime);
@@ -851,7 +716,7 @@ void Session::detectSessionState()
else if (checkEmail != -1) {
mEmailVerificationCodeObject = emailVerificationCodeObjects[checkEmail];
}
-
+
}
catch (Poco::Exception& ex) {
printf("[Session::detectSessionState] exception: %s\n", ex.displayText().data());
@@ -864,13 +729,13 @@ void Session::detectSessionState()
updateState(SESSION_STATE_EMAIL_VERIFICATION_WRITTEN);
return;
}
-
+
updateState(SESSION_STATE_USER_WRITTEN);
return;
}
if (USER_NO_KEYS == userState) {
-
+
auto user_id = mNewUser->getModel()->getID();
auto userBackups = controller::UserBackup::load(user_id);
@@ -903,8 +768,8 @@ void Session::detectSessionState()
auto dbConnection = ConnectionManager::getInstance()->getConnection(CONNECTION_MYSQL_LOGIN_SERVER);
Poco::Data::Statement select(dbConnection);
Poco::Nullable passphrase;
-
- select << "SELECT passphrase from user_backups where user_id = ?;",
+
+ select << "SELECT passphrase from user_backups where user_id = ?;",
into(passphrase), use(user_id);
try {
if (select.execute() == 1 && !passphrase.isNull()) {
@@ -927,7 +792,7 @@ void Session::detectSessionState()
updateState(SESSION_STATE_EMAIL_VERIFICATION_CODE_CHECKED);
return;
}
-
+
updateState(SESSION_STATE_KEY_PAIR_WRITTEN);
if (resetPasswd != -1) {
@@ -945,14 +810,14 @@ Poco::Net::HTTPCookie Session::getLoginCookie()
// keks.setHttpOnly();
keks.setPath("/");
- // send cookie only via https, on linux, except in test builds
+ // send cookie only via https, on linux, except in test builds
#ifndef WIN32
if (ServerConfig::SERVER_TYPE_PRODUCTION == ServerConfig::g_ServerSetupType ||
ServerConfig::SERVER_TYPE_STAGING == ServerConfig::g_ServerSetupType) {
keks.setSecure(true);
}
#endif
-
+
return keks;
}
@@ -1024,7 +889,7 @@ const char* Session::translateSessionStateToString(SessionStates state)
case SESSION_STATE_EMAIL_VERIFICATION_SEND: return "Verification E-Mail sended";
case SESSION_STATE_EMAIL_VERIFICATION_CODE_CHECKED: return "Verification Code checked";
case SESSION_STATE_PASSPHRASE_GENERATED: return "Passphrase generated";
- case SESSION_STATE_PASSPHRASE_SHOWN: return "Passphrase shown";
+ case SESSION_STATE_PASSPHRASE_SHOWN: return "Passphrase shown";
case SESSION_STATE_PASSPHRASE_WRITTEN: return "Passphrase written";
case SESSION_STATE_KEY_PAIR_GENERATED: return "Gradido Address created";
case SESSION_STATE_KEY_PAIR_WRITTEN: return "Gradido Address saved";
@@ -1041,7 +906,7 @@ const char* Session::translateSessionStateToString(SessionStates state)
bool Session::useOrGeneratePassphrase(const std::string& passphase)
{
if (passphase != "" && User::validatePassphrase(passphase)) {
- // passphrase is valid
+ // passphrase is valid
setPassphrase(passphase);
updateState(SESSION_STATE_PASSPHRASE_SHOWN);
return true;
@@ -1081,7 +946,7 @@ bool Session::generateKeys(bool savePrivkey, bool savePassphrase)
if (savePassphrase) {
auto user_backup = controller::UserBackup::create(user_model->getID(), passphrase->getString(), mnemonic_type);
// sync version
- //user_backup->getModel()->insertIntoDB(false);
+ //user_backup->getModel()->insertIntoDB(false);
// async version
UniLib::controller::TaskPtr save_user_backup_task = new model::table::ModelInsertTask(user_backup->getModel(), false, true);
@@ -1089,7 +954,7 @@ bool Session::generateKeys(bool savePrivkey, bool savePassphrase)
save_user_backup_task->scheduleTask(save_user_backup_task);
}
- // keys
+ // keys
auto gradido_key_pair = KeyPairEd25519::create(passphrase);
auto set_key_result = mNewUser->setGradidoKeyPair(gradido_key_pair);
size_t result_save_key = 0;
diff --git a/login_server/src/cpp/model/Session.h b/login_server/src/cpp/model/Session.h
index aaa6dc7c4..1607d23c9 100644
--- a/login_server/src/cpp/model/Session.h
+++ b/login_server/src/cpp/model/Session.h
@@ -14,7 +14,6 @@
#include "../controller/User.h"
#include "../lib/MultithreadContainer.h"
-#include "../tasks/ProcessingTransaction.h"
#include "../SingletonManager/LanguageManager.h"
@@ -83,7 +82,7 @@ public:
// TODO: check if email exist and if not, fake waiting on password hashing with profiled times of real password hashing
UserState loadUser(const std::string& email, const std::string& password);
bool ifUserExist(const std::string& email);
-
+
bool deleteUser();
@@ -102,7 +101,7 @@ public:
//! \return 2 = reset password email already shortly before
//! \return 0 = ok
int sendResetPasswordEmail(Poco::AutoPtr user, bool passphraseMemorized, const std::string &baseUrl);
- //
+ //
//! \return 0 = not the same
//! \return 1 = same
//! \return -1 = error
@@ -111,23 +110,23 @@ public:
Poco::Net::HTTPCookie getLoginCookie();
-
+
inline int getHandle() { return mHandleId; }
// ------------------------ Passphrase functions ----------------------------
-
+
inline void setPassphrase(Poco::AutoPtr passphrase) { mNewPassphrase = passphrase; }
inline Poco::AutoPtr getPassphrase() { return mNewPassphrase; }
inline void setPassphrase(const std::string& passphrase) { mPassphrase = passphrase; }
-
+
inline const std::string& getOldPassphrase() { return mPassphrase; }
-
+
bool generateKeys(bool savePrivkey, bool savePassphrase);
inline void setClientIp(Poco::Net::IPAddress ip) { mClientLoginIP = ip; }
inline Poco::Net::IPAddress getClientIp() { return mClientLoginIP; }
-
+
inline bool isIPValid(Poco::Net::IPAddress ip) { return mClientLoginIP == ip; }
void reset();
@@ -135,9 +134,9 @@ public:
const char* getSessionStateString();
inline SessionStates getSessionState() { SessionStates s; lock("Session::getSessionState"); s = mState; unlock(); return s; }
- inline Poco::UInt64 getEmailVerificationCode() {
+ inline Poco::UInt64 getEmailVerificationCode() {
std::shared_lock _lock(mSharedMutex);
- if (mEmailVerificationCodeObject.isNull()) return 0; return mEmailVerificationCodeObject->getModel()->getCode();
+ if (mEmailVerificationCodeObject.isNull()) return 0; return mEmailVerificationCodeObject->getModel()->getCode();
}
inline void setEmailVerificationCodeObject(Poco::AutoPtr emailVerficationObject) {
std::unique_lock _lock(mSharedMutex);
@@ -153,7 +152,7 @@ public:
//! \return -1 if session is locked
//! \return 1 if session is active
- //! \return 0
+ //! \return 0
int isActive();
//! \return false if session is locked
bool setActive(bool active);
@@ -164,12 +163,6 @@ public:
// ------------------------ transactions functions ----------------------------
- //! \return true if succeed
- bool startProcessingTransaction(const std::string& proto_message_base64, bool autoSign = false);
- //! \param working if set will filled with transaction running
- Poco::AutoPtr getNextReadyTransaction(size_t* working = nullptr);
- bool finalizeTransaction(bool sign, bool reject);
- size_t getProcessingTransactionCount();
inline LanguageCatalog* getLanguageCatalog() { return mLanguageCatalog.isNull() ? nullptr : mLanguageCatalog; }
void setLanguage(Languages lang);
@@ -187,14 +180,14 @@ public:
protected:
void updateTimeout();
inline void setHandle(int newHandle) { mHandleId = newHandle; }
-
+
void detectSessionState();
static const char* translateSessionStateToString(SessionStates state);
inline const std::string& getPassphrase() const { return mPassphrase; }
-
-private:
+
+private:
int mHandleId;
Poco::AutoPtr mNewUser;
std::string mPassphrase;
@@ -211,8 +204,6 @@ private:
SessionStates mState;
bool mActive;
- std::list> mProcessingTransactions;
- Poco::AutoPtr mCurrentActiveProcessingTransaction;
Poco::AutoPtr mLanguageCatalog;
};
diff --git a/login_server/src/cpp/model/gradido/Transaction.cpp b/login_server/src/cpp/model/gradido/Transaction.cpp
index 0301d4440..20f47bb83 100644
--- a/login_server/src/cpp/model/gradido/Transaction.cpp
+++ b/login_server/src/cpp/model/gradido/Transaction.cpp
@@ -2,21 +2,13 @@
#include "../../SingletonManager/ErrorManager.h"
#include "../../SingletonManager/PendingTasksManager.h"
#include "../../SingletonManager/LanguageManager.h"
-#include "../../SingletonManager/CronManager.h"
#include "../../ServerConfig.h"
-#include "../../controller/HederaId.h"
-#include "../../controller/HederaAccount.h"
-#include "../../controller/HederaRequest.h"
#include "../../lib/DataTypeConverter.h"
#include "../../lib/Profiler.h"
#include "../../lib/JsonRequest.h"
-#include "../hedera/Transaction.h"
-#include "../hedera/TransactionId.h"
-
-#include "../../tasks/HederaTask.h"
#include
@@ -65,21 +57,11 @@ namespace model {
return nullptr;
}
auto group_model = group->getModel();
- auto network_type = ServerConfig::g_HederaNetworkType;
- auto topic_id = controller::HederaId::find(group_model->getID(), network_type);
-
- if (topic_id.isNull()) {
- em->addError(new ParamError(function_name, "could'n find topic for group: ", group_model->getID()));
- em->addError(new ParamError(function_name, "network type: ", network_type));
- em->sendErrorsAsEmail();
- return nullptr;
- }
auto body = TransactionBody::create("", user, proto::gradido::GroupMemberUpdate_MemberUpdateType_ADD_USER, group_model->getAlias());
Poco::AutoPtr result = new Transaction(body);
auto model = result->getModel();
- model->setHederaId(topic_id->getModel()->getID());
result->insertPendingTaskIntoDB(user, model::table::TASK_TYPE_GROUP_ADD_MEMBER);
PendingTasksManager::getInstance()->addTask(result);
return result;
@@ -99,7 +81,6 @@ namespace model {
if (receiver.isNull() || !receiver->getModel()) {
return nullptr;
}
- auto network_type = ServerConfig::g_HederaNetworkType;
auto receiver_model = receiver->getModel();
auto body = TransactionBody::create(memo, receiver, amount, targetDate, blockchainType);
@@ -107,17 +88,7 @@ namespace model {
result->setParam("blockchain_type", (int)blockchainType);
auto model = result->getModel();
- if (blockchainType == BLOCKCHAIN_HEDERA) {
- auto topic_id = controller::HederaId::find(receiver_model->getGroupId(), network_type);
- if (topic_id.isNull()) {
- em->addError(new ParamError(function_name, "could'n find topic for group: ", receiver_model->getGroupId()));
- em->addError(new ParamError(function_name, "network type: ", network_type));
- em->sendErrorsAsEmail();
- return nullptr;
- }
- model->setHederaId(topic_id->getModel()->getID());
- }
result->insertPendingTaskIntoDB(receiver, model::table::TASK_TYPE_CREATION);
PendingTasksManager::getInstance()->addTask(result);
@@ -136,7 +107,6 @@ namespace model {
{
Poco::AutoPtr transaction;
Poco::AutoPtr transaction_body;
- Poco::AutoPtr topic_id;
auto em = ErrorManager::getInstance();
static const char* function_name = "Transaction::create transfer";
@@ -151,75 +121,6 @@ namespace model {
transaction_body = TransactionBody::create(memo, sender, receiverPubkey, amount, blockchainType);
transaction = new Transaction(transaction_body);
}
- else if (blockchainType == BLOCKCHAIN_HEDERA)
- {
- auto network_type = ServerConfig::g_HederaNetworkType;
-
-
- // LOCAL Transfer
- if (receiverGroup.isNull() || sender_model->getGroupId() == receiverGroup->getModel()->getID())
- {
- topic_id = controller::HederaId::find(sender_model->getGroupId(), network_type);
-
- if (topic_id.isNull())
- {
- em->addError(new ParamError(function_name, "could'n find topic for group: ", sender_model->getGroupId()));
- em->addError(new ParamError(function_name, "network type: ", network_type));
- em->sendErrorsAsEmail();
- return transaction;
- }
- transaction_body = TransactionBody::create(memo, sender, receiverPubkey, amount, blockchainType);
- transaction = new Transaction(transaction_body);
- }
- else
- {
- auto sender_group = controller::Group::load(sender_model->getGroupId());
- if (sender_group.isNull())
- {
- em->addError(new ParamError(function_name, "couldn't find group with id: ", sender_model->getGroupId()));
- em->sendErrorsAsEmail();
- return transaction;
- }
- Poco::AutoPtr transaction_group;
- Poco::AutoPtr