diff --git a/app/modules/web/Controllers/AccessManagerController.php b/app/modules/web/Controllers/AccessManagerController.php
index 684599c0..963605fc 100644
--- a/app/modules/web/Controllers/AccessManagerController.php
+++ b/app/modules/web/Controllers/AccessManagerController.php
@@ -31,7 +31,7 @@ use SP\DataModel\ItemSearchData;
use SP\Http\Request;
use SP\Modules\Web\Controllers\Helpers\ItemsGridHelper;
use SP\Modules\Web\Controllers\Helpers\TabsGridHelper;
-use SP\Repositories\ApiToken\ApiTokenRepository;
+use SP\Repositories\AuthToken\AuthTokenRepository;
use SP\Repositories\PublicLink\PublicLinkRepository;
use SP\Repositories\User\UserRepository;
use SP\Repositories\UserGroup\UserGroupRepository;
@@ -143,7 +143,7 @@ class AccessManagerController extends ControllerBase
*/
protected function getApiTokensList()
{
- $service = new ApiTokenRepository();
+ $service = new AuthTokenRepository();
return $this->itemsGridHelper->getApiTokensGrid($service->search($this->itemSearchData))->updatePager();
}
diff --git a/app/modules/web/Controllers/AccountController.php b/app/modules/web/Controllers/AccountController.php
index f637af4c..257ec724 100644
--- a/app/modules/web/Controllers/AccountController.php
+++ b/app/modules/web/Controllers/AccountController.php
@@ -44,7 +44,9 @@ use SP\Modules\Web\Controllers\Traits\JsonTrait;
use SP\Mvc\Controller\CrudControllerInterface;
use SP\Repositories\PublicLink\PublicLinkRepository;
use SP\Services\Account\AccountFileService;
+use SP\Services\Account\AccountHistoryService;
use SP\Services\Account\AccountService;
+use SP\Services\PublicLink\PublicLinkService;
use SP\Util\ErrorUtil;
use SP\Util\ImageUtil;
use SP\Util\Util;
@@ -175,7 +177,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac
$LayoutHelper->getPublicLayout('account-link', 'account');
try {
- $publicLinkService = new PublicLinkRepository();
+ $publicLinkService = new PublicLinkService();
$publicLinkData = $publicLinkService->getByHash($hash);
if (time() < $publicLinkData->getDateExpire()
@@ -208,7 +210,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac
$vault = unserialize($publicLinkData->getData());
/** @var AccountExtData $accountData */
- $accountData = Util::unserialize(AccountExtData::class, $vault->getData(PublicLinkRepository::getKeyForHash($this->config, $publicLinkData)));
+ $accountData = Util::unserialize(AccountExtData::class, $vault->getData(PublicLinkService::getKeyForHash($this->config->getConfigData()->getPasswordSalt(), $publicLinkData)));
$this->view->assign('title',
[
@@ -520,8 +522,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac
try {
$AccountHelper = new AccountHelper($this->view, $this->config, $this->session, $this->eventDispatcher);
- // FIXME: Crear servicio AccountHistoryService
- $AccountHelper->setAccountDataHistory($this->accountService->getById($id), ActionsInterface::ACCOUNT_VIEW_HISTORY);
+ $AccountHelper->setAccountDataHistory($id, ActionsInterface::ACCOUNT_VIEW_HISTORY);
// Obtener los datos de la cuenta antes y comprobar el acceso
if (!$AccountHelper->checkAccess()) {
@@ -591,7 +592,6 @@ class AccountController extends ControllerBase implements CrudControllerInterfac
try {
$accountPassHelper = new AccountPasswordHelper($this->view, $this->config, $this->session, $this->eventDispatcher);
- // FIXME: JS no envía isHistory
$account = $isHistory === 0 ? $this->accountService->getPasswordForId($id) : $this->accountService->getPasswordHistoryForId($id);
$data = [
@@ -619,6 +619,7 @@ class AccountController extends ControllerBase implements CrudControllerInterfac
* @throws Helpers\HelperException
* @throws SPException
* @throws \Defuse\Crypto\Exception\CryptoException
+ * @throws \SP\Core\Dic\ContainerException
* @throws \SP\Core\Exceptions\InvalidArgumentException
*/
public function copyPassAction($id, $isHistory)
diff --git a/app/modules/web/Controllers/ApiTokenController.php b/app/modules/web/Controllers/ApiTokenController.php
index fdc35839..d79d9047 100644
--- a/app/modules/web/Controllers/ApiTokenController.php
+++ b/app/modules/web/Controllers/ApiTokenController.php
@@ -32,8 +32,8 @@ use SP\Core\Acl\ActionsInterface;
use SP\Core\Exceptions\SPException;
use SP\Core\Exceptions\ValidationException;
use SP\Core\SessionUtil;
-use SP\DataModel\ApiTokenData;
-use SP\Forms\ApiTokenForm;
+use SP\DataModel\AuthTokenData;
+use SP\Forms\AuthTokenForm;
use SP\Http\JsonResponse;
use SP\Http\Request;
use SP\Mgmt\ApiTokens\ApiTokensUtil;
@@ -42,7 +42,7 @@ use SP\Modules\Web\Controllers\Traits\ItemTrait;
use SP\Modules\Web\Controllers\Traits\JsonTrait;
use SP\Mvc\Controller\CrudControllerInterface;
use SP\Mvc\View\Components\SelectItemAdapter;
-use SP\Services\ApiToken\ApiTokenService;
+use SP\Services\AuthToken\AuthTokenService;
use SP\Services\User\UserService;
/**
@@ -56,9 +56,9 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
use ItemTrait;
/**
- * @var ApiTokenService
+ * @var AuthTokenService
*/
- protected $apiTokenService;
+ protected $authTokenService;
/**
* Search action
@@ -72,7 +72,7 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
}
$itemsGridHelper = new ItemsGridHelper($this->view, $this->config, $this->session, $this->eventDispatcher);
- $grid = $itemsGridHelper->getApiTokensGrid($this->apiTokenService->search($this->getSearchData($this->configData)))->updatePager();
+ $grid = $itemsGridHelper->getApiTokensGrid($this->authTokenService->search($this->getSearchData($this->configData)))->updatePager();
$this->view->addTemplate('datagrid-table', 'grid');
$this->view->assign('index', Request::analyze('activetab', 0));
@@ -100,7 +100,7 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
try {
$this->setViewData();
- $this->eventDispatcher->notifyEvent('show.apiToken.create', $this);
+ $this->eventDispatcher->notifyEvent('show.authToken.create', $this);
} catch (\Exception $e) {
$this->returnJsonResponse(1, $e->getMessage());
}
@@ -111,19 +111,19 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
/**
* Sets view data for displaying user's data
*
- * @param $apiTokenId
+ * @param $authTokenId
* @throws \Psr\Container\ContainerExceptionInterface
*/
- protected function setViewData($apiTokenId = null)
+ protected function setViewData($authTokenId = null)
{
- $this->view->addTemplate('apitoken', 'itemshow');
+ $this->view->addTemplate('authtoken', 'itemshow');
- $apiToken = $apiTokenId ? $this->apiTokenService->getById($apiTokenId) : new ApiTokenData();
+ $authToken = $authTokenId ? $this->authTokenService->getById($authTokenId) : new AuthTokenData();
- $this->view->assign('apiToken', $apiToken);
+ $this->view->assign('authToken', $authToken);
- $this->view->assign('users', (new SelectItemAdapter(UserService::getItemsBasic()))->getItemsFromModelSelected([$apiToken->getUserId()]));
- $this->view->assign('actions', (new SelectItemAdapter(ApiTokensUtil::getTokenActions()))->getItemsFromArraySelected([$apiToken->getActionId()]));
+ $this->view->assign('users', (new SelectItemAdapter(UserService::getItemsBasic()))->getItemsFromModelSelected([$authToken->getUserId()]));
+ $this->view->assign('actions', (new SelectItemAdapter(ApiTokensUtil::getTokenActions()))->getItemsFromArraySelected([$authToken->getActionId()]));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$this->view->assign('nextAction', Acl::getActionRoute(ActionsInterface::ACCESS_MANAGE));
@@ -136,7 +136,7 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
$this->view->assign('readonly');
}
- $this->view->assign('customFields', $this->getCustomFieldsForItem(ActionsInterface::APITOKEN, $apiTokenId));
+ $this->view->assign('customFields', $this->getCustomFieldsForItem(ActionsInterface::APITOKEN, $authTokenId));
}
/**
@@ -158,7 +158,7 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
try {
$this->setViewData($id);
- $this->eventDispatcher->notifyEvent('show.apiToken.edit', $this);
+ $this->eventDispatcher->notifyEvent('show.authToken.edit', $this);
} catch (\Exception $e) {
$this->returnJsonResponse(JsonResponse::JSON_ERROR, $e->getMessage());
}
@@ -178,12 +178,11 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
}
try {
-// $this->apiTokenService->logAction($id, ActionsInterface::APITOKEN_DELETE);
- $this->apiTokenService->delete($id);
+ $this->authTokenService->delete($id);
$this->deleteCustomFieldsForItem(ActionsInterface::APITOKEN, $id);
- $this->eventDispatcher->notifyEvent('delete.apiToken', $this);
+ $this->eventDispatcher->notifyEvent('delete.authToken', $this);
$this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Autorización eliminada'));
} catch (SPException $e) {
@@ -203,17 +202,16 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
}
try {
- $form = new ApiTokenForm();
+ $form = new AuthTokenForm();
$form->validate(ActionsInterface::APITOKEN_CREATE);
$apiTokenData = $form->getItemData();
- $id = $this->apiTokenService->create($apiTokenData);
-// $this->apiTokenService->logAction($id, ActionsInterface::APITOKEN_CREATE);
+ $id = $this->authTokenService->create($apiTokenData);
$this->addCustomFieldsForItem(ActionsInterface::APITOKEN, $id);
- $this->eventDispatcher->notifyEvent('create.apiToken', $this);
+ $this->eventDispatcher->notifyEvent('create.authToken', $this);
$this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Autorización creada'));
} catch (ValidationException $e) {
@@ -237,6 +235,7 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
* Saves edit action
*
* @param $id
+ * @throws \SP\Core\Dic\ContainerException
*/
public function saveEditAction($id)
{
@@ -245,18 +244,21 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
}
try {
- $form = new ApiTokenForm($id);
+ $form = new AuthTokenForm($id);
$form->validate(ActionsInterface::APITOKEN_EDIT);
- $apiTokenData = $form->getItemData();
+ if ($form->isRefresh()){
+ $this->authTokenService->refreshAndUpdate($form->getItemData());
- $this->apiTokenService->update($apiTokenData);
-// $this->apiTokenService->logAction($id, ActionsInterface::APITOKEN_EDIT);
+ $this->eventDispatcher->notifyEvent('refresh.authToken', $this);
+ } else {
+ $this->authTokenService->update($form->getItemData());
+
+ $this->eventDispatcher->notifyEvent('edit.authToken', $this);
+ }
$this->updateCustomFieldsForItem(ActionsInterface::APITOKEN, $id);
- $this->eventDispatcher->notifyEvent('edit.apiToken', $this);
-
$this->returnJsonResponse(JsonResponse::JSON_SUCCESS, __u('Autorización actualizada'));
} catch (ValidationException $e) {
$this->returnJsonResponse(JsonResponse::JSON_ERROR, $e->getMessage());
@@ -289,7 +291,7 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
try {
$this->setViewData($id);
- $this->eventDispatcher->notifyEvent('show.apiToken', $this);
+ $this->eventDispatcher->notifyEvent('show.authToken', $this);
} catch (\Exception $e) {
$this->returnJsonResponse(JsonResponse::JSON_ERROR, $e->getMessage());
}
@@ -306,6 +308,6 @@ class ApiTokenController extends ControllerBase implements CrudControllerInterfa
{
$this->checkLoggedIn();
- $this->apiTokenService = new ApiTokenService();
+ $this->authTokenService = new AuthTokenService();
}
}
\ No newline at end of file
diff --git a/app/modules/web/Controllers/Helpers/AccountHelper.php b/app/modules/web/Controllers/Helpers/AccountHelper.php
index 2608cc85..2b6c17ba 100644
--- a/app/modules/web/Controllers/Helpers/AccountHelper.php
+++ b/app/modules/web/Controllers/Helpers/AccountHelper.php
@@ -35,9 +35,11 @@ use SP\Modules\Web\Controllers\Traits\ItemTrait;
use SP\Mvc\View\Components\SelectItemAdapter;
use SP\Repositories\Account\AccountHistoryRepository;
use SP\Repositories\PublicLink\PublicLinkRepository;
+use SP\Services\Account\AccountHistoryService;
use SP\Services\Account\AccountService;
use SP\Services\Category\CategoryService;
use SP\Services\Client\ClientService;
+use SP\Services\PublicLink\PublicLinkService;
use SP\Services\Tag\TagService;
use SP\Services\User\UserService;
use SP\Services\UserGroup\UserGroupService;
@@ -99,6 +101,7 @@ class AccountHelper extends HelperBase
*
* @param $accountHistoryId
* @param $actionId
+ * @throws \SP\Core\Dic\ContainerException
*/
public function setAccountDataHistory($accountHistoryId, $actionId)
{
@@ -106,7 +109,8 @@ class AccountHelper extends HelperBase
$this->actionId = $actionId;
$this->isHistory = true;
- $this->accountService = new AccountHistoryRepository();
+ // FIXME
+ $this->accountService = new AccountHistoryService();
$this->accountDetailsResponse = $this->accountService->getById($accountHistoryId);
$this->accountId = $this->accountDetailsResponse->getId();
@@ -174,7 +178,7 @@ class AccountHelper extends HelperBase
$publicLinkService = new PublicLinkRepository();
$publicLinkData = $publicLinkService->getHashForItem($this->accountId);
- $publicLinkUrl = $publicLinkData ? PublicLinkRepository::getLinkForHash($publicLinkData->getHash()) : null;
+ $publicLinkUrl = $publicLinkData ? PublicLinkService::getLinkForHash($publicLinkData->getHash()) : null;
$this->view->assign('publicLinkUrl', $publicLinkUrl);
$this->view->assign('publicLinkId', $publicLinkData ? $publicLinkData->getId() : 0);
$this->view->assign('publicLinkShow', true);
diff --git a/app/modules/web/Controllers/Helpers/ItemsGridHelper.php b/app/modules/web/Controllers/Helpers/ItemsGridHelper.php
index 3c1b8bf5..e82a4a69 100644
--- a/app/modules/web/Controllers/Helpers/ItemsGridHelper.php
+++ b/app/modules/web/Controllers/Helpers/ItemsGridHelper.php
@@ -124,7 +124,7 @@ class ItemsGridHelper extends HelperBase
$GridActionEdit->setTitle(__('Editar Categoría'));
$GridActionEdit->setIcon($this->icons->getIconEdit());
$GridActionEdit->setOnClickFunction('appMgmt/show');
- $GridActionEdit->addData('action-route', Acl::getActionRoute(ActionsInterface::CATEGORY_VIEW));
+ $GridActionEdit->addData('action-route', Acl::getActionRoute(ActionsInterface::CATEGORY_EDIT));
$Grid->setDataActions($GridActionEdit);
diff --git a/app/modules/web/Controllers/ItemManagerController.php b/app/modules/web/Controllers/ItemManagerController.php
index 80a06902..a46885a0 100644
--- a/app/modules/web/Controllers/ItemManagerController.php
+++ b/app/modules/web/Controllers/ItemManagerController.php
@@ -62,6 +62,7 @@ class ItemManagerController extends ControllerBase
/**
* @throws \SP\Core\Exceptions\InvalidArgumentException
+ * @throws \SP\Core\Dic\ContainerException
*/
public function indexAction()
{
@@ -72,6 +73,7 @@ class ItemManagerController extends ControllerBase
* Returns a tabbed grid with items
*
* @throws \SP\Core\Exceptions\InvalidArgumentException
+ * @throws \SP\Core\Dic\ContainerException
*/
protected function getGridTabs()
{
diff --git a/app/modules/web/Controllers/PublicLinkController.php b/app/modules/web/Controllers/PublicLinkController.php
index a47d32d8..3ad0ada3 100644
--- a/app/modules/web/Controllers/PublicLinkController.php
+++ b/app/modules/web/Controllers/PublicLinkController.php
@@ -40,7 +40,6 @@ use SP\Modules\Web\Controllers\Traits\ItemTrait;
use SP\Modules\Web\Controllers\Traits\JsonTrait;
use SP\Mvc\Controller\CrudControllerInterface;
use SP\Mvc\View\Components\SelectItemAdapter;
-use SP\Repositories\PublicLink\PublicLinkRepository;
use SP\Services\Account\AccountService;
use SP\Services\PublicLink\PublicLinkService;
@@ -121,13 +120,14 @@ class PublicLinkController extends ControllerBase implements CrudControllerInter
$publicLink = $publicLinkId ? $this->publicLinkService->getById($publicLinkId) : new PublicLinkListData();
$this->view->assign('publicLink', $publicLink);
+ $this->view->assign('usageInfo', unserialize($publicLink->getUseInfo()));
$this->view->assign('accounts', (new SelectItemAdapter((new AccountService())->getForUser()))->getItemsFromModelSelected([$publicLink->getItemId()]));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$this->view->assign('nextAction', Acl::getActionRoute(ActionsInterface::ACCESS_MANAGE));
if ($this->view->isView === true) {
- $this->view->assign('publicLinkURL', PublicLinkRepository::getLinkForHash($publicLink->getHash()));
+ $this->view->assign('publicLinkURL', PublicLinkService::getLinkForHash($publicLink->getHash()));
$this->view->assign('disabled', 'disabled');
$this->view->assign('readonly', 'readonly');
} else {
@@ -220,6 +220,8 @@ class PublicLinkController extends ControllerBase implements CrudControllerInter
/**
* Saves create action
+ *
+ * @throws \SP\Core\Dic\ContainerException
*/
public function saveCreateAction()
{
diff --git a/app/modules/web/themes/material-blue/views/itemshow/apitoken.inc b/app/modules/web/themes/material-blue/views/itemshow/authtoken.inc
similarity index 97%
rename from app/modules/web/themes/material-blue/views/itemshow/apitoken.inc
rename to app/modules/web/themes/material-blue/views/itemshow/authtoken.inc
index 4554d080..04dcf906 100644
--- a/app/modules/web/themes/material-blue/views/itemshow/apitoken.inc
+++ b/app/modules/web/themes/material-blue/views/itemshow/authtoken.inc
@@ -1,5 +1,5 @@
+
+
+
diff --git a/lib/SP/Api/ApiBase.php b/lib/SP/Api/ApiBase.php
index b4c15fb5..09183e83 100644
--- a/lib/SP/Api/ApiBase.php
+++ b/lib/SP/Api/ApiBase.php
@@ -33,7 +33,7 @@ use SP\Core\Exceptions\InvalidArgumentException;
use SP\Core\Exceptions\SPException;
use SP\Core\SessionFactory;
use SP\Core\SessionUtil;
-use SP\DataModel\ApiTokenData;
+use SP\DataModel\AuthTokenData;
use SP\DataModel\UserLoginData;
use SP\Log\Log;
use SP\Mgmt\ApiTokens\ApiToken;
@@ -80,7 +80,7 @@ abstract class ApiBase implements ApiInterface
*/
protected $Log;
/**
- * @var ApiTokenData
+ * @var AuthTokenData
*/
protected $ApiTokenData;
diff --git a/lib/SP/Controller/ItemActionController.php b/lib/SP/Controller/ItemActionController.php
index f99074f8..4a74b002 100644
--- a/lib/SP/Controller/ItemActionController.php
+++ b/lib/SP/Controller/ItemActionController.php
@@ -39,7 +39,7 @@ use SP\DataModel\NoticeData;
use SP\DataModel\PluginData;
use SP\DataModel\PublicLinkData;
use SP\Forms\AccountForm;
-use SP\Forms\ApiTokenForm;
+use SP\Forms\AuthTokenForm;
use SP\Forms\CategoryForm;
use SP\Forms\ClientForm;
use SP\Forms\CustomFieldDefForm;
@@ -608,7 +608,7 @@ class ItemActionController implements ItemControllerInterface
*/
protected function tokenAction()
{
- $Form = new ApiTokenForm($this->itemId);
+ $Form = new AuthTokenForm($this->itemId);
$refresh = Request::analyze('refreshtoken', false, false, true);
diff --git a/lib/SP/Controller/ItemShowController.php b/lib/SP/Controller/ItemShowController.php
index e8a3fee6..5af5233a 100644
--- a/lib/SP/Controller/ItemShowController.php
+++ b/lib/SP/Controller/ItemShowController.php
@@ -38,7 +38,7 @@ use SP\Core\SessionFactory;
use SP\Core\SessionUtil;
use SP\Mvc\View\Template;
use SP\DataModel\AccountExtData;
-use SP\DataModel\ApiTokenData;
+use SP\DataModel\AuthTokenData;
use SP\DataModel\CategoryData;
use SP\DataModel\ClientData;
use SP\DataModel\CustomFieldData;
@@ -395,11 +395,11 @@ class ItemShowController extends ControllerBase implements ActionsInterface, Ite
$this->module = self::APITOKEN;
$this->view->addTemplate('tokens');
- $ApiTokenData = $this->itemId ? ApiToken::getItem()->getById($this->itemId) : new ApiTokenData();
+ $ApiTokenData = $this->itemId ? ApiToken::getItem()->getById($this->itemId) : new AuthTokenData();
$this->view->assign('users', User::getItem()->getItemsForSelect());
$this->view->assign('actions', ApiTokensUtil::getTokenActions());
- $this->view->assign('apiTokenData', $ApiTokenData);
+ $this->view->assign('authTokenData', $ApiTokenData);
$this->view->assign('isDisabled', ($this->view->actionId === self::APITOKEN_VIEW) ? 'disabled' : '');
$this->view->assign('isReadonly', $this->view->isDisabled ? 'readonly' : '');
diff --git a/lib/SP/Core/Crypt/Hash.php b/lib/SP/Core/Crypt/Hash.php
index b66ca454..837ade81 100644
--- a/lib/SP/Core/Crypt/Hash.php
+++ b/lib/SP/Core/Crypt/Hash.php
@@ -42,7 +42,6 @@ class Hash
* @param string $key con la clave a comprobar
* @param string $hash con el hash a comprobar
* @return bool
- * @throws \SP\Core\Exceptions\SPException
*/
public static function checkHashKey($key, $hash)
{
diff --git a/lib/SP/DataModel/ApiTokenData.php b/lib/SP/DataModel/AuthTokenData.php
similarity index 94%
rename from lib/SP/DataModel/ApiTokenData.php
rename to lib/SP/DataModel/AuthTokenData.php
index 9c418396..6081ee43 100644
--- a/lib/SP/DataModel/ApiTokenData.php
+++ b/lib/SP/DataModel/AuthTokenData.php
@@ -27,18 +27,18 @@ namespace SP\DataModel;
use SP\Core\Crypt\Vault;
/**
- * Class ApiTokenData
+ * Class AuthTokenData
*
* @package SP\DataModel
*/
-class ApiTokenData extends DataModelBase implements DataModelInterface
+class AuthTokenData extends DataModelBase implements DataModelInterface
{
/**
* @var int
*/
public $id;
/**
- * @var Vault
+ * @var string
*/
public $vault;
/**
@@ -83,7 +83,7 @@ class ApiTokenData extends DataModelBase implements DataModelInterface
}
/**
- * @return Vault
+ * @return string
*/
public function getVault()
{
@@ -95,7 +95,7 @@ class ApiTokenData extends DataModelBase implements DataModelInterface
*/
public function setVault(Vault $vault)
{
- $this->vault = $vault;
+ $this->vault = serialize($vault);
}
/**
diff --git a/lib/SP/DataModel/PublicLinkData.php b/lib/SP/DataModel/PublicLinkData.php
index e6cfa8de..969e94ac 100644
--- a/lib/SP/DataModel/PublicLinkData.php
+++ b/lib/SP/DataModel/PublicLinkData.php
@@ -78,7 +78,7 @@ class PublicLinkData extends DataModelBase implements DataModelInterface
*/
public $maxCountViews = 0;
/**
- * @var array|string
+ * @var string
*/
public $useInfo;
/**
@@ -271,15 +271,11 @@ class PublicLinkData extends DataModelBase implements DataModelInterface
}
/**
- * @return array
+ * @return string
*/
public function getUseInfo()
{
- if (is_string($this->useInfo)) {
- return unserialize($this->useInfo);
- }
-
- return (array)$this->useInfo;
+ return $this->useInfo;
}
/**
@@ -287,7 +283,7 @@ class PublicLinkData extends DataModelBase implements DataModelInterface
*/
public function setUseInfo(array $useInfo)
{
- $this->useInfo = $useInfo;
+ $this->useInfo = serialize($useInfo);
}
/**
diff --git a/lib/SP/Forms/ApiTokenForm.php b/lib/SP/Forms/AuthTokenForm.php
similarity index 64%
rename from lib/SP/Forms/ApiTokenForm.php
rename to lib/SP/Forms/AuthTokenForm.php
index 710c993e..50ead924 100644
--- a/lib/SP/Forms/ApiTokenForm.php
+++ b/lib/SP/Forms/AuthTokenForm.php
@@ -26,7 +26,7 @@ namespace SP\Forms;
use SP\Core\Acl\ActionsInterface;
use SP\Core\Exceptions\ValidationException;
-use SP\DataModel\ApiTokenData;
+use SP\DataModel\AuthTokenData;
use SP\Http\Request;
/**
@@ -34,18 +34,22 @@ use SP\Http\Request;
*
* @package SP\Forms
*/
-class ApiTokenForm extends FormBase implements FormInterface
+class AuthTokenForm extends FormBase implements FormInterface
{
/**
- * @var ApiTokenData
+ * @var AuthTokenData
*/
- protected $apiTokenData;
+ protected $authTokenData;
+ /**
+ * @var bool
+ */
+ protected $refresh = false;
/**
* Validar el formulario
*
* @param $action
- * @return ApiTokenForm
+ * @return AuthTokenForm
* @throws \SP\Core\Exceptions\ValidationException
*/
public function validate($action)
@@ -68,11 +72,13 @@ class ApiTokenForm extends FormBase implements FormInterface
*/
protected function analyzeRequestData()
{
- $this->apiTokenData = new ApiTokenData();
- $this->apiTokenData->setId($this->itemId);
- $this->apiTokenData->setUserId(Request::analyze('users', 0));
- $this->apiTokenData->setActionId(Request::analyze('actions', 0));
- $this->apiTokenData->setHash(Request::analyzeEncrypted('pass'));
+ $this->refresh = (bool)Request::analyze('refreshtoken', 0, false, 1);
+
+ $this->authTokenData = new AuthTokenData();
+ $this->authTokenData->setId($this->itemId);
+ $this->authTokenData->setUserId(Request::analyze('users', 0));
+ $this->authTokenData->setActionId(Request::analyze('actions', 0));
+ $this->authTokenData->setHash(Request::analyzeEncrypted('pass'));
}
/**
@@ -80,29 +86,38 @@ class ApiTokenForm extends FormBase implements FormInterface
*/
protected function checkCommon()
{
- if ($this->apiTokenData->getUserId() === 0) {
+ if ($this->authTokenData->getUserId() === 0) {
throw new ValidationException(__u('Usuario no indicado'));
}
- if ($this->apiTokenData->getActionId() === 0) {
+ if ($this->authTokenData->getActionId() === 0) {
throw new ValidationException(__u('Acción no indicada'));
}
- $action = $this->apiTokenData->getActionId();
+ $action = $this->authTokenData->getActionId();
if (($action === ActionsInterface::ACCOUNT_VIEW_PASS
- || $action === ActionsInterface::ACCOUNT_CREATE)
- && $this->apiTokenData->getHash() === ''
+ || $action === ActionsInterface::ACCOUNT_CREATE
+ || $this->isRefresh())
+ && $this->authTokenData->getHash() === ''
) {
throw new ValidationException(__u('La clave no puede estar en blanco'));
}
}
/**
- * @return ApiTokenData
+ * @return bool
+ */
+ public function isRefresh()
+ {
+ return $this->refresh;
+ }
+
+ /**
+ * @return AuthTokenData
*/
public function getItemData()
{
- return $this->apiTokenData;
+ return $this->authTokenData;
}
}
\ No newline at end of file
diff --git a/lib/SP/Forms/FormBase.php b/lib/SP/Forms/FormBase.php
index 1a506beb..acf41000 100644
--- a/lib/SP/Forms/FormBase.php
+++ b/lib/SP/Forms/FormBase.php
@@ -59,6 +59,7 @@ abstract class FormBase
* FormBase constructor.
*
* @param $itemId
+ * @throws \SP\Core\Dic\ContainerException
*/
public function __construct($itemId = null)
{
diff --git a/lib/SP/Forms/UserForm.php b/lib/SP/Forms/UserForm.php
index 03de0544..205df7dc 100644
--- a/lib/SP/Forms/UserForm.php
+++ b/lib/SP/Forms/UserForm.php
@@ -150,7 +150,7 @@ class UserForm extends FormBase implements FormInterface
throw new ValidationException(__u('La clave no puede estar en blanco'));
}
- if ($this->userData->getPass() !== $userPassR) {
+ if (!Hash::checkHashKey($userPassR, $this->userData->getPass())) {
throw new ValidationException(__u('Las claves no coinciden'));
}
}
diff --git a/lib/SP/Mgmt/ApiTokens/ApiToken.php b/lib/SP/Mgmt/ApiTokens/ApiToken.php
index dd8a5911..77dfd3b1 100644
--- a/lib/SP/Mgmt/ApiTokens/ApiToken.php
+++ b/lib/SP/Mgmt/ApiTokens/ApiToken.php
@@ -30,7 +30,7 @@ use SP\Core\Crypt\Session as CryptSession;
use SP\Core\Crypt\Vault;
use SP\Core\Exceptions\SPException;
use SP\Core\SessionFactory;
-use SP\DataModel\ApiTokenData;
+use SP\DataModel\AuthTokenData;
use SP\Mgmt\ItemInterface;
use SP\Mgmt\ItemTrait;
use SP\Storage\DbWrapper;
@@ -41,7 +41,7 @@ use SP\Util\Util;
* Class ApiToken
*
* @package SP\Mgmt\ApiTokens
- * @property ApiTokenData $itemData
+ * @property AuthTokenData $itemData
*/
class ApiToken extends ApiTokenBase implements ItemInterface
{
@@ -306,7 +306,7 @@ class ApiToken extends ApiTokenBase implements ItemInterface
/**
* @param $id int
- * @return ApiTokenData
+ * @return AuthTokenData
*/
public function getById($id)
{
@@ -405,7 +405,7 @@ class ApiToken extends ApiTokenBase implements ItemInterface
*
* @param $actionId int El id de la accion
* @param $token string El token de seguridad
- * @return false|ApiTokenData
+ * @return false|AuthTokenData
* @throws \SP\Core\Exceptions\SPException
*/
public function getTokenByToken($actionId, $token)
diff --git a/lib/SP/Mgmt/ApiTokens/ApiTokenBase.php b/lib/SP/Mgmt/ApiTokens/ApiTokenBase.php
index b62c6627..799a2223 100644
--- a/lib/SP/Mgmt/ApiTokens/ApiTokenBase.php
+++ b/lib/SP/Mgmt/ApiTokens/ApiTokenBase.php
@@ -27,7 +27,7 @@ namespace SP\Mgmt\ApiTokens;
defined('APP_ROOT') || die();
use SP\Core\Exceptions\InvalidClassException;
-use SP\DataModel\ApiTokenData;
+use SP\DataModel\AuthTokenData;
use SP\Mgmt\ItemBaseInterface;
use SP\Mgmt\ItemBaseTrait;
@@ -48,6 +48,6 @@ abstract class ApiTokenBase implements ItemBaseInterface
*/
protected function init()
{
- $this->setDataModel(ApiTokenData::class);
+ $this->setDataModel(AuthTokenData::class);
}
}
\ No newline at end of file
diff --git a/lib/SP/Repositories/Account/AccountHistoryRepository.php b/lib/SP/Repositories/Account/AccountHistoryRepository.php
index 071b5e38..93e73629 100644
--- a/lib/SP/Repositories/Account/AccountHistoryRepository.php
+++ b/lib/SP/Repositories/Account/AccountHistoryRepository.php
@@ -2,8 +2,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
@@ -123,7 +123,7 @@ class AccountHistoryRepository extends Repository implements RepositoryItemInter
/**
* Crea una nueva cuenta en la BBDD
*
- * @param array $itemData ['id' => , 'isDelete' => ]
+ * @param array $itemData ['id' => , 'isModify' => ,'isDelete' => , 'masterPassHash' => ]
* @return bool
* @throws QueryException
* @throws \SP\Core\Exceptions\ConstraintException
@@ -176,12 +176,12 @@ class AccountHistoryRepository extends Repository implements RepositoryItemInter
otherUserGroupEdit,
isPrivate,
isPrivateGroup,
- ?,?,? FROM Account WHERE id = ?';
+ ?,?,? FROM Account WHERE id = ?';
- $Data->setQuery($query . ' ' . $query);
- $Data->addParam(($itemData['isDelete'] === false) ? 1 : 0);
- $Data->addParam(($itemData['isDelete'] === true) ? 1 : 0);
- $Data->addParam(ConfigDB::getValue('masterPwd'));
+ $Data->setQuery($query);
+ $Data->addParam($itemData['isModify']);
+ $Data->addParam($itemData['isDelete']);
+ $Data->addParam($itemData['masterPassHash']);
$Data->addParam($itemData['id']);
$Data->setOnErrorMessage(__u('Error al actualizar el historial'));
@@ -208,11 +208,10 @@ class AccountHistoryRepository extends Repository implements RepositoryItemInter
*/
public function delete($id)
{
- $Data = new QueryData();
-
$query = /** @lang SQL */
'DELETE FROM AccountHistory WHERE id = ? LIMIT 1';
+ $Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($id);
$Data->setOnErrorMessage(__u('Error al eliminar la cuenta'));
@@ -265,17 +264,17 @@ class AccountHistoryRepository extends Repository implements RepositoryItemInter
AH.otherUserGroupEdit,
AH.isPrivate,
AH.isPrivateGroup,
- u1.name AS userName,
- u1.login AS userLogin,
+ U1.name AS userName,
+ U1.login AS userLogin,
UG.name AS userGroupName,
- u2.name AS useEditName,
- u2.login AS userEditLogin
+ U2.name AS useEditName,
+ U2.login AS userEditLogin
FROM AccountHistory AH
INNER JOIN Category C ON AH.categoryId = C.id
INNER JOIN Client C2 ON AH.clientId = C2.id
INNER JOIN UserGroup UG ON AH.userGroupId = UG.id
INNER JOIN User U1 ON AH.userId = U1.id
- LEFT JOIN User u2 ON AH.userEditId = U2.id
+ LEFT JOIN User U2 ON AH.userEditId = U2.id
WHERE AH.id = ? LIMIT 1';
$Data = new QueryData();
diff --git a/lib/SP/Repositories/ApiToken/ApiTokenRepository.php b/lib/SP/Repositories/AuthToken/AuthTokenRepository.php
similarity index 73%
rename from lib/SP/Repositories/ApiToken/ApiTokenRepository.php
rename to lib/SP/Repositories/AuthToken/AuthTokenRepository.php
index 0919f2c2..e5f6d97d 100644
--- a/lib/SP/Repositories/ApiToken/ApiTokenRepository.php
+++ b/lib/SP/Repositories/AuthToken/AuthTokenRepository.php
@@ -2,8 +2,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
@@ -22,29 +22,24 @@
* along with sysPass. If not, see .
*/
-namespace SP\Repositories\ApiToken;
+namespace SP\Repositories\AuthToken;
use SP\Core\Acl\Acl;
-use SP\Core\Acl\ActionsInterface;
-use SP\Core\Crypt\Hash;
-use SP\Core\Crypt\Session as CryptSession;
-use SP\Core\Crypt\Vault;
use SP\Core\Exceptions\SPException;
-use SP\DataModel\ApiTokenData;
+use SP\DataModel\AuthTokenData;
use SP\DataModel\ItemSearchData;
use SP\Repositories\Repository;
use SP\Repositories\RepositoryItemInterface;
use SP\Repositories\RepositoryItemTrait;
use SP\Storage\DbWrapper;
use SP\Storage\QueryData;
-use SP\Util\Util;
/**
- * Class ApiTokenRepository
+ * Class AuthTokenRepository
*
* @package SP\Repositories\ApiToken
*/
-class ApiTokenRepository extends Repository implements RepositoryItemInterface
+class AuthTokenRepository extends Repository implements RepositoryItemInterface
{
use RepositoryItemTrait;
@@ -90,7 +85,7 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
WHERE id = ? LIMIT 1';
$Data = new QueryData();
- $Data->setMapClassName(ApiTokenData::class);
+ $Data->setMapClassName(AuthTokenData::class);
$Data->setQuery($query);
$Data->addParam($id);
@@ -200,11 +195,9 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
/**
* Creates an item
*
- * @param ApiTokenData $itemData
+ * @param AuthTokenData $itemData
* @return mixed
* @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
@@ -228,22 +221,10 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
$Data->setQuery($query);
$Data->addParam($itemData->getUserId());
$Data->addParam($itemData->getActionId());
- $Data->addParam($this->session->getUserData()->getId());
-
- $token = $this->getTokenByUserId($itemData->getUserId());
- $Data->addParam($token);
-
- $action = $itemData->getActionId();
-
- if ($action === ActionsInterface::ACCOUNT_VIEW_PASS
- || $action === ActionsInterface::ACCOUNT_CREATE
- ) {
- $Data->addParam(serialize($this->getSecureData($token, $itemData)));
- } else {
- $Data->addParam(null);
- }
-
- $Data->addParam(Hash::hashKey($itemData->getHash()));
+ $Data->addParam($itemData->getCreatedBy());
+ $Data->addParam($itemData->getToken());
+ $Data->addParam($itemData->getVault());
+ $Data->addParam($itemData->getHash());
$Data->setOnErrorMessage(__u('Error interno'));
DbWrapper::getQuery($Data, $this->db);
@@ -254,7 +235,7 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
/**
* Checks whether the item is duplicated on adding
*
- * @param mixed $itemData
+ * @param AuthTokenData $itemData
* @return bool
*/
public function checkDuplicatedOnAdd($itemData)
@@ -266,8 +247,8 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam($itemData->getAuthtokenUserId());
- $Data->addParam($itemData->getAuthtokenActionId());
+ $Data->addParam($itemData->getUserId());
+ $Data->addParam($itemData->getActionId());
DbWrapper::getResults($Data, $this->db);
@@ -279,12 +260,11 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
*
* @param $id
* @return string
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
*/
- private function getTokenByUserId($id)
+ public function getTokenByUserId($id)
{
$query = /** @lang SQL */
- 'SELECT token FROM AuthToken WHERE userId = ? LIMIT 1';
+ 'SELECT token FROM AuthToken WHERE userId = ? AND token <> \'\' LIMIT 1';
$Data = new QueryData();
$Data->setQuery($query);
@@ -292,43 +272,15 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
$queryRes = DbWrapper::getResults($Data, $this->db);
- return $Data->getQueryNumRows() === 1 ? $queryRes->token : $this->generateToken();
- }
-
- /**
- * Generar un token de acceso
- *
- * @return string
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- */
- private function generateToken()
- {
- return Util::generateRandomBytes(32);
- }
-
- /**
- * Generar la llave segura del token
- *
- * @param string $token
- * @param ApiTokenData $itemData
- * @return Vault
- * @throws \Defuse\Crypto\Exception\CryptoException
- */
- private function getSecureData($token, ApiTokenData $itemData)
- {
- $Vault = new Vault();
- $Vault->saveData(CryptSession::getSessionKey(), $itemData->getHash() . $token);
-
- return $Vault;
+ return $Data->getQueryNumRows() === 1 ? $queryRes->token : null;
}
/**
* Updates an item
*
- * @param ApiTokenData $itemData
+ * @param AuthTokenData $itemData
* @return mixed
* @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
@@ -338,8 +290,6 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
throw new SPException(SPException::SP_WARNING, __u('La autorización ya existe'));
}
- $token = $this->getTokenByUserId($itemData->getUserId());
-
$query = /** @lang SQL */
'UPDATE AuthToken
SET userId = ?,
@@ -355,20 +305,10 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
$Data->setQuery($query);
$Data->addParam($itemData->getUserId());
$Data->addParam($itemData->getActionId());
- $Data->addParam($this->session->getUserData()->getId());
- $Data->addParam($token);
-
- $action = $itemData->getActionId();
-
- if ($action === ActionsInterface::ACCOUNT_VIEW_PASS
- || $action === ActionsInterface::ACCOUNT_CREATE
- ) {
- $Data->addParam(serialize($this->getSecureData($token, $itemData)));
- } else {
- $Data->addParam(null);
- }
-
- $Data->addParam(Hash::hashKey($itemData->getHash()));
+ $Data->addParam($itemData->getCreatedBy());
+ $Data->addParam($itemData->getToken());
+ $Data->addParam($itemData->getVault());
+ $Data->addParam($itemData->getHash());
$Data->addParam($itemData->getId());
$Data->setOnErrorMessage(__u('Error interno'));
@@ -378,7 +318,7 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
/**
* Checks whether the item is duplicated on updating
*
- * @param ApiTokenData $itemData
+ * @param AuthTokenData $itemData
* @return bool
*/
public function checkDuplicatedOnUpdate($itemData)
@@ -403,41 +343,53 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
/**
* Regenerar el hash de los tokens de un usuario
*
- * @param ApiTokenData $itemData
+ * @param int $id
+ * @param string $token
* @return bool
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function refreshToken(ApiTokenData $itemData)
+ public function refreshTokenByUserId($id, $token)
{
$query = /** @lang SQL */
'UPDATE AuthToken
SET token = ?,
- `hash` = ?,
- vault = ?,
startDate = UNIX_TIMESTAMP()
- WHERE userId = ? LIMIT 1';
+ WHERE userId = ?';
$Data = new QueryData();
$Data->setQuery($query);
-
- $token = $this->generateToken();
$Data->addParam($token);
- $Data->addParam(Hash::hashKey($itemData->getHash()));
+ $Data->addParam($id);
+ $Data->setOnErrorMessage(__u('Error interno'));
- $action = $itemData->getActionId();
+ return DbWrapper::getQuery($Data, $this->db);
+ }
- if ($action === ActionsInterface::ACCOUNT_VIEW_PASS
- || $action === ActionsInterface::ACCOUNT_CREATE
- ) {
- $Data->addParam(serialize($this->getSecureData($token, $itemData)));
- } else {
- $Data->addParam(null);
- }
+ /**
+ * Regenerar el hash de los tokens de un usuario
+ *
+ * @param int $id
+ * @param $vault
+ * @param $hash
+ * @return bool
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function refreshVaultByUserId($id, $vault, $hash)
+ {
+ $query = /** @lang SQL */
+ 'UPDATE AuthToken
+ SET vault = ?,
+ `hash` = ?,
+ startDate = UNIX_TIMESTAMP()
+ WHERE userId = ? AND vault IS NOT NULL';
- $Data->addParam($itemData->getUserId());
+ $Data = new QueryData();
+ $Data->setQuery($query);
+ $Data->addParam($vault);
+ $Data->addParam($hash);
+ $Data->addParam($id);
$Data->setOnErrorMessage(__u('Error interno'));
return DbWrapper::getQuery($Data, $this->db);
@@ -468,7 +420,7 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
*
* @param $actionId int El id de la accion
* @param $token string El token de seguridad
- * @return false|ApiTokenData
+ * @return false|AuthTokenData
*/
public function getTokenByToken($actionId, $token)
{
@@ -479,7 +431,7 @@ class ApiTokenRepository extends Repository implements RepositoryItemInterface
AND token = ? LIMIT 1';
$Data = new QueryData();
- $Data->setMapClassName(ApiTokenData::class);
+ $Data->setMapClassName(AuthTokenData::class);
$Data->setQuery($query);
$Data->addParam($actionId);
$Data->addParam($token);
diff --git a/lib/SP/Repositories/PublicLink/PublicLinkRepository.php b/lib/SP/Repositories/PublicLink/PublicLinkRepository.php
index 17e360c4..f5f1e73a 100644
--- a/lib/SP/Repositories/PublicLink/PublicLinkRepository.php
+++ b/lib/SP/Repositories/PublicLink/PublicLinkRepository.php
@@ -2,8 +2,8 @@
/**
* sysPass
*
- * @author nuxsmin
- * @link http://syspass.org
+ * @author nuxsmin
+ * @link http://syspass.org
* @copyright 2012-2018, Rubén Domínguez nuxsmin@$syspass.org
*
* This file is part of sysPass.
@@ -24,25 +24,15 @@
namespace SP\Repositories\PublicLink;
-use SP\Bootstrap;
-use SP\Config\Config;
-use SP\Core\Crypt\Crypt;
-use SP\Core\Crypt\Session as CryptSession;
-use SP\Core\Crypt\Vault;
use SP\Core\Exceptions\SPException;
use SP\DataModel\ItemSearchData;
use SP\DataModel\PublicLinkData;
use SP\DataModel\PublicLinkListData;
-use SP\Http\Request;
-use SP\Repositories\Account\AccountRepository;
use SP\Repositories\Repository;
use SP\Repositories\RepositoryItemInterface;
use SP\Repositories\RepositoryItemTrait;
use SP\Storage\DbWrapper;
use SP\Storage\QueryData;
-use SP\Util\Checks;
-use SP\Util\HttpUtil;
-use SP\Util\Util;
/**
* Class PublicLinkRepository
@@ -53,26 +43,6 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
{
use RepositoryItemTrait;
- /**
- * Returns an HTTP URL for given hash
- *
- * @param $hash
- * @return string
- */
- public static function getLinkForHash($hash)
- {
- return Bootstrap::$WEBURI . '/index.php?r=account/viewLink/' . $hash;
- }
-
- /**
- * Generar el hash para el enlace
- *
- * @return string
- */
- protected static function createLinkHash()
- {
- return hash('sha256', uniqid('sysPassPublicLink', true));
- }
/**
* Deletes an item
@@ -263,7 +233,6 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
* @param PublicLinkData $itemData
* @return int
* @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
@@ -289,12 +258,12 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$Data->setQuery($query);
$Data->addParam($itemData->getItemId());
$Data->addParam($itemData->getHash());
- $Data->addParam($this->getSecuredLinkData($itemData->getItemId(), self::getKeyForHash($this->config, $itemData)));
- $Data->addParam($this->session->getUserData()->getId());
+ $Data->addParam($itemData->getData());
+ $Data->addParam($itemData->getUserId());
$Data->addParam($itemData->getTypeId());
$Data->addParam((int)$itemData->isNotify());
- $Data->addParam(self::calcDateExpire($this->config));
- $Data->addParam($this->config->getConfigData()->getPublinksMaxViews());
+ $Data->addParam($itemData->getDateExpire());
+ $Data->addParam($itemData->getMaxCountViews());
$Data->setOnErrorMessage(__u('Error al crear enlace'));
DbWrapper::getQuery($Data, $this->db);
@@ -305,7 +274,7 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
/**
* Checks whether the item is duplicated on adding
*
- * @param mixed $itemData
+ * @param PublicLinkData $itemData
* @return bool
*/
public function checkDuplicatedOnAdd($itemData)
@@ -315,64 +284,13 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam($itemData->getPublicLinkItemId());
+ $Data->addParam($itemData->getItemId());
DbWrapper::getResults($Data, $this->db);
return ($Data->getQueryNumRows() === 1);
}
- /**
- * Obtener los datos de una cuenta y encriptarlos para el enlace
- *
- * @param int $itemId
- * @param string $linkKey
- * @return Vault
- * @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
- */
- protected function getSecuredLinkData($itemId, $linkKey)
- {
- // Obtener los datos de la cuenta
- $accountService = new AccountRepository();
- $accountData = $accountService->getDataForLink($itemId);
-
- // Desencriptar la clave de la cuenta
- $key = CryptSession::getSessionKey();
- $securedKey = Crypt::unlockSecuredKey($accountData->getKey(), $key);
- $accountData->setPass(Crypt::decrypt($accountData->getPass(), $securedKey, $key));
- $accountData->setKey(null);
-
- $vault = new Vault();
- return serialize($vault->saveData(serialize($accountData), $linkKey));
- }
-
- /**
- * @param Config $config
- * @param PublicLinkData $publicLinkData
- * @return string
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- */
- public static function getKeyForHash(Config $config, PublicLinkData $publicLinkData = null)
- {
- if (null !== $publicLinkData) {
- return $config->getConfigData()->getPasswordSalt() . $publicLinkData->getHash();
- }
-
- return $config->getConfigData()->getPasswordSalt() . Util::generateRandomBytes();
- }
-
- /**
- * Devolver el tiempo de caducidad del enlace
- *
- * @param Config $config
- * @return int
- */
- protected static function calcDateExpire(Config $config)
- {
- return time() + $config->getConfigData()->getPublinksMaxTime();
- }
-
/**
* Checks whether the item is duplicated on updating
*
@@ -388,16 +306,12 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
* Incrementar el contador de visitas de un enlace
*
* @param PublicLinkData $publicLinkData
- * @return void
+ * @return bool
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
public function addLinkView(PublicLinkData $publicLinkData)
{
- $useInfo = $publicLinkData->getUseInfo();
- $useInfo[] = self::getUseInfo($publicLinkData->getHash());
- $publicLinkData->setUseInfo($useInfo);
-
$query = /** @lang SQL */
'UPDATE PublicLink
SET countViews = countViews + 1,
@@ -407,42 +321,11 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam(serialize($publicLinkData->getUseInfo()));
+ $Data->addParam($publicLinkData->getUseInfo());
$Data->addParam($publicLinkData->getHash());
$Data->setOnErrorMessage(__u('Error al actualizar enlace'));
- DbWrapper::getQuery($Data, $this->db);
-
- // FIXME
-// $Log = new Log();
-// $LogMessage = $Log->getLogMessage();
-// $LogMessage->setAction(__u('Ver Enlace Público'));
-// $LogMessage->addDescription(__u('Enlace visualizado'));
-// $LogMessage->addDetails(__u('Tipo'), $publicLinkData->getPublicLinkTypeId());
-// $LogMessage->addDetails(__u('Cuenta'), AccountUtil::getAccountNameById($publicLinkData->getPublicLinkItemId()));
-// $LogMessage->addDetails(__u('Usuario'), UserUtil::getUserLoginById($publicLinkData->getPublicLinkUserId()));
-// $Log->writeLog();
-//
-// if ($publicLinkData->isPublicLinkNotify()) {
-// Email::sendEmail($LogMessage);
-// }
- }
-
- /**
- * Actualizar la información de uso
- *
- * @param $hash
- * @return array
- */
- protected static function getUseInfo($hash)
- {
- return [
- 'who' => HttpUtil::getClientAddress(true),
- 'time' => time(),
- 'hash' => $hash,
- 'agent' => Request::getRequestHeaders('HTTP_USER_AGENT'),
- 'https' => Checks::httpsEnabled()
- ];
+ return DbWrapper::getQuery($Data, $this->db);
}
/**
@@ -451,7 +334,6 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
* @param PublicLinkData $itemData
* @return mixed
* @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
@@ -469,10 +351,10 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$Data = new QueryData();
$Data->setQuery($query);
$Data->addParam($itemData->getHash());
- $Data->addParam($this->getSecuredLinkData($itemData->getItemId(), self::getKeyForHash($this->config, $itemData)));
+ $Data->addParam($itemData->getData());
$Data->addParam((int)$itemData->isNotify());
- $Data->addParam(self::calcDateExpire($this->config));
- $Data->addParam($this->config->getConfigData()->getPublinksMaxViews());
+ $Data->addParam($itemData->getDateExpire());
+ $Data->addParam($itemData->getMaxCountViews());
$Data->addParam($itemData->getId());
$Data->setOnErrorMessage(__u('Error al actualizar enlace'));
@@ -482,19 +364,14 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
/**
* Refreshes a public link
*
- * @param $id
+ * @param PublicLinkData $publicLinkData
* @return bool
* @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function refresh($id)
+ public function refresh(PublicLinkData $publicLinkData)
{
- $publicLinkData = $this->getById($id);
- $key = self::getKeyForHash($this->config);
-
$query = /** @lang SQL */
'UPDATE PublicLink
SET `hash` = ?,
@@ -506,11 +383,11 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam(self::getHashForKey($key, $this->config));
- $Data->addParam($this->getSecuredLinkData($publicLinkData->getItemId(), $key));
- $Data->addParam(self::calcDateExpire($this->config));
- $Data->addParam($this->config->getConfigData()->getPublinksMaxViews());
- $Data->addParam($id);
+ $Data->addParam($publicLinkData->getHash());
+ $Data->addParam($publicLinkData->getData());
+ $Data->addParam($publicLinkData->getDateExpire());
+ $Data->addParam($publicLinkData->getMaxCountViews());
+ $Data->addParam($publicLinkData->getId());
$Data->setOnErrorMessage(__u('Error al renovar enlace'));
return DbWrapper::getQuery($Data, $this->db);
@@ -561,18 +438,6 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
return $queryRes;
}
- /**
- * Returns the hash from a composed key
- *
- * @param string $key
- * @param Config $config
- * @return mixed
- */
- public static function getHashForKey($key, Config $config)
- {
- return str_replace($config->getConfigData()->getPasswordSalt(), '', $key);
- }
-
/**
* @param $hash string
* @return bool|PublicLinkData
@@ -609,7 +474,7 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
$Data->addParam($hash);
/** @var PublicLinkData $queryRes */
- $queryRes = DbWrapper::getResults($Data);
+ $queryRes = DbWrapper::getResults($Data, $this->db);
if ($queryRes === false) {
throw new SPException(SPException::SP_ERROR, __u('Error al obtener enlace'));
@@ -643,5 +508,4 @@ class PublicLinkRepository extends Repository implements RepositoryItemInterface
return $queryRes;
}
-
}
\ No newline at end of file
diff --git a/lib/SP/Repositories/User/UserRepository.php b/lib/SP/Repositories/User/UserRepository.php
index 8953b6c8..72f50181 100644
--- a/lib/SP/Repositories/User/UserRepository.php
+++ b/lib/SP/Repositories/User/UserRepository.php
@@ -118,17 +118,16 @@ class UserRepository extends Repository implements RepositoryItemInterface
$query = /** @lang SQL */
'SELECT login, email
FROM User
- WHERE (UPPER(login) = UPPER(?)
- OR UPPER(ssoLogin) = UPPER(?)
- OR UPPER(email) = UPPER(?))
- AND id <> ?';
+ WHERE id <> ? AND (UPPER(login) = UPPER(?)
+ OR (ssoLogin <> "" AND UPPER(ssoLogin) = UPPER(?))
+ OR UPPER(email) = UPPER(?))';
$Data = new QueryData();
$Data->setQuery($query);
+ $Data->addParam($itemData->getId());
$Data->addParam($itemData->getLogin());
$Data->addParam($itemData->getSsoLogin());
$Data->addParam($itemData->getEmail());
- $Data->addParam($itemData->getId());
DbWrapper::getQuery($Data, $this->db);
diff --git a/lib/SP/Repositories/UserGroup/UserGroupRepository.php b/lib/SP/Repositories/UserGroup/UserGroupRepository.php
index d26d4471..a954061d 100644
--- a/lib/SP/Repositories/UserGroup/UserGroupRepository.php
+++ b/lib/SP/Repositories/UserGroup/UserGroupRepository.php
@@ -65,7 +65,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
$Data->addParam($id);
$Data->setOnErrorMessage(__u('Error al eliminar el grupo'));
- DbWrapper::getQuery($Data);
+ DbWrapper::getQuery($Data, $this->db);
return $Data->getQueryNumRows();
}
@@ -85,24 +85,43 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
FROM User WHERE userGroupId = ?
UNION ALL
SELECT userGroupId
- FROM UserToUserGroup WHERE userGroupId = ?
- UNION ALL
- SELECT userGroupId
- FROM AccountToUserGroup WHERE userGroupId = ?
- UNION ALL
- SELECT userGroupId
FROM Account WHERE userGroupId = ?';
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam($id);
- $Data->addParam($id);
- $Data->addParam($id);
- $Data->addParam($id);
+ $Data->addParams(array_fill(0, 2, (int)$id));
- DbWrapper::getQuery($Data);
+ DbWrapper::getQuery($Data, $this->db);
- return ($Data->getQueryNumRows() > 1);
+ return $Data->getQueryNumRows() > 0;
+ }
+
+ /**
+ * Checks whether the item is in use or not
+ *
+ * @param $id int
+ * @return array
+ */
+ public function getUsage($id)
+ {
+ $query = /** @lang SQL */
+ 'SELECT userGroupId, "User" as ref
+ FROM User WHERE userGroupId = ?
+ UNION ALL
+ SELECT userGroupId, "UserGroup" as ref
+ FROM UserToUserGroup WHERE userGroupId = ?
+ UNION ALL
+ SELECT userGroupId, "AccountToUserGroup" as ref
+ FROM AccountToUserGroup WHERE userGroupId = ?
+ UNION ALL
+ SELECT userGroupId, "Account" as ref
+ FROM Account WHERE userGroupId = ?';
+
+ $Data = new QueryData();
+ $Data->setQuery($query);
+ $Data->addParams(array_fill(0, 4, (int)$id));
+
+ return DbWrapper::getResultsArray($Data, $this->db);
}
/**
@@ -121,7 +140,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
$Data->setQuery($query);
$Data->addParam($id);
- return DbWrapper::getResults($Data);
+ return DbWrapper::getResults($Data, $this->db);
}
/**
@@ -140,7 +159,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
$Data->setQuery($query);
$Data->addParam($name);
- return DbWrapper::getResults($Data);
+ return DbWrapper::getResults($Data, $this->db);
}
/**
@@ -180,14 +199,14 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
$Data->setQuery($query);
$Data->setParams($ids);
- return DbWrapper::getResultsArray($Data);
+ return DbWrapper::getResultsArray($Data, $this->db);
}
/**
* Deletes all the items for given ids
*
* @param array $ids
- * @return UserGroupRepository
+ * @return int
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
@@ -201,9 +220,9 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
$Data->setQuery($query);
$Data->setParams($ids);
- DbWrapper::getQuery($Data);
+ DbWrapper::getQuery($Data, $this->db);
- return $this;
+ return $Data->getQueryNumRows();
}
/**
@@ -244,7 +263,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
/**
* Creates an item
*
- * @param mixed $itemData
+ * @param UserGroupData $itemData
* @return int
* @throws SPException
* @throws \SP\Core\Exceptions\ConstraintException
@@ -261,8 +280,8 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam($itemData->getUsergroupName());
- $Data->addParam($itemData->getUsergroupDescription());
+ $Data->addParam($itemData->getName());
+ $Data->addParam($itemData->getDescription());
$Data->setOnErrorMessage(__u('Error al crear el grupo'));
DbWrapper::getQuery($Data, $this->db);
@@ -273,7 +292,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
/**
* Checks whether the item is duplicated on adding
*
- * @param mixed $itemData
+ * @param UserGroupData $itemData
* @return bool
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
@@ -281,12 +300,12 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
public function checkDuplicatedOnAdd($itemData)
{
$query = /** @lang SQL */
- 'SELECT name FROM UserGroup WHERE UPPER(name) = ?';
+ 'SELECT name FROM UserGroup WHERE UPPER(name) = UPPER(?)';
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam($itemData->getUsergroupName());
+ $Data->addParam($itemData->getName());
- DbWrapper::getQuery($Data);
+ DbWrapper::getQuery($Data, $this->db);
return $Data->getQueryNumRows() > 0;
}
@@ -294,7 +313,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
/**
* Updates an item
*
- * @param mixed $itemData
+ * @param UserGroupData $itemData
* @return mixed
* @throws SPException
* @throws \SP\Core\Exceptions\ConstraintException
@@ -311,12 +330,12 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam($itemData->getUsergroupName());
- $Data->addParam($itemData->getUsergroupDescription());
- $Data->addParam($itemData->getUsergroupId());
+ $Data->addParam($itemData->getName());
+ $Data->addParam($itemData->getDescription());
+ $Data->addParam($itemData->getId());
$Data->setOnErrorMessage(__u('Error al actualizar el grupo'));
- DbWrapper::getQuery($Data);
+ DbWrapper::getQuery($Data, $this->db);
return $this;
}
@@ -324,7 +343,7 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
/**
* Checks whether the item is duplicated on updating
*
- * @param mixed $itemData
+ * @param UserGroupData $itemData
* @return bool
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
@@ -332,13 +351,13 @@ class UserGroupRepository extends Repository implements RepositoryItemInterface
public function checkDuplicatedOnUpdate($itemData)
{
$query = /** @lang SQL */
- 'SELECT name FROM UserGroup WHERE UPPER(name) = ? AND id <> ?';
+ 'SELECT name FROM UserGroup WHERE UPPER(name) = UPPER(?) AND id <> ?';
$Data = new QueryData();
$Data->setQuery($query);
- $Data->addParam($itemData->getUsergroupName());
- $Data->addParam($itemData->getUsergroupId());
+ $Data->addParam($itemData->getName());
+ $Data->addParam($itemData->getId());
- DbWrapper::getQuery($Data);
+ DbWrapper::getQuery($Data, $this->db);
return $Data->getQueryNumRows() > 0;
}
diff --git a/lib/SP/Services/Account/AccountHistoryService.php b/lib/SP/Services/Account/AccountHistoryService.php
new file mode 100644
index 00000000..7c318e23
--- /dev/null
+++ b/lib/SP/Services/Account/AccountHistoryService.php
@@ -0,0 +1,77 @@
+.
+ */
+
+namespace SP\Services\Account;
+
+use SP\Core\Exceptions\SPException;
+use SP\Core\Traits\InjectableTrait;
+use SP\DataModel\AccountHistoryData;
+use SP\Repositories\Account\AccountHistoryRepository;
+
+/**
+ * Class AccountHistoryService
+ *
+ * @package SP\Services\Account
+ */
+class AccountHistoryService
+{
+ use InjectableTrait;
+
+ /**
+ * @var AccountHistoryRepository
+ */
+ protected $accountHistoryRepository;
+
+ /**
+ * AccountHistoryService constructor.
+ *
+ * @throws \SP\Core\Dic\ContainerException
+ */
+ public function __construct()
+ {
+ $this->injectDependencies();
+ }
+
+ /**
+ * @param AccountHistoryRepository $accountHistoryRepository
+ */
+ public function inject(AccountHistoryRepository $accountHistoryRepository)
+ {
+ $this->accountHistoryRepository = $accountHistoryRepository;
+ }
+
+ /**
+ * Returns the item for given id
+ *
+ * @param int $id
+ * @return AccountHistoryData
+ * @throws SPException
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function getById($id)
+ {
+ return $this->accountHistoryRepository->getById($id);
+ }
+
+}
\ No newline at end of file
diff --git a/lib/SP/Services/Account/AccountService.php b/lib/SP/Services/Account/AccountService.php
index d0ddf935..01352195 100644
--- a/lib/SP/Services/Account/AccountService.php
+++ b/lib/SP/Services/Account/AccountService.php
@@ -43,6 +43,7 @@ use SP\Repositories\Account\AccountToTagRepository;
use SP\Repositories\Account\AccountToUserGroupRepository;
use SP\Repositories\Account\AccountToUserRepository;
use SP\Core\Crypt\Session as CryptSession;
+use SP\Services\Config\ConfigService;
use SP\Services\ServiceItemTrait;
/**
@@ -185,6 +186,7 @@ class AccountService implements AccountServiceInterface
* @return int
* @throws QueryException
* @throws SPException
+ * @throws \SP\Core\Dic\ContainerException
* @throws \SP\Core\Exceptions\ConstraintException
*/
public function create(AccountRequest $accountRequest)
@@ -262,6 +264,7 @@ class AccountService implements AccountServiceInterface
*
* @param AccountRequest $accountRequest
* @throws SPException
+ * @throws \SP\Core\Dic\ContainerException
*/
public function update(AccountRequest $accountRequest)
{
@@ -277,15 +280,19 @@ class AccountService implements AccountServiceInterface
/**
* @param int $accountId
* @param bool $isDelete
+ * @return bool
* @throws QueryException
+ * @throws \SP\Core\Dic\ContainerException
* @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Services\Config\ParameterNotFoundException
*/
protected function addHistory($accountId, $isDelete = false)
{
- $accountHistoryRepository = new AccountHistoryRepository();
- $accountHistoryRepository->create([
+ return (new AccountHistoryRepository())->create([
'id' => $accountId,
- 'isDelete' => $isDelete
+ 'isDelete' => (int)$isDelete,
+ 'isModify' => (int)!$isDelete,
+ 'masterPassHash' => (new ConfigService())->getByParam('masterPwd')
]);
}
@@ -312,7 +319,9 @@ class AccountService implements AccountServiceInterface
* @param AccountRequest $accountRequest
* @throws QueryException
* @throws SPException
+ * @throws \SP\Core\Dic\ContainerException
* @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Services\Config\ParameterNotFoundException
*/
public function editPassword(AccountRequest $accountRequest)
{
@@ -330,7 +339,9 @@ class AccountService implements AccountServiceInterface
* @param $historyId
* @param $accountId
* @throws QueryException
+ * @throws \SP\Core\Dic\ContainerException
* @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Services\Config\ParameterNotFoundException
*/
public function editRestore($historyId, $accountId)
{
diff --git a/lib/SP/Services/ApiToken/ApiTokenService.php b/lib/SP/Services/ApiToken/ApiTokenService.php
deleted file mode 100644
index dd2c868d..00000000
--- a/lib/SP/Services/ApiToken/ApiTokenService.php
+++ /dev/null
@@ -1,135 +0,0 @@
-.
- */
-
-namespace SP\Services\ApiToken;
-
-use SP\Core\Exceptions\SPException;
-use SP\Core\Traits\InjectableTrait;
-use SP\DataModel\ItemSearchData;
-use SP\Repositories\ApiToken\ApiTokenRepository;
-use SP\Services\ServiceItemTrait;
-
-/**
- * Class ApiTokenService
- *
- * @package SP\Services\ApiToken
- */
-class ApiTokenService
-{
- use InjectableTrait;
- use ServiceItemTrait;
-
- /**
- * @var ApiTokenRepository
- */
- protected $apiTokenRepository;
-
- /**
- * CategoryService constructor.
- *
- * @throws \SP\Core\Dic\ContainerException
- */
- public function __construct()
- {
- $this->injectDependencies();
- }
-
- /**
- * @param ApiTokenRepository $apiTokenRepository
- */
- public function inject(ApiTokenRepository $apiTokenRepository)
- {
- $this->apiTokenRepository = $apiTokenRepository;
- }
-
- /**
- * @param ItemSearchData $itemSearchData
- * @return mixed
- */
- public function search(ItemSearchData $itemSearchData)
- {
- return $this->apiTokenRepository->search($itemSearchData);
- }
-
- /**
- * @param $id
- * @return mixed
- */
- public function getById($id)
- {
- return $this->apiTokenRepository->getById($id);
- }
-
- /**
- * @param $id
- * @return ApiTokenService
- * @throws SPException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- public function delete($id)
- {
- if ($this->apiTokenRepository->delete($id) === 0) {
- throw new SPException(SPException::SP_INFO, __u('Token no encontrado'));
- }
-
- return $this;
- }
-
- /**
- * @param $itemData
- * @return mixed
- * @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- public function create($itemData)
- {
- return $this->apiTokenRepository->create($itemData);
- }
-
- /**
- * @param $itemData
- * @return mixed
- * @throws SPException
- * @throws \Defuse\Crypto\Exception\CryptoException
- * @throws \SP\Core\Exceptions\ConstraintException
- * @throws \SP\Core\Exceptions\QueryException
- */
- public function update($itemData)
- {
- return $this->apiTokenRepository->update($itemData);
- }
-
-
- /**
- * @return array
- */
- public function getAllBasic()
- {
- return $this->apiTokenRepository->getAll();
- }
-}
\ No newline at end of file
diff --git a/lib/SP/Services/AuthToken/AuthTokenService.php b/lib/SP/Services/AuthToken/AuthTokenService.php
new file mode 100644
index 00000000..1fd79d94
--- /dev/null
+++ b/lib/SP/Services/AuthToken/AuthTokenService.php
@@ -0,0 +1,228 @@
+.
+ */
+
+namespace SP\Services\AuthToken;
+
+use SP\Core\Acl\ActionsInterface;
+use SP\Core\Crypt\Hash;
+use SP\Core\Crypt\Vault;
+use SP\Core\Exceptions\SPException;
+use SP\Core\Session\Session;
+use SP\Core\Traits\InjectableTrait;
+use SP\DataModel\AuthTokenData;
+use SP\DataModel\ItemSearchData;
+use SP\Repositories\AuthToken\AuthTokenRepository;
+use SP\Services\ServiceItemTrait;
+use SP\Core\Crypt\Session as CryptSession;
+use SP\Util\Util;
+
+/**
+ * Class AuthTokenService
+ *
+ * @package SP\Services\AuthToken
+ */
+class AuthTokenService
+{
+ use InjectableTrait;
+ use ServiceItemTrait;
+
+ /**
+ * @var AuthTokenRepository
+ */
+ protected $authTokenRepository;
+ /**
+ * @var Session
+ */
+ protected $session;
+
+ /**
+ * CategoryService constructor.
+ *
+ * @throws \SP\Core\Dic\ContainerException
+ */
+ public function __construct()
+ {
+ $this->injectDependencies();
+ }
+
+ /**
+ * @param AuthTokenRepository $apiTokenRepository
+ * @param Session $session
+ */
+ public function inject(AuthTokenRepository $apiTokenRepository, Session $session)
+ {
+ $this->authTokenRepository = $apiTokenRepository;
+ $this->session = $session;
+ }
+
+ /**
+ * @param ItemSearchData $itemSearchData
+ * @return mixed
+ */
+ public function search(ItemSearchData $itemSearchData)
+ {
+ return $this->authTokenRepository->search($itemSearchData);
+ }
+
+ /**
+ * @param $id
+ * @return mixed
+ */
+ public function getById($id)
+ {
+ return $this->authTokenRepository->getById($id);
+ }
+
+ /**
+ * @param $id
+ * @return AuthTokenService
+ * @throws SPException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function delete($id)
+ {
+ if ($this->authTokenRepository->delete($id) === 0) {
+ throw new SPException(SPException::SP_INFO, __u('Token no encontrado'));
+ }
+
+ return $this;
+ }
+
+ /**
+ * @param $itemData
+ * @return mixed
+ * @throws SPException
+ * @throws \Defuse\Crypto\Exception\CryptoException
+ * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function create($itemData)
+ {
+ $this->injectSecureData($itemData);
+
+ return $this->authTokenRepository->create($itemData);
+ }
+
+ /**
+ * Injects secure data for token
+ *
+ * @param AuthTokenData $authTokenData
+ * @param string $token
+ * @throws \Defuse\Crypto\Exception\CryptoException
+ * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
+ */
+ private function injectSecureData(AuthTokenData $authTokenData, $token = null)
+ {
+ if ($token === null) {
+ $token = $this->authTokenRepository->getTokenByUserId($authTokenData->getUserId()) ?: $this->generateToken();
+ }
+
+ $action = $authTokenData->getActionId();
+
+ if ($action === ActionsInterface::ACCOUNT_VIEW_PASS
+ || $action === ActionsInterface::ACCOUNT_CREATE
+ ) {
+ $authTokenData->setHash(Hash::hashKey($authTokenData->getHash()));
+ $authTokenData->setVault($this->getSecureData($token, $authTokenData->getHash()));
+ } else {
+ $authTokenData->setHash(null);
+ }
+
+ $authTokenData->setToken($token);
+ $authTokenData->setCreatedBy($this->session->getUserData()->getId());
+ }
+
+ /**
+ * Generar un token de acceso
+ *
+ * @return string
+ * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
+ */
+ private function generateToken()
+ {
+ return Util::generateRandomBytes(32);
+ }
+
+ /**
+ * Generar la llave segura del token
+ *
+ * @param string $token
+ * @param string $hash
+ * @return Vault
+ * @throws \Defuse\Crypto\Exception\CryptoException
+ */
+ private function getSecureData($token, $hash)
+ {
+ $Vault = new Vault();
+ $Vault->saveData(CryptSession::getSessionKey(), $hash . $token);
+
+ return $Vault;
+ }
+
+ /**
+ * @param AuthTokenData $itemData
+ * @return mixed
+ * @throws SPException
+ * @throws \Defuse\Crypto\Exception\CryptoException
+ * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function refreshAndUpdate(AuthTokenData $itemData)
+ {
+ $token = $this->generateToken();
+ $vault = serialize($this->getSecureData($token, $itemData->getHash()));
+
+ $this->authTokenRepository->refreshTokenByUserId($itemData->getUserId(), $token);
+ $this->authTokenRepository->refreshVaultByUserId($itemData->getUserId(), $vault, Hash::hashKey($itemData->getHash()));
+
+ return $this->update($itemData, $token);
+ }
+
+ /**
+ * @param AuthTokenData $itemData
+ * @param string $token
+ * @return mixed
+ * @throws SPException
+ * @throws \Defuse\Crypto\Exception\CryptoException
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function update(AuthTokenData $itemData, $token = null)
+ {
+ $this->injectSecureData($itemData, $token);
+
+ return $this->authTokenRepository->update($itemData);
+ }
+
+ /**
+ * @return array
+ */
+ public function getAllBasic()
+ {
+ return $this->authTokenRepository->getAll();
+ }
+}
\ No newline at end of file
diff --git a/lib/SP/Services/Config/ConfigService.php b/lib/SP/Services/Config/ConfigService.php
index 38c1b818..fa3c9160 100644
--- a/lib/SP/Services/Config/ConfigService.php
+++ b/lib/SP/Services/Config/ConfigService.php
@@ -27,6 +27,7 @@ namespace SP\Services\Config;
use SP\Core\Exceptions\ConstraintException;
use SP\Core\Exceptions\QueryException;
use SP\Core\Exceptions\SPException;
+use SP\Core\Traits\InjectableTrait;
use SP\DataModel\ConfigData;
use SP\DataModel\Dto\ConfigRequest;
use SP\Repositories\Config\ConfigRepository;
@@ -39,6 +40,8 @@ use SP\Services\ServiceException;
*/
class ConfigService
{
+ use InjectableTrait;
+
/**
* @var ConfigRepository
*/
@@ -47,9 +50,17 @@ class ConfigService
/**
* ConfigService constructor.
*
+ * @throws \SP\Core\Dic\ContainerException
+ */
+ public function __construct()
+ {
+ $this->injectDependencies();
+ }
+
+ /**
* @param ConfigRepository $configRepository
*/
- public function __construct(ConfigRepository $configRepository)
+ public function inject(ConfigRepository $configRepository)
{
$this->configRepository = $configRepository;
}
diff --git a/lib/SP/Services/PublicLink/PublicLinkService.php b/lib/SP/Services/PublicLink/PublicLinkService.php
index e28cbf0b..a071c6fd 100644
--- a/lib/SP/Services/PublicLink/PublicLinkService.php
+++ b/lib/SP/Services/PublicLink/PublicLinkService.php
@@ -24,11 +24,23 @@
namespace SP\Services\PublicLink;
+use SP\Bootstrap;
+use SP\Config\Config;
+use SP\Core\Crypt\Crypt;
+use SP\Core\Crypt\Vault;
use SP\Core\Exceptions\SPException;
+use SP\Core\Session\Session;
use SP\Core\Traits\InjectableTrait;
use SP\DataModel\ItemSearchData;
+use SP\DataModel\PublicLinkData;
+use SP\Http\Request;
+use SP\Repositories\Account\AccountRepository;
use SP\Repositories\PublicLink\PublicLinkRepository;
use SP\Services\ServiceItemTrait;
+use SP\Core\Crypt\Session as CryptSession;
+use SP\Util\Checks;
+use SP\Util\HttpUtil;
+use SP\Util\Util;
/**
* Class PublicLinkService
@@ -44,6 +56,14 @@ class PublicLinkService
* @var PublicLinkRepository
*/
protected $publicLinkRepository;
+ /**
+ * @var Config
+ */
+ protected $config;
+ /**
+ * @var Session
+ */
+ protected $session;
/**
* CategoryService constructor.
@@ -56,11 +76,36 @@ class PublicLinkService
}
/**
- * @param PublicLinkRepository $publicLinkRepository
+ * Returns an HTTP URL for given hash
+ *
+ * @param $hash
+ * @return string
*/
- public function inject(PublicLinkRepository $publicLinkRepository)
+ public static function getLinkForHash($hash)
+ {
+ return Bootstrap::$WEBURI . '/index.php?r=account/viewLink/' . $hash;
+ }
+
+ /**
+ * Generar el hash para el enlace
+ *
+ * @return string
+ */
+ public static function createLinkHash()
+ {
+ return hash('sha256', uniqid('sysPassPublicLink', true));
+ }
+
+ /**
+ * @param PublicLinkRepository $publicLinkRepository
+ * @param Config $config
+ * @param Session $session
+ */
+ public function inject(PublicLinkRepository $publicLinkRepository, Config $config, Session $session)
{
$this->publicLinkRepository = $publicLinkRepository;
+ $this->config = $config;
+ $this->session = $session;
}
/**
@@ -93,7 +138,73 @@ class PublicLinkService
*/
public function refresh($id)
{
- return $this->publicLinkRepository->refresh($id);
+ $salt = $this->config->getConfigData()->getPasswordSalt();
+ $key = self::getNewKey($salt);
+
+ $publicLinkData = $this->publicLinkRepository->getById($id);
+ $publicLinkData->setHash(self::getHashForKey($key, $salt));
+ $publicLinkData->setData($this->getSecuredLinkData($publicLinkData->getItemId(), $key));
+ $publicLinkData->setDateExpire(self::calcDateExpire($this->config));
+ $publicLinkData->setCountViews($this->config->getConfigData()->getPublinksMaxViews());
+
+ return $this->publicLinkRepository->refresh($publicLinkData);
+ }
+
+ /**
+ * @param string $salt
+ * @return string
+ * @throws \Defuse\Crypto\Exception\EnvironmentIsBrokenException
+ */
+ public static function getNewKey($salt)
+ {
+ return $salt . Util::generateRandomBytes();
+ }
+
+ /**
+ * Returns the hash from a composed key
+ *
+ * @param string $key
+ * @return mixed
+ */
+ public static function getHashForKey($key, $salt)
+ {
+ return str_replace($salt, '', $key);
+ }
+
+ /**
+ * Obtener los datos de una cuenta y encriptarlos para el enlace
+ *
+ * @param int $itemId
+ * @param string $linkKey
+ * @return Vault
+ * @throws SPException
+ * @throws \Defuse\Crypto\Exception\CryptoException
+ */
+ protected function getSecuredLinkData($itemId, $linkKey)
+ {
+ // Obtener los datos de la cuenta
+ $accountService = new AccountRepository();
+ $accountData = $accountService->getDataForLink($itemId);
+
+ // Desencriptar la clave de la cuenta
+ $key = CryptSession::getSessionKey();
+ $securedKey = Crypt::unlockSecuredKey($accountData->getKey(), $key);
+ $accountData->setPass(Crypt::decrypt($accountData->getPass(), $securedKey, $key));
+ $accountData->setKey(null);
+
+ $vault = new Vault();
+ return serialize($vault->saveData(serialize($accountData), $linkKey));
+ }
+
+ /**
+ * Devolver el tiempo de caducidad del enlace
+ *
+ * @param Config $config
+ * @return int
+ */
+ public static function calcDateExpire(Config $config)
+ {
+ return time() + $config->getConfigData()->getPublinksMaxTime();
}
/**
@@ -113,18 +224,33 @@ class PublicLinkService
}
/**
- * @param $itemData
+ * @param PublicLinkData $itemData
* @return int
* @throws SPException
* @throws \Defuse\Crypto\Exception\CryptoException
* @throws \SP\Core\Exceptions\ConstraintException
* @throws \SP\Core\Exceptions\QueryException
*/
- public function create($itemData)
+ public function create(PublicLinkData $itemData)
{
+ $itemData->setData($this->getSecuredLinkData($itemData->getItemId(), self::getKeyForHash($this->config->getConfigData()->getPasswordSalt(), $itemData)));
+ $itemData->setDateExpire(self::calcDateExpire($this->config));
+ $itemData->setMaxCountViews($this->config->getConfigData()->getPublinksMaxViews());
+ $itemData->setUserId($this->session->getUserData()->getId());
+
return $this->publicLinkRepository->create($itemData);
}
+ /**
+ * @param string $salt
+ * @param PublicLinkData $publicLinkData
+ * @return string
+ */
+ public static function getKeyForHash($salt, PublicLinkData $publicLinkData)
+ {
+ return $salt . $publicLinkData->getHash();
+ }
+
/**
* Get all items from the service's repository
*
@@ -134,4 +260,63 @@ class PublicLinkService
{
return $this->publicLinkRepository->getAll();
}
+
+ /**
+ * Incrementar el contador de visitas de un enlace
+ *
+ * @param PublicLinkData $publicLinkData
+ * @return bool
+ * @throws \SP\Core\Exceptions\ConstraintException
+ * @throws \SP\Core\Exceptions\QueryException
+ */
+ public function addLinkView(PublicLinkData $publicLinkData)
+ {
+ /** @var array $useInfo */
+ $useInfo = serialize($publicLinkData->getUseInfo());
+ $useInfo[] = self::getUseInfo($publicLinkData->getHash());
+ $publicLinkData->setUseInfo($useInfo);
+
+ // FIXME
+// $Log = new Log();
+// $LogMessage = $Log->getLogMessage();
+// $LogMessage->setAction(__u('Ver Enlace Público'));
+// $LogMessage->addDescription(__u('Enlace visualizado'));
+// $LogMessage->addDetails(__u('Tipo'), $publicLinkData->getPublicLinkTypeId());
+// $LogMessage->addDetails(__u('Cuenta'), AccountUtil::getAccountNameById($publicLinkData->getPublicLinkItemId()));
+// $LogMessage->addDetails(__u('Usuario'), UserUtil::getUserLoginById($publicLinkData->getPublicLinkUserId()));
+// $Log->writeLog();
+//
+// if ($publicLinkData->isPublicLinkNotify()) {
+// Email::sendEmail($LogMessage);
+// }
+
+ return $this->publicLinkRepository->addLinkView($publicLinkData);
+ }
+
+ /**
+ * Actualizar la información de uso
+ *
+ * @param $hash
+ * @return array
+ */
+ public static function getUseInfo($hash)
+ {
+ return [
+ 'who' => HttpUtil::getClientAddress(true),
+ 'time' => time(),
+ 'hash' => $hash,
+ 'agent' => Request::getRequestHeaders('HTTP_USER_AGENT'),
+ 'https' => Checks::httpsEnabled()
+ ];
+ }
+
+ /**
+ * @param $hash string
+ * @return bool|PublicLinkData
+ * @throws \SP\Core\Exceptions\SPException
+ */
+ public function getByHash($hash)
+ {
+ return $this->publicLinkRepository->getByHash($hash);
+ }
}
\ No newline at end of file
diff --git a/lib/SP/Storage/Database.php b/lib/SP/Storage/Database.php
index 285e055c..e5197457 100644
--- a/lib/SP/Storage/Database.php
+++ b/lib/SP/Storage/Database.php
@@ -176,7 +176,7 @@ class Database implements DatabaseInterface
$stmt->bindValue($param, $value, PDO::PARAM_INT);
} else {
// error_log("STR: " . $param . " -> " . print_r($value, true));
- $stmt->bindValue($param, $value, PDO::PARAM_STR);
+ $stmt->bindValue($param, $value);
}
$paramIndex++;
diff --git a/public/css/css.php b/public/css/css.php
index e72e137a..45a7966a 100644
--- a/public/css/css.php
+++ b/public/css/css.php
@@ -25,7 +25,7 @@
use SP\Html\Minify;
use SP\Http\Request;
-define('APP_ROOT', realpath(__DIR__ . '/../../'));
+define('APP_ROOT', dirname(dirname(__DIR__)));
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'Base.php';
diff --git a/public/js/app-actions.js b/public/js/app-actions.js
index 939851ad..a6e6c9ef 100644
--- a/public/js/app-actions.js
+++ b/public/js/app-actions.js
@@ -175,12 +175,12 @@ sysPass.Actions = function (Common) {
$boxPopup.find(":input:text:visible:first").focus();
- if (typeof callback.open === "function") {
+ if (callback !== undefined && typeof callback.open === "function") {
callback.open();
}
},
close: function () {
- if (typeof callback.close === "function") {
+ if (callback !== undefined && typeof callback.close === "function") {
callback.close();
}
}
@@ -932,12 +932,13 @@ sysPass.Actions = function (Common) {
var parentId = $obj.data("parent-id");
var id = parentId === 0 ? $obj.data("item-id") : parentId;
+ var history = $obj.data("history") || 0;
var opts = Common.appRequests().getRequestOpts();
opts.url = ajaxUrl.entrypoint;
opts.method = "get";
opts.data = {
- r: $obj.data("action-route") + "/" + id + "/" + $obj.data("history"),
+ r: $obj.data("action-route") + "/" + id + "/" + history,
sk: Common.sk.get(),
isAjax: 1
};
diff --git a/public/js/app-actions.min.js b/public/js/app-actions.min.js
index 58d14803..f440f1d2 100644
--- a/public/js/app-actions.min.js
+++ b/public/js/app-actions.min.js
@@ -5,18 +5,18 @@ sysPass.Actions=function(c){var e=c.log,h=0,f={entrypoint:"/index.php",doAction:
"export":"/ajax/ajax_configSave.php","import":"/ajax/ajax_configSave.php"},file:"/ajax/ajax_filesMgmt.php",link:"/index.php",plugin:"/ajax/ajax_itemSave.php",account:{save:"/index.php",saveFavorite:"/ajax/ajax_itemSave.php",request:"/ajax/ajax_itemSave.php",getFiles:"/index.php",search:"/index.php?r=account/search"},appMgmt:{show:"/index.php",save:"/index.php",search:"/index.php"},eventlog:"/ajax/ajax_eventlog.php",wiki:{show:"/ajax/ajax_wiki.php"},notice:{show:"/ajax/ajax_noticeShow.php",search:"/ajax/ajax_noticeSearch.php"}};
Object.freeze(f);var k=function(a,b){var d={r:a.r+(void 0!==a.itemId?"/"+a.itemId:""),isAjax:1},g=c.appRequests().getRequestOpts();g.url=f.doAction;g.method="get";g.type="html";g.addHistory=!0;g.data=d;c.appRequests().getActionCall(g,function(a){var d=$("#content");d.empty().html(a);a=c.triggers().views;a.common(d);if(void 0!==b&&"function"===typeof a[b])a[b]();d=$(".mdl-layout__content");0