* [ADD] New classes to improve performance and code readability.

* [ADD] Security enhancement for master password in session.
* [MOD] Minor UI tweaks.
* [MOD] Improved config handling.
* [MOD] Code cleaning.
* [FIX] Accounts' main group were not set when the user hadn't enough privileges.
* [FIX] Accounts restoration didn't restore the account's main group.
This commit is contained in:
nuxsmin
2015-10-06 19:27:49 +02:00
parent e6d2d6a34d
commit 8538ba3dfc
86 changed files with 2526 additions and 2005 deletions

View File

@@ -1,4 +1,14 @@
=== ** v1.2.0.0-rc4 ===
=== ** v1.2.0.05-rc5 ===
* [ADD] New classes to improve performance and code readability.
* [ADD] Security enhancement for master password in session.
* [MOD] Minor UI tweaks.
* [MOD] Improved config handling.
* [MOD] Code cleaning.
* [FIX] Accounts' main group were not set when the user hadn't enough privileges.
* [FIX] Accounts restoration didn't restore the account's main group.
=== ** v1.2.0.04-rc4 ===
* [ADD] New copy-to-clipboard using only Javascript NO flash needed (gooood).
* [ADD] New method to optimize/minimize CSS and JS files.
@@ -21,18 +31,18 @@
* [FIX] Fixed issue while retrieving the public key when no session is active from Javascript to sign.
* [FIX] Fixed language detection issue.
=== ** v1.2.0.0-rc3 ===
=== ** v1.2.0.03-rc3 ===
* [ADD] New user preferences available
* [MOD] CSS fonts are now stored locally for Material Blue theme
=== ** v1.2.0.0-rc2 ===
=== ** v1.2.0.02-rc2 ===
* [ADD] Switched to BCRYPT for hashing passwords and key derivation. WARNING: Master password should be reentered by users (you can use a temporary password)
* [MOD] Some tweaks on forms passwords decryption
* [FIX] Fixed issue when blank custom fields are retrieved for an item.
=== ** v1.2.0.0-rc1 ===
=== ** v1.2.0.01-rc1 ===
* [ADD] Security improvements preventing common threats (SQL Injection, XSS, CSRF)
* [ADD] Fully MVC

View File

@@ -1,4 +1,14 @@
=== ** v1.2.0.0-rc4 ===
=== ** v1.2.0.05-rc5 ===
* [ADD] Nuevas clases para mejorar el rendimiento y la legibilidad del código.
* [ADD] Mejora de seguridad para la gestión de la clave maestra de la sesión.
* [MOD] Ajustes visuales menores.
* [MOD] Mejorada la gestión de la configuración.
* [MOD] Limpieza de código.
* [FIX] Corregido error al guardar una cuenta en la que el usuario no tenía permisos para cambiar el grupo principal.
* [FIX] Corregido error al restaurar una cuenta donde el grupo principal no se restauraba.
=== ** v1.2.0.04-rc4 ===
* [ADD] Nueva función para copiar al portapapeles SIN flash, sólo Javascript (biennnnn).
* [ADD] Nuevo método para optimizar(/reducir los archivos CSS y JS.
@@ -21,18 +31,18 @@
* [FIX] Corregido fallo al obtener la clave pública cuando no había una sesión iniciada.
* [FIX] Corregido fallo en la nueva detección del lenguaje.
=== ** v1.2.0.0-rc3 ===
=== ** v1.2.0.03-rc3 ===
* [ADD] Nuevas preferencias de usuario disponibles
* [MOD] Las fuentes CSS son ahora almacenadas localmente para el tema Material Blue
=== ** v1.2.0.0-rc2 ===
=== ** v1.2.0.02-rc2 ===
* [ADD] Cambiado a BCRYPT para generar el hash de las claves y derivaciones. AVISO: La clave maestra debe de ser introducida por los usuarios (es posible usar una clave temporal)
* [MOD] Algunos ajustes en la desencriptación de claves de los formularios
* [FIX] Corregido error cuando los campos personalizados en blanco son obtenidos para un elemento.
=== ** v1.2.0.0-rc1 ===
=== ** v1.2.0.01-rc1 ===
* [ADD] Mejoras de seguridad para prevenir ataques comunes (SQL Injection, XSS, CSRF)
* [ADD] Totalmente MVC

View File

@@ -23,6 +23,8 @@
*
*/
use SP\SessionUtil;
define('APP_ROOT', '..');
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
@@ -31,8 +33,8 @@ SP\Request::checkReferer('POST');
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
$userId = SP\Request::analyze('itemId', 0);
@@ -52,8 +54,8 @@ if($userId && $pin && $twoFa->verifyKey($pin)){
$urlParams = isset($params) ? '?' . implode('&', $params) : '';
SP\Common::printJSON(_('Código correcto'), 0, 'redirect(\'index.php\')');
SP\Response::printJSON(_('Código correcto'), 0, 'redirect(\'index.php\')');
} else {
\SP\Session::set2FApassed(false);
SP\Common::printJSON(_('Código incorrecto'));
SP\Response::printJSON(_('Código incorrecto'));
}

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
define('APP_ROOT', '..');
@@ -32,13 +33,13 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
// Variables POST del formulario
@@ -65,7 +66,7 @@ $customFields = SP\Request::analyze('customfield');
// Datos del Usuario
$currentUserId = SP\Session::getUserId();
if ($accountMainGroupId === 0) {
if (!$accountMainGroupId === 0) {
$accountMainGroupId = SP\Session::getUserGroupId();
}
@@ -74,42 +75,42 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_ACC_NEW
) {
// Comprobaciones para nueva cuenta
if (!$accountName) {
SP\Common::printJSON(_('Es necesario un nombre de cuenta'));
SP\Response::printJSON(_('Es necesario un nombre de cuenta'));
} elseif (!$customerId && !$newCustomer) {
SP\Common::printJSON(_('Es necesario un nombre de cliente'));
SP\Response::printJSON(_('Es necesario un nombre de cliente'));
} elseif (!$accountLogin) {
SP\Common::printJSON(_('Es necesario un usuario'));
SP\Response::printJSON(_('Es necesario un usuario'));
} elseif (!$accountPassword || !$accountPasswordR) {
SP\Common::printJSON(_('Es necesaria una clave'));
SP\Response::printJSON(_('Es necesaria una clave'));
} elseif (!$categoryId) {
SP\Common::printJSON(_('Es necesario una categoría'));
SP\Response::printJSON(_('Es necesario una categoría'));
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_ACC_EDIT) {
// Comprobaciones para modificación de cuenta
if (!$customerId && !$newCustomer) {
SP\Common::printJSON(_('Es necesario un nombre de cliente'));
SP\Response::printJSON(_('Es necesario un nombre de cliente'));
} elseif (!$accountName) {
SP\Common::printJSON(_('Es necesario un nombre de cuenta'));
SP\Response::printJSON(_('Es necesario un nombre de cuenta'));
} elseif (!$accountLogin) {
SP\Common::printJSON(_('Es necesario un usuario'));
SP\Response::printJSON(_('Es necesario un usuario'));
} elseif (!$categoryId) {
SP\Common::printJSON(_('Es necesario una categoría'));
SP\Response::printJSON(_('Es necesario una categoría'));
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_ACC_DELETE) {
if (!$accountId) {
SP\Common::printJSON(_('Id inválido'));
SP\Response::printJSON(_('Id inválido'));
}
} elseif ($actionId == \SP\Controller\ActionsInterface::ACTION_ACC_EDIT_PASS) {
// Comprobaciones para modficación de clave
if (!$accountPassword || !$accountPasswordR) {
SP\Common::printJSON(_('Es necesaria una clave'));
SP\Response::printJSON(_('Es necesaria una clave'));
}
} elseif ($actionId == \SP\Controller\ActionsInterface::ACTION_ACC_EDIT_RESTORE) {
if (!$accountId) {
SP\Common::printJSON(_('Id inválido'));
SP\Response::printJSON(_('Id inválido'));
}
} else {
SP\Common::printJSON(_('Acción Inválida'));
SP\Response::printJSON(_('Acción Inválida'));
}
if ($actionId == \SP\Controller\ActionsInterface::ACTION_ACC_NEW
@@ -117,14 +118,14 @@ if ($actionId == \SP\Controller\ActionsInterface::ACTION_ACC_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_ACC_EDIT_PASS
) {
if ($accountPassword != $accountPasswordR) {
SP\Common::printJSON(_('Las claves no coinciden'));
SP\Response::printJSON(_('Las claves no coinciden'));
}
// Encriptar clave de cuenta
try {
$accountEncPass = SP\Crypt::encryptData($accountPassword);
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage());
SP\Response::printJSON($e->getMessage());
}
}
@@ -141,7 +142,7 @@ switch ($actionId) {
SP\Customer::addCustomer();
$customerId = SP\Customer::$customerLastId;
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage());
SP\Response::printJSON($e->getMessage());
}
}
@@ -169,10 +170,10 @@ switch ($actionId) {
}
}
SP\Common::printJSON(_('Cuenta creada'), 0);
SP\Response::printJSON(_('Cuenta creada'), 0);
}
SP\Common::printJSON(_('Error al crear la cuenta'), 0);
SP\Response::printJSON(_('Error al crear la cuenta'), 0);
break;
case \SP\Controller\ActionsInterface::ACTION_ACC_EDIT:
SP\Customer::$customerName = $newCustomer;
@@ -183,7 +184,7 @@ switch ($actionId) {
SP\Customer::addCustomer();
$customerId = SP\Customer::$customerLastId;
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage());
SP\Response::printJSON($e->getMessage());
}
}
@@ -207,7 +208,7 @@ switch ($actionId) {
// Comprobar si han habido cambios
if ($accountChangesHash == $Account->calcChangesHash()) {
SP\Common::printJSON(_('Sin cambios'), 0);
SP\Response::printJSON(_('Sin cambios'), 0);
}
// Actualizar cuenta
@@ -219,20 +220,20 @@ switch ($actionId) {
}
}
SP\Common::printJSON(_('Cuenta actualizada'), 0);
SP\Response::printJSON(_('Cuenta actualizada'), 0);
}
SP\Common::printJSON(_('Error al modificar la cuenta'));
SP\Response::printJSON(_('Error al modificar la cuenta'));
break;
case \SP\Controller\ActionsInterface::ACTION_ACC_DELETE:
$Account->setAccountId($accountId);
// Eliminar cuenta
if ($Account->deleteAccount() && \SP\CustomFields::deleteCustomFieldForItem($accountId, \SP\Controller\ActionsInterface::ACTION_ACC_NEW)) {
SP\Common::printJSON(_('Cuenta eliminada'), 0, "sysPassUtil.Common.doAction('" . \SP\Controller\ActionsInterface::ACTION_ACC_SEARCH . "');");
SP\Response::printJSON(_('Cuenta eliminada'), 0, "sysPassUtil.Common.doAction('" . \SP\Controller\ActionsInterface::ACTION_ACC_SEARCH . "');");
}
SP\Common::printJSON(_('Error al eliminar la cuenta'));
SP\Response::printJSON(_('Error al eliminar la cuenta'));
break;
case \SP\Controller\ActionsInterface::ACTION_ACC_EDIT_PASS:
$Account->setAccountId($accountId);
@@ -242,22 +243,22 @@ switch ($actionId) {
// Actualizar clave de cuenta
if ($Account->updateAccountPass()) {
SP\Common::printJSON(_('Clave actualizada'), 0);
SP\Response::printJSON(_('Clave actualizada'), 0);
}
SP\Common::printJSON(_('Error al actualizar la clave'));
SP\Response::printJSON(_('Error al actualizar la clave'));
break;
case \SP\Controller\ActionsInterface::ACTION_ACC_EDIT_RESTORE:
$Account->setAccountId(SP\AccountHistory::getAccountIdFromId($accountId));
$Account->setAccountUserEditId($currentUserId);
if ($Account->restoreFromHistory($accountId)) {
SP\Common::printJSON(_('Cuenta restaurada'), 0);
SP\Response::printJSON(_('Cuenta restaurada'), 0);
}
SP\Common::printJSON(_('Error al restaurar cuenta'));
SP\Response::printJSON(_('Error al restaurar cuenta'));
break;
default:
SP\Common::printJSON(_('Acción Inválida'));
SP\Response::printJSON(_('Acción Inválida'));
}

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
use SP\UserUtil;
define('APP_ROOT', '..');
@@ -33,13 +34,13 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
@@ -82,33 +83,33 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_EDIT
) {
if (!$User->getUserName() && !$isLdap) {
SP\Common::printJSON(_('Es necesario un nombre de usuario'), 2);
SP\Response::printJSON(_('Es necesario un nombre de usuario'), 2);
} elseif (!$User->getUserLogin() && !$isLdap) {
SP\Common::printJSON(_('Es necesario un login'), 2);
SP\Response::printJSON(_('Es necesario un login'), 2);
} elseif (!$User->getUserProfileId()) {
SP\Common::printJSON(_('Es necesario un perfil'), 2);
SP\Response::printJSON(_('Es necesario un perfil'), 2);
} elseif (!$User->getUserGroupId()) {
SP\Common::printJSON(_('Es necesario un grupo'), 2);
SP\Response::printJSON(_('Es necesario un grupo'), 2);
} elseif (!$User->getUserEmail() && !$isLdap) {
SP\Common::printJSON(_('Es necesario un email'), 2);
SP\Response::printJSON(_('Es necesario un email'), 2);
} elseif (SP\Util::demoIsEnabled() && !\SP\Session::getUserIsAdminApp() && $User->getUserLogin() == 'demo') {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
SP\Response::printJSON(_('Ey, esto es una DEMO!!'));
}
switch ($User->checkUserExist()) {
case UserUtil::USER_LOGIN_EXIST:
SP\Common::printJSON(_('Login de usuario duplicado'), 2);
SP\Response::printJSON(_('Login de usuario duplicado'), 2);
break;
case UserUtil::USER_MAIL_EXIST:
SP\Common::printJSON(_('Email de usuario duplicado'), 2);
SP\Response::printJSON(_('Email de usuario duplicado'), 2);
break;
}
if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW) {
if (!$User->getUserPass() || !$userPassR) {
SP\Common::printJSON(_('La clave no puede estar en blanco'), 2);
SP\Response::printJSON(_('La clave no puede estar en blanco'), 2);
} elseif ($User->getUserPass() != $userPassR) {
SP\Common::printJSON(_('Las claves no coinciden'), 2);
SP\Response::printJSON(_('Las claves no coinciden'), 2);
}
if ($User->addUser()) {
@@ -119,10 +120,10 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
}
}
SP\Common::printJSON(_('Usuario creado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Usuario creado'), 0, $doActionOnClose);
}
SP\Common::printJSON(_('Error al crear el usuario'));
SP\Response::printJSON(_('Error al crear el usuario'));
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_EDIT) {
if ($User->updateUser()) {
if (is_array($customFields)) {
@@ -132,40 +133,40 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
}
}
SP\Common::printJSON(_('Usuario actualizado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Usuario actualizado'), 0, $doActionOnClose);
}
SP\Common::printJSON(_('Error al actualizar el usuario'));
SP\Response::printJSON(_('Error al actualizar el usuario'));
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_EDITPASS) {
if (SP\Util::demoIsEnabled() && UserUtil::getUserLoginById($itemId) == 'demo') {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
SP\Response::printJSON(_('Ey, esto es una DEMO!!'));
} elseif (!$User->getUserPass() || !$userPassR) {
SP\Common::printJSON(_('La clave no puede estar en blanco'), 2);
SP\Response::printJSON(_('La clave no puede estar en blanco'), 2);
} elseif ($User->getUserPass() != $userPassR) {
SP\Common::printJSON(_('Las claves no coinciden'), 2);
SP\Response::printJSON(_('Las claves no coinciden'), 2);
}
if ($User->updateUserPass()) {
SP\Common::printJSON(_('Clave actualizada'), 0);
SP\Response::printJSON(_('Clave actualizada'), 0);
}
SP\Common::printJSON(_('Error al modificar la clave'));
SP\Response::printJSON(_('Error al modificar la clave'));
// Eliminar usuario
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_DELETE) {
if (SP\Util::demoIsEnabled() && UserUtil::getUserLoginById($itemId) == 'demo') {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
SP\Response::printJSON(_('Ey, esto es una DEMO!!'));
} elseif ($User->getUserId() == SP\Session::getUserId()) {
SP\Common::printJSON(_('No es posible eliminar, usuario en uso'));
SP\Response::printJSON(_('No es posible eliminar, usuario en uso'));
}
if ($User->deleteUser() && SP\CustomFields::deleteCustomFieldForItem($User->getUserId(), \SP\Controller\ActionsInterface::ACTION_USR_USERS)) {
SP\Common::printJSON(_('Usuario eliminado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Usuario eliminado'), 0, $doActionOnClose);
}
SP\Common::printJSON(_('Error al eliminar el usuario'));
SP\Response::printJSON(_('Error al eliminar el usuario'));
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT
@@ -180,7 +181,7 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT
) {
if (!$frmGrpName) {
SP\Common::printJSON(_('Es necesario un nombre de grupo'), 2);
SP\Response::printJSON(_('Es necesario un nombre de grupo'), 2);
}
SP\Groups::$groupId = $itemId;
@@ -188,7 +189,7 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
SP\Groups::$groupDescription = $frmGrpDesc;
if (SP\Groups::checkGroupExist()) {
SP\Common::printJSON(_('Nombre de grupo duplicado'), 2);
SP\Response::printJSON(_('Nombre de grupo duplicado'), 2);
}
if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_NEW) {
@@ -200,9 +201,9 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
}
}
SP\Common::printJSON(_('Grupo creado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Grupo creado'), 0, $doActionOnClose);
} else {
SP\Common::printJSON(_('Error al crear el grupo'));
SP\Response::printJSON(_('Error al crear el grupo'));
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_EDIT) {
if (SP\Groups::updateGroup($frmGrpUsers)) {
@@ -213,10 +214,10 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
}
}
SP\Common::printJSON(_('Grupo actualizado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Grupo actualizado'), 0, $doActionOnClose);
}
SP\Common::printJSON(_('Error al actualizar el grupo'));
SP\Response::printJSON(_('Error al actualizar el grupo'));
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_GROUPS_DELETE) {
SP\Groups::$groupId = $itemId;
@@ -232,15 +233,15 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
$uses[] = _('Cuentas') . " (" . $resGroupUse['accounts'] . ")";
}
SP\Common::printJSON(_('No es posible eliminar') . ';;' . _('Grupo en uso por:') . ';;' . implode(';;', $uses));
SP\Response::printJSON(_('No es posible eliminar') . ';;' . _('Grupo en uso por:') . ';;' . implode(';;', $uses));
} else {
$groupName = SP\Groups::getGroupNameById($itemId);
if (SP\Groups::deleteGroup() && SP\CustomFields::deleteCustomFieldForItem($itemId, \SP\Controller\ActionsInterface::ACTION_USR_GROUPS)) {
SP\Common::printJSON(_('Grupo eliminado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Grupo eliminado'), 0, $doActionOnClose);
}
SP\Common::printJSON(_('Error al eliminar el grupo'));
SP\Response::printJSON(_('Error al eliminar el grupo'));
}
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_NEW
@@ -279,23 +280,23 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT
) {
if (!$Profile->getName()) {
SP\Common::printJSON(_('Es necesario un nombre de perfil'), 2);
SP\Response::printJSON(_('Es necesario un nombre de perfil'), 2);
} elseif (SP\Profile::checkProfileExist($Profile->getId(), $Profile->getName())) {
SP\Common::printJSON(_('Nombre de perfil duplicado'), 2);
SP\Response::printJSON(_('Nombre de perfil duplicado'), 2);
}
if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_NEW) {
if ($Profile->profileAdd()) {
SP\Common::printJSON(_('Perfil creado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Perfil creado'), 0, $doActionOnClose);
}
SP\Common::printJSON(_('Error al crear el perfil'));
SP\Response::printJSON(_('Error al crear el perfil'));
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_EDIT) {
if ($Profile->profileUpdate()) {
SP\Common::printJSON(_('Perfil actualizado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Perfil actualizado'), 0, $doActionOnClose);
}
SP\Common::printJSON(_('Error al actualizar el perfil'));
SP\Response::printJSON(_('Error al actualizar el perfil'));
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_PROFILES_DELETE) {
@@ -304,13 +305,13 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
if ($resProfileUse['users'] > 0) {
$uses[] = _('Usuarios') . " (" . $resProfileUse['users'] . ")";
SP\Common::printJSON(_('No es posible eliminar') . ';;' . _('Perfil en uso por:') . ';;' . implode(';;', $uses));
SP\Response::printJSON(_('No es posible eliminar') . ';;' . _('Perfil en uso por:') . ';;' . implode(';;', $uses));
} else {
if ($Profile->profileDelete()) {
SP\Common::printJSON(_('Perfil eliminado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Perfil eliminado'), 0, $doActionOnClose);
}
SP\Common::printJSON(_('Error al eliminar el perfil'));
SP\Response::printJSON(_('Error al eliminar el perfil'));
}
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_NEW
@@ -325,7 +326,7 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT
) {
if (!$frmCustomerName) {
SP\Common::printJSON(_('Es necesario un nombre de cliente'), 2);
SP\Response::printJSON(_('Es necesario un nombre de cliente'), 2);
}
SP\Customer::$customerName = $frmCustomerName;
@@ -342,10 +343,10 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
}
}
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Cliente creado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Cliente creado'), 0, $doActionOnClose);
} else if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_EDIT) {
try {
SP\Customer::updateCustomer($itemId);
@@ -357,20 +358,20 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
}
}
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Cliente actualizado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Cliente actualizado'), 0, $doActionOnClose);
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS_DELETE) {
try {
SP\Customer::deleteCustomer($itemId);
SP\CustomFields::deleteCustomFieldForItem($itemId, \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMERS);
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage());
SP\Response::printJSON($e->getMessage());
}
SP\Common::printJSON(_('Cliente eliminado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Cliente eliminado'), 0, $doActionOnClose);
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT
@@ -384,7 +385,7 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT
) {
if (!$frmCategoryName) {
SP\Common::printJSON(_('Es necesario un nombre de categoría'), 2);
SP\Response::printJSON(_('Es necesario un nombre de categoría'), 2);
}
SP\Category::$categoryName = $frmCategoryName;
@@ -401,10 +402,10 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
}
}
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Categoría creada'), 0, $doActionOnClose);
SP\Response::printJSON(_('Categoría creada'), 0, $doActionOnClose);
} else if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_EDIT) {
try {
SP\Category::updateCategory($itemId);
@@ -416,10 +417,10 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
}
}
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Categoría actualizada'), 0, $doActionOnClose);
SP\Response::printJSON(_('Categoría actualizada'), 0, $doActionOnClose);
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES_DELETE) {
@@ -427,10 +428,10 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
SP\Category::deleteCategory($itemId);
SP\CustomFields::deleteCustomFieldForItem($itemId, \SP\Controller\ActionsInterface::ACTION_MGM_CATEGORIES);
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage());
SP\Response::printJSON($e->getMessage());
}
SP\Common::printJSON(_('Categoría eliminada'), 0, $doActionOnClose);
SP\Response::printJSON(_('Categoría eliminada'), 0, $doActionOnClose);
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_APITOKENS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_APITOKENS_EDIT
@@ -446,35 +447,35 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_APITOKENS_EDIT
) {
if ($ApiTokens->getUserId() === 0 || $ApiTokens->getActionId() === 0) {
SP\Common::printJSON(_('Usuario o acción no indicado'), 2);
SP\Response::printJSON(_('Usuario o acción no indicado'), 2);
}
if ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_APITOKENS_NEW) {
try {
$ApiTokens->addToken();
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Autorización creada'), 0, $doActionOnClose);
SP\Response::printJSON(_('Autorización creada'), 0, $doActionOnClose);
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_APITOKENS_EDIT) {
try {
$ApiTokens->updateToken();
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Autorización actualizada'), 0, $doActionOnClose);
SP\Response::printJSON(_('Autorización actualizada'), 0, $doActionOnClose);
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_APITOKENS_DELETE) {
try {
$ApiTokens->deleteToken();
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Autorización eliminada'), 0, $doActionOnClose);
SP\Response::printJSON(_('Autorización eliminada'), 0, $doActionOnClose);
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMFIELDS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMFIELDS_EDIT
@@ -491,11 +492,11 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
|| $actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMFIELDS_EDIT
) {
if (!$frmFieldName) {
SP\Common::printJSON(_('Nombre del campo no indicado'), 2);
SP\Response::printJSON(_('Nombre del campo no indicado'), 2);
} elseif ($frmFieldType === 0) {
SP\Common::printJSON(_('Tipo del campo no indicado'), 2);
SP\Response::printJSON(_('Tipo del campo no indicado'), 2);
} elseif ($frmFieldModule === 0) {
SP\Common::printJSON(_('Módulo del campo no indicado'), 2);
SP\Response::printJSON(_('Módulo del campo no indicado'), 2);
}
$CustomFieldDef = new \SP\CustomFieldDef($frmFieldName, $frmFieldType, $frmFieldModule);
@@ -506,30 +507,30 @@ if ($actionId === \SP\Controller\ActionsInterface::ACTION_USR_USERS_NEW
try {
$CustomFieldDef->addCustomField();
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Campo creado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Campo creado'), 0, $doActionOnClose);
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMFIELDS_EDIT) {
try {
$CustomFieldDef->setId($itemId);
$CustomFieldDef->updateCustomField();
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Campo actualizado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Campo actualizado'), 0, $doActionOnClose);
}
} elseif ($actionId === \SP\Controller\ActionsInterface::ACTION_MGM_CUSTOMFIELDS_DELETE) {
try {
\SP\CustomFieldDef::deleteCustomField($itemId);
} catch (\SP\SPException $e) {
SP\Common::printJSON($e->getMessage(), 2);
SP\Response::printJSON($e->getMessage(), 2);
}
SP\Common::printJSON(_('Campo eliminado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Campo eliminado'), 0, $doActionOnClose);
}
} else {
SP\Common::printJSON(_('Acción Inválida'));
SP\Response::printJSON(_('Acción Inválida'));
}

View File

@@ -23,6 +23,8 @@
*
*/
use SP\SessionUtil;
define('APP_ROOT', '..');
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
@@ -30,13 +32,13 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
SP\Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
$actionId = SP\Request::analyze('actionId', 0);
@@ -48,27 +50,31 @@ $exportPasswordR = SP\Request::analyzeEncrypted('exportPwdR');
$doActionOnClose = "sysPassUtil.Common.doAction($actionId,'',$activeTab);";
if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_BACKUP) {
if (SP\Util::demoIsEnabled()) {
SP\Response::printJSON(_('Ey, esto es una DEMO!!'));
}
if (!SP\Backup::doBackup()) {
SP\Log::writeNewLogAndEmail(_('Realizar Backup'), _('Error al realizar el backup'));
SP\Common::printJSON(_('Error al realizar el backup') . ';;' . _('Revise el registro de eventos para más detalles'));
SP\Response::printJSON(_('Error al realizar el backup') . ';;' . _('Revise el registro de eventos para más detalles'));
}
SP\Log::writeNewLogAndEmail(_('Realizar Backup'), _('Copia de la aplicación y base de datos realizada correctamente'));
SP\Common::printJSON(_('Proceso de backup finalizado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Proceso de backup finalizado'), 0, $doActionOnClose);
} elseif ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_EXPORT) {
if (!empty($exportPassword) && $exportPassword !== $exportPasswordR){
SP\Common::printJSON(_('Las claves no coinciden'));
SP\Response::printJSON(_('Las claves no coinciden'));
}
if(!\SP\XmlExport::doExport($exportPassword)){
SP\Log::writeNewLogAndEmail(_('Realizar Exportación'), _('Error al realizar la exportación de cuentas'));
SP\Common::printJSON(_('Error al realizar la exportación') . ';;' . _('Revise el registro de eventos para más detalles'));
SP\Response::printJSON(_('Error al realizar la exportación') . ';;' . _('Revise el registro de eventos para más detalles'));
}
SP\Log::writeNewLogAndEmail(_('Realizar Exportación'), _('Exportación de cuentas realizada correctamente'));
SP\Common::printJSON(_('Proceso de exportación finalizado'), 0, $doActionOnClose);
SP\Response::printJSON(_('Proceso de exportación finalizado'), 0, $doActionOnClose);
}

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
define('APP_ROOT', '..');
@@ -32,13 +33,13 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
$frmLdapServer = SP\Request::analyze('ldap_server');
@@ -48,13 +49,13 @@ $frmLdapBindUser = SP\Request::analyze('ldap_binduser');
$frmLdapBindPass = SP\Request::analyzeEncrypted('ldap_bindpass');
if (!$frmLdapServer || !$frmLdapBase || !$frmLdapBindUser || !$frmLdapBindPass) {
SP\Common::printJSON(_('Los parámetros de LDAP no están configurados'));
SP\Response::printJSON(_('Los parámetros de LDAP no están configurados'));
}
$resCheckLdap = SP\Ldap::checkLDAPConn($frmLdapServer, $frmLdapBindUser, $frmLdapBindPass, $frmLdapBase, $frmLdapGroup);
if ($resCheckLdap === false) {
SP\Common::printJSON(_('Error de conexión a LDAP') . ';;' . _('Revise el registro de eventos para más detalles'));
SP\Response::printJSON(_('Error de conexión a LDAP') . ';;' . _('Revise el registro de eventos para más detalles'));
} else {
SP\Common::printJSON(_('Conexión a LDAP correcta') . ';;' . _('Objetos encontrados') . ': ' . $resCheckLdap, 0);
SP\Response::printJSON(_('Conexión a LDAP correcta') . ';;' . _('Objetos encontrados') . ': ' . $resCheckLdap, 0);
}

View File

@@ -23,7 +23,10 @@
*
*/
use SP\UserUtil;
use SP\ConfigDB;
use SP\CryptMasterPass;
use SP\SessionUtil;
use SP\UserPass;
define('APP_ROOT', '..');
@@ -32,13 +35,13 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
SP\Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
// Variables POST del formulario
@@ -52,7 +55,7 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
|| $actionId === SP\Controller\ActionsInterface::ACTION_CFG_LDAP
|| $actionId === SP\Controller\ActionsInterface::ACTION_CFG_MAIL
) {
$log = SP\Log::newLog(_('Modificar Configuración'));
$Log = SP\Log::newLog(_('Modificar Configuración'));
if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL) {
// General
@@ -66,15 +69,15 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
$checkUpdatesEnabled = SP\Request::analyze('updates', false, false, true);
$checkNoticesEnabled = SP\Request::analyze('notices', false, false, true);
SP\Config::setValue('sitelang', $siteLang);
SP\Config::setValue('sitetheme', $siteTheme);
SP\Config::setValue('session_timeout', $sessionTimeout);
SP\Config::setValue('https_enabled', $httpsEnabled);
SP\Config::setValue('log_enabled', $logEnabled);
SP\Config::setValue('debug', $debugEnabled);
SP\Config::setValue('maintenance', $maintenanceEnabled);
SP\Config::setValue('checkupdates', $checkUpdatesEnabled);
SP\Config::setValue('checknotices', $checkNoticesEnabled);
SP\Config::setCacheConfigValue('sitelang', $siteLang);
SP\Config::setCacheConfigValue('sitetheme', $siteTheme);
SP\Config::setCacheConfigValue('session_timeout', $sessionTimeout);
SP\Config::setCacheConfigValue('https_enabled', $httpsEnabled);
SP\Config::setCacheConfigValue('log_enabled', $logEnabled);
SP\Config::setCacheConfigValue('debug', $debugEnabled);
SP\Config::setCacheConfigValue('maintenance', $maintenanceEnabled);
SP\Config::setCacheConfigValue('checkupdates', $checkUpdatesEnabled);
SP\Config::setCacheConfigValue('checknotices', $checkNoticesEnabled);
// Accounts
$globalSearchEnabled = SP\Request::analyze('globalsearch', false, false, true);
@@ -83,23 +86,23 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
$accountCount = SP\Request::analyze('account_count', 10);
$resultsAsCardsEnabled = SP\Request::analyze('resultsascards', false, false, true);
SP\Config::setValue('globalsearch', $globalSearchEnabled);
SP\Config::setValue('account_passtoimage', $accountPassToImageEnabled);
SP\Config::setValue('account_link', $accountLinkEnabled);
SP\Config::setValue('account_count', $accountCount);
SP\Config::setValue('resultsascards', $resultsAsCardsEnabled);
SP\Config::setCacheConfigValue('globalsearch', $globalSearchEnabled);
SP\Config::setCacheConfigValue('account_passtoimage', $accountPassToImageEnabled);
SP\Config::setCacheConfigValue('account_link', $accountLinkEnabled);
SP\Config::setCacheConfigValue('account_count', $accountCount);
SP\Config::setCacheConfigValue('resultsascards', $resultsAsCardsEnabled);
// Files
$filesEnabled = SP\Request::analyze('files_enabled', false, false, true);
$filesAllowedSize = SP\Request::analyze('files_allowed_size', 1024);
$filesAllowedExts = SP\Request::analyze('files_allowed_exts');
SP\Config::setValue('files_enabled', $filesEnabled);
SP\Config::setValue('files_allowed_size', $filesAllowedSize);
SP\Config::setValue('files_allowed_exts', $filesAllowedExts);
SP\Config::setCacheConfigValue('files_enabled', $filesEnabled);
SP\Config::setCacheConfigValue('files_allowed_size', $filesAllowedSize);
SP\Config::setCacheConfigValue('files_allowed_exts', $filesAllowedExts);
if ($filesEnabled && $filesAllowedSize >= 16384) {
SP\Common::printJSON(_('El tamaño máximo por archivo es de 16MB'));
SP\Response::printJSON(_('El tamaño máximo por archivo es de 16MB'));
}
// Proxy
@@ -112,18 +115,22 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
// Valores para Proxy
if ($proxyEnabled && (!$proxyServer || !$proxyPort)) {
SP\Common::printJSON(_('Faltan parámetros de Proxy'));
SP\Response::printJSON(_('Faltan parámetros de Proxy'));
} elseif ($proxyEnabled) {
SP\Config::setValue('proxy_enabled', true);
SP\Config::setValue('proxy_server', $proxyServer);
SP\Config::setValue('proxy_port', $proxyPort);
SP\Config::setValue('proxy_user', $proxyUser);
SP\Config::setValue('proxy_pass', $proxyPass);
SP\Config::setCacheConfigValue('proxy_enabled', true);
SP\Config::setCacheConfigValue('proxy_server', $proxyServer);
SP\Config::setCacheConfigValue('proxy_port', $proxyPort);
SP\Config::setCacheConfigValue('proxy_user', $proxyUser);
SP\Config::setCacheConfigValue('proxy_pass', $proxyPass);
$Log->addDescription(_('Proxy habiltado'));
} else {
SP\Config::setValue('proxy_enabled', false);
SP\Config::setCacheConfigValue('proxy_enabled', false);
$Log->addDescription(_('Proxy deshabilitado'));
}
$log->addDescription(sprintf('%s: %s', _('Sección'), _('General')));
$Log->addDescription(sprintf('%s: %s', _('Sección'), _('General')));
} elseif ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_WIKI) {
// Wiki
$wikiEnabled = SP\Request::analyze('wiki_enabled', false, false, true);
@@ -133,17 +140,21 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
// Valores para la conexión a la Wiki
if ($wikiEnabled && (!$wikiSearchUrl || !$wikiPageUrl || !$wikiFilter)) {
SP\Common::printJSON(_('Faltan parámetros de Wiki'));
SP\Response::printJSON(_('Faltan parámetros de Wiki'));
} elseif ($wikiEnabled) {
SP\Config::setValue('wiki_enabled', true);
SP\Config::setValue('wiki_searchurl', $wikiSearchUrl);
SP\Config::setValue('wiki_pageurl', $wikiPageUrl);
SP\Config::setValue('wiki_filter', $wikiFilter);
SP\Config::setCacheConfigValue('wiki_enabled', true);
SP\Config::setCacheConfigValue('wiki_searchurl', $wikiSearchUrl);
SP\Config::setCacheConfigValue('wiki_pageurl', $wikiPageUrl);
SP\Config::setCacheConfigValue('wiki_filter', $wikiFilter);
$Log->addDescription(_('Wiki habiltada'));
} else {
SP\Config::setValue('wiki_enabled', false);
SP\Config::setCacheConfigValue('wiki_enabled', false);
$Log->addDescription(_('Wiki deshabilitada'));
}
$log->addDescription(sprintf('%s: %s', _('Sección'), _('Wiki')));
$Log->addDescription(sprintf('%s: %s', _('Sección'), _('Wiki')));
} elseif ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_LDAP) {
// LDAP
$ldapEnabled = SP\Request::analyze('ldap_enabled', false, false, true);
@@ -158,22 +169,26 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
// Valores para la configuración de LDAP
if ($ldapEnabled && (!$ldapServer || !$ldapBase || !$ldapBindUser)) {
SP\Common::printJSON(_('Faltan parámetros de LDAP'));
SP\Response::printJSON(_('Faltan parámetros de LDAP'));
} elseif ($ldapEnabled) {
SP\Config::setValue('ldap_enabled', true);
SP\Config::setValue('ldap_ads', $ldapADSEnabled);
SP\Config::setValue('ldap_server', $ldapServer);
SP\Config::setValue('ldap_base', $ldapBase);
SP\Config::setValue('ldap_group', $ldapGroup);
SP\Config::setValue('ldap_defaultgroup', $ldapDefaultGroup);
SP\Config::setValue('ldap_defaultprofile', $ldapDefaultProfile);
SP\Config::setValue('ldap_binduser', $ldapBindUser);
SP\Config::setValue('ldap_bindpass', $ldapBindPass);
SP\Config::setCacheConfigValue('ldap_enabled', true);
SP\Config::setCacheConfigValue('ldap_ads', $ldapADSEnabled);
SP\Config::setCacheConfigValue('ldap_server', $ldapServer);
SP\Config::setCacheConfigValue('ldap_base', $ldapBase);
SP\Config::setCacheConfigValue('ldap_group', $ldapGroup);
SP\Config::setCacheConfigValue('ldap_defaultgroup', $ldapDefaultGroup);
SP\Config::setCacheConfigValue('ldap_defaultprofile', $ldapDefaultProfile);
SP\Config::setCacheConfigValue('ldap_binduser', $ldapBindUser);
SP\Config::setCacheConfigValue('ldap_bindpass', $ldapBindPass);
$Log->addDescription(_('LDAP habiltado'));
} else {
SP\Config::setValue('ldap_enabled', false);
SP\Config::setCacheConfigValue('ldap_enabled', false);
$Log->addDescription(_('LDAP deshabilitado'));
}
$log->addDescription(sprintf('%s: %s', _('Sección'), _('LDAP')));
$Log->addDescription(sprintf('%s: %s', _('Sección'), _('LDAP')));
} elseif ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_MAIL) {
// Mail
$mailEnabled = SP\Request::analyze('mail_enabled', false, false, true);
@@ -188,39 +203,53 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
// Valores para la configuración del Correo
if ($mailEnabled && (!$mailServer || !$mailFrom)) {
SP\Common::printJSON(_('Faltan parámetros de Correo'));
SP\Response::printJSON(_('Faltan parámetros de Correo'));
} elseif ($mailEnabled) {
SP\Config::setValue('mail_enabled', true);
SP\Config::setValue('mail_requestsenabled', $mailRequests);
SP\Config::setValue('mail_server', $mailServer);
SP\Config::setValue('mail_port', $mailPort);
SP\Config::setValue('mail_security', $mailSecurity);
SP\Config::setValue('mail_from', $mailFrom);
SP\Config::setCacheConfigValue('mail_enabled', true);
SP\Config::setCacheConfigValue('mail_requestsenabled', $mailRequests);
SP\Config::setCacheConfigValue('mail_server', $mailServer);
SP\Config::setCacheConfigValue('mail_port', $mailPort);
SP\Config::setCacheConfigValue('mail_security', $mailSecurity);
SP\Config::setCacheConfigValue('mail_from', $mailFrom);
if ($mailAuth) {
SP\Config::setValue('mail_authenabled', $mailAuth);
SP\Config::setValue('mail_user', $mailUser);
SP\Config::setValue('mail_pass', $mailPass);
SP\Config::setCacheConfigValue('mail_authenabled', $mailAuth);
SP\Config::setCacheConfigValue('mail_user', $mailUser);
SP\Config::setCacheConfigValue('mail_pass', $mailPass);
}
$Log->addDescription(_('Correo habiltado'));
} else {
SP\Config::setValue('mail_enabled', false);
SP\Config::setValue('mail_requestsenabled', false);
SP\Config::setValue('mail_authenabled', false);
SP\Config::setCacheConfigValue('mail_enabled', false);
SP\Config::setCacheConfigValue('mail_requestsenabled', false);
SP\Config::setCacheConfigValue('mail_authenabled', false);
$Log->addDescription(_('Correo deshabilitado'));
}
$log->addDescription(sprintf('%s: %s', _('Sección'), _('Correo')));
$Log->addDescription(sprintf('%s: %s', _('Sección'), _('Correo')));
}
$log->writeLog();
try {
SP\Config::writeConfig();
} catch (\SP\SPException $e){
$Log->addDescription($e->getMessage());
$Log->addDescription($e->getHint());
$Log->writeLog();
SP\Email::sendEmail($log);
SP\Response::printJSON($e->getMessage());
}
$Log->writeLog();
SP\Email::sendEmail($Log);
if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL) {
// Recargar la aplicación completa para establecer nuevos valores
SP\Util::reload();
}
SP\Common::printJSON(_('Configuración actualizada'), 0, $doActionOnClose);
SP\Response::printJSON(_('Configuración actualizada'), 0, $doActionOnClose);
} elseif ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_ENCRYPTION) {
$currentMasterPass = SP\Request::analyzeEncrypted('curMasterPwd');
$newMasterPass = SP\Request::analyzeEncrypted('newMasterPwd');
@@ -228,20 +257,20 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
$confirmPassChange = SP\Request::analyze('confirmPassChange', 0, false, 1);
$noAccountPassChange = SP\Request::analyze('chkNoAccountChange', 0, false, 1);
if (!UserUtil::checkUserUpdateMPass()) {
SP\Common::printJSON(_('Clave maestra actualizada') . ';;' . _('Reinicie la sesión para cambiarla'));
if (!UserPass::checkUserUpdateMPass()) {
SP\Response::printJSON(_('Clave maestra actualizada') . ';;' . _('Reinicie la sesión para cambiarla'));
} elseif ($newMasterPass == '' && $currentMasterPass == '') {
SP\Common::printJSON(_('Clave maestra no indicada'));
SP\Response::printJSON(_('Clave maestra no indicada'));
} elseif ($confirmPassChange == 0) {
SP\Common::printJSON(_('Se ha de confirmar el cambio de clave'));
SP\Response::printJSON(_('Se ha de confirmar el cambio de clave'));
}
if ($newMasterPass == $currentMasterPass) {
SP\Common::printJSON(_('Las claves son idénticas'));
SP\Response::printJSON(_('Las claves son idénticas'));
} elseif ($newMasterPass != $newMasterPassR) {
SP\Common::printJSON(_('Las claves maestras no coinciden'));
} elseif (!SP\Crypt::checkHashPass($currentMasterPass, SP\Config::getConfigDbValue('masterPwd'), true)) {
SP\Common::printJSON(_('La clave maestra actual no coincide'));
SP\Response::printJSON(_('Las claves maestras no coinciden'));
} elseif (!SP\Crypt::checkHashPass($currentMasterPass, ConfigDB::getValue('masterPwd'), true)) {
SP\Response::printJSON(_('La clave maestra actual no coincide'));
}
$hashMPass = SP\Crypt::mkHashPassword($newMasterPass);
@@ -250,45 +279,47 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_GENERAL
$Account = new SP\Account();
if (!$Account->updateAccountsMasterPass($currentMasterPass, $newMasterPass)) {
SP\Common::printJSON(_('Errores al actualizar las claves de las cuentas'));
SP\Response::printJSON(_('Errores al actualizar las claves de las cuentas'));
}
$AccountHistory = new SP\AccountHistory();
if (!$AccountHistory->updateAccountsMasterPass($currentMasterPass, $newMasterPass, $hashMPass)) {
SP\Common::printJSON(_('Errores al actualizar las claves de las cuentas del histórico'));
SP\Response::printJSON(_('Errores al actualizar las claves de las cuentas del histórico'));
}
if (!\SP\CustomFields::updateCustomFieldsCrypt($currentMasterPass, $newMasterPass)) {
SP\Common::printJSON(_('Errores al actualizar datos de campos personalizados'));
SP\Response::printJSON(_('Errores al actualizar datos de campos personalizados'));
}
}
if (SP\Util::demoIsEnabled()) {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
SP\Response::printJSON(_('Ey, esto es una DEMO!!'));
}
SP\Config::getConfigDb();
SP\Config::setArrConfigValue('masterPwd', $hashMPass);
SP\Config::setArrConfigValue('lastupdatempass', time());
// ConfigDB::readConfig();
ConfigDB::setCacheConfigValue('masterPwd', $hashMPass);
ConfigDB::setCacheConfigValue('lastupdatempass', time());
if (SP\Config::writeConfigDb()) {
if (ConfigDB::writeConfig()) {
SP\Log::writeNewLogAndEmail(_('Actualizar Clave Maestra'));
SP\Common::printJSON(_('Clave maestra actualizada'), 0);
SP\Response::printJSON(_('Clave maestra actualizada'), 0);
} else {
SP\Common::printJSON(_('Error al guardar el hash de la clave maestra'));
SP\Response::printJSON(_('Error al guardar el hash de la clave maestra'));
}
} elseif ($actionId === SP\Controller\ActionsInterface::ACTION_CFG_ENCRYPTION_TEMPPASS) {
$tempMasterMaxTime = SP\Request::analyze('tmpass_maxtime', 3600);
$tempMasterPass = SP\Config::setTempMasterPass($tempMasterMaxTime);
$tempMasterPass = CryptMasterPass::setTempMasterPass($tempMasterMaxTime);
if (!empty($tempMasterPass)) {
if ($tempMasterPass !== false && !empty($tempMasterPass)) {
SP\Email::sendEmail(new \SP\Log(_('Generar Clave Temporal'), SP\Html::strongText(_('Clave') . ': ') . $tempMasterPass));
SP\Common::printJSON(_('Clave Temporal Generada'), 0, $doActionOnClose);
SP\Response::printJSON(_('Clave Temporal Generada'), 0, $doActionOnClose);
} else {
SP\Response::printJSON(_('Error al generar clave temporal'));
}
} else {
SP\Common::printJSON(_('Acción Inválida'));
SP\Response::printJSON(_('Acción Inválida'));
}

View File

@@ -23,9 +23,12 @@
*
*/
use SP\CryptMasterPass;
use SP\Request;
use SP\SessionUtil;
use SP\UserLdap;
use SP\UserPass;
use SP\UserPassRecover;
use SP\UserUtil;
define('APP_ROOT', '..');
@@ -43,7 +46,7 @@ $userPass = SP\Request::analyzeEncrypted('pass');
$masterPass = SP\Request::analyzeEncrypted('mpass');
if (!$userLogin || !$userPass) {
SP\Common::printJSON(_('Usuario/Clave no introducidos'));
SP\Response::printJSON(_('Usuario/Clave no introducidos'));
}
$User = new SP\User();
@@ -69,7 +72,7 @@ if ($resLdap === true) {
$Log->addDescription(_('Error al guardar los datos de LDAP'));
$Log->writeLog();
SP\Common::printJSON(_('Error interno'));
SP\Response::printJSON(_('Error interno'));
}
} else {
// Actualizamos la clave del usuario en MySQL
@@ -77,7 +80,7 @@ if ($resLdap === true) {
$Log->addDescription(_('Error al actualizar la clave del usuario en la BBDD'));
$Log->writeLog();
SP\Common::printJSON(_('Error interno'));
SP\Response::printJSON(_('Error interno'));
}
}
} else if ($resLdap == 49) {
@@ -86,21 +89,21 @@ if ($resLdap === true) {
$Log->addDescription(_('Usuario') . ": " . $userLogin);
$Log->writeLog();
SP\Common::printJSON(_('Usuario/Clave incorrectos'));
SP\Response::printJSON(_('Usuario/Clave incorrectos'));
} else if ($resLdap === 701) {
$Log->addDescription('(LDAP)');
$Log->addDescription(_('Cuenta expirada'));
$Log->addDescription(_('Usuario') . ": " . $userLogin);
$Log->writeLog();
SP\Common::printJSON(_('Cuenta expirada'));
SP\Response::printJSON(_('Cuenta expirada'));
} else if ($resLdap === 702) {
$Log->addDescription('(LDAP)');
$Log->addDescription(_('El usuario no tiene grupos asociados'));
$Log->addDescription(_('Usuario') . ": " . $userLogin);
$Log->writeLog();
SP\Common::printJSON(_('Usuario/Clave incorrectos'));
SP\Response::printJSON(_('Usuario/Clave incorrectos'));
} else { // Autentificamos por MySQL (ha fallado LDAP)
$Log->resetDescription();
$Log->addDescription('(MySQL)');
@@ -111,7 +114,7 @@ if ($resLdap === true) {
$Log->addDescription(_('Usuario') . ": " . $userLogin);
$Log->writeLog();
SP\Common::printJSON(_('Usuario/Clave incorrectos'));
SP\Response::printJSON(_('Usuario/Clave incorrectos'));
}
}
@@ -121,7 +124,7 @@ if (UserUtil::checkUserIsDisabled($userLogin)) {
$Log->addDescription(_('Usuario') . ": " . $userLogin);
$Log->writeLog();
SP\Common::printJSON(_('Usuario deshabilitado'));
SP\Response::printJSON(_('Usuario deshabilitado'));
}
// Obtenemos los datos del usuario
@@ -129,24 +132,24 @@ if (!$User->getUserInfo()) {
$Log->addDescription(_('Error al obtener los datos del usuario de la BBDD'));
$Log->writeLog();
SP\Common::printJSON(_('Error interno'));
SP\Response::printJSON(_('Error interno'));
}
// Comprobamos que la clave maestra del usuario es correcta y está actualizada
if (!$masterPass
&& (!UserUtil::checkUserMPass($User) || !UserUtil::checkUserUpdateMPass($userLogin))
&& (!UserPass::checkUserMPass($User) || !UserPass::checkUserUpdateMPass($userLogin))
) {
SP\Common::printJSON(_('La clave maestra no ha sido guardada o es incorrecta'), 3);
SP\Response::printJSON(_('La clave maestra no ha sido guardada o es incorrecta'), 3);
} elseif ($masterPass) {
if (SP\Config::checkTempMasterPass($masterPass)) {
$masterPass = SP\Config::getTempMasterPass($masterPass);
if (CryptMasterPass::checkTempMasterPass($masterPass)) {
$masterPass = CryptMasterPass::getTempMasterPass($masterPass);
}
if (!$User->updateUserMPass($masterPass)) {
$Log->addDescription(_('Clave maestra incorrecta'));
$Log->writeLog();
SP\Common::printJSON(_('Clave maestra incorrecta'), 4);
SP\Response::printJSON(_('Clave maestra incorrecta'), 4);
}
}
@@ -154,9 +157,9 @@ if (!$masterPass
if ($User->isUserChangePass()) {
$hash = SP\Util::generate_random_bytes();
if (UserUtil::addPassRecover($userLogin, $hash)) {
if (UserPassRecover::addPassRecover($userLogin, $hash)) {
$url = SP\Init::$WEBURI . '/index.php?a=passreset&h=' . $hash . '&t=' . time() . '&f=1';
SP\Common::printJSON($url, 0);
SP\Response::printJSON($url, 0);
}
}
@@ -173,7 +176,7 @@ if ($User->getUserMPass()) {
$Log->addDescription(sprintf('%s : %s', _('Grupo'), SP\Groups::getGroupNameById($User->getUserGroupId())));
$Log->writeLog();
} else {
SP\Common::printJSON(_('Error interno'));
SP\Response::printJSON(_('Error interno'));
}
$UserPrefs = \SP\UserPreferences::getPreferences($User->getUserId());
@@ -181,7 +184,7 @@ $UserPrefs = \SP\UserPreferences::getPreferences($User->getUserId());
if ($UserPrefs->isUse2Fa()) {
SP\Session::set2FApassed(false);
$url = SP\Init::$WEBURI . '/index.php?a=2fa&i=' . $User->getUserId() . '&t=' . time() . '&f=1';
SP\Common::printJSON($url, 0);
SP\Response::printJSON($url, 0);
} else {
SP\Session::set2FApassed(true);
}
@@ -204,4 +207,4 @@ foreach ($_POST as $param => $value) {
$urlParams = (count($params) > 0) ? '?' . implode('&', $params) : '';
SP\Common::printJSON('index.php' . $urlParams, 0);
SP\Response::printJSON('index.php' . $urlParams, 0);

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
define('APP_ROOT', '..');
@@ -37,7 +38,7 @@ if (!SP\Init::isLoggedIn()) {
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
die(_('CONSULTA INVÁLIDA'));
}

View File

@@ -41,4 +41,4 @@ $data = array(
'pk' => $publicKey
);
SP\Common::printJSON($data, 0);
SP\Response::printJSON($data, 0);

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
define('APP_ROOT', '..');
@@ -42,8 +43,8 @@ if (!SP\Util::fileIsEnabled()) {
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printXML(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printXML(_('CONSULTA INVÁLIDA'));
}
$controller = new SP\Controller\AccountsMgmtC();

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
define('APP_ROOT', '..');
@@ -32,11 +33,11 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
if (SP\Util::demoIsEnabled()) {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
SP\Response::printJSON(_('Ey, esto es una DEMO!!'));
}
$sk = SP\Request::analyze('sk', false);
@@ -45,8 +46,8 @@ $defaultGroup = SP\Request::analyze('defGroup', 0);
$importPwd = SP\Request::analyzeEncrypted('importPwd');
$csvDelimiter = SP\Request::analyze('csvDelimiter');
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
SP\Import::setDefUser($defaultUser);
@@ -61,9 +62,9 @@ if (isset($res['error']) && is_array($res['error'])) {
$out = implode('\n\n', $res['error']);
SP\Common::printJSON($out);
SP\Response::printJSON($out);
} else if (is_array($res['ok'])) {
$out = implode('\n\n', $res['ok']);
SP\Common::printJSON($out, 0);
SP\Response::printJSON($out, 0);
}

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
define('APP_ROOT', '..');
@@ -32,17 +33,17 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
if (SP\Util::demoIsEnabled()) {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
SP\Response::printJSON(_('Ey, esto es una DEMO!!'));
}
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
$frmDBUser = SP\Request::analyze('dbuser');
@@ -52,15 +53,15 @@ $frmDBHost = SP\Request::analyze('dbhost');
$frmMigrateEnabled = SP\Request::analyze('chkmigrate', 0, false, 1);
if (!$frmMigrateEnabled) {
SP\Common::printJSON(_('Confirmar la importación de cuentas'));
SP\Response::printJSON(_('Confirmar la importación de cuentas'));
} elseif (!$frmDBUser) {
SP\Common::printJSON(_('Es necesario un usuario de conexión'));
SP\Response::printJSON(_('Es necesario un usuario de conexión'));
} elseif (!$frmDBPass) {
SP\Common::printJSON(_('Es necesaria una clave de conexión'));
SP\Response::printJSON(_('Es necesaria una clave de conexión'));
} elseif (!$frmDBName) {
SP\Common::printJSON(_('Es necesario el nombre de la BBDD'));
SP\Response::printJSON(_('Es necesario el nombre de la BBDD'));
} elseif (!$frmDBHost) {
SP\Common::printJSON(_('Es necesario un nombre de host'));
SP\Response::printJSON(_('Es necesario un nombre de host'));
}
$options['dbhost'] = $frmDBHost;
@@ -78,9 +79,9 @@ if (is_array($res['error'])) {
}
$out = implode('<br>', $errors);
SP\Common::printJSON($out);
SP\Response::printJSON($out);
} elseif (is_array($res['ok'])) {
$out = implode('<br>', $res['ok']);
SP\Common::printJSON($out, 0);
SP\Response::printJSON($out, 0);
}

View File

@@ -23,6 +23,9 @@
*
*/
use SP\SessionUtil;
use SP\UserPass;
use SP\UserPassRecover;
use SP\UserUtil;
define('APP_ROOT', '..');
@@ -33,8 +36,8 @@ SP\Request::checkReferer('POST');
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
$userLogin = SP\Request::analyze('login');
@@ -52,28 +55,28 @@ if ($userLogin && $userEmail) {
if (SP\Auth::mailPassRecover($userLogin, $userEmail)) {
$log->addDescription(SP\Html::strongText(_('Solicitado para') . ': ') . ' ' . $userLogin . ' (' . $userEmail . ')');
SP\Common::printJSON(_('Solicitud enviada') . ';;' . _('En breve recibirá un correo para completar la solicitud.'), 0, 'goLogin();');
SP\Response::printJSON(_('Solicitud enviada') . ';;' . _('En breve recibirá un correo para completar la solicitud.'), 0, 'goLogin();');
} else {
$log->addDescription('ERROR');
$log->addDescription(SP\Html::strongText(_('Solicitado para') . ': ') . ' ' . $userLogin . ' (' . $userEmail . ')');
SP\Common::printJSON(_('No se ha podido realizar la solicitud. Consulte con el administrador.'));
SP\Response::printJSON(_('No se ha podido realizar la solicitud. Consulte con el administrador.'));
}
$log->writeLog();
SP\Email::sendEmail($log);
} elseif ($userPass && $userPassR && $userPass === $userPassR) {
$userId = UserUtil::checkHashPassRecover($hash);
$userId = UserPassRecover::checkHashPassRecover($hash);
if ($userId) {
if (UserUtil::updateUserPass($userId, $userPass) && UserUtil::updateHashPassRecover($hash)) {
if (UserPass::updateUserPass($userId, $userPass) && UserPassRecover::updateHashPassRecover($hash)) {
\SP\Log::writeNewLogAndEmail(_('Modificar Clave Usuario'), SP\Html::strongText(_('Login') . ': ') . UserUtil::getUserLoginById($userId));
SP\Common::printJSON(_('Clave actualizada'), 0, 'goLogin();');
SP\Response::printJSON(_('Clave actualizada'), 0, 'goLogin();');
}
}
SP\Common::printJSON(_('Error al modificar la clave'));
SP\Response::printJSON(_('Error al modificar la clave'));
} else {
SP\Common::printJSON(_('La clave es incorrecta o no coincide'));
SP\Response::printJSON(_('La clave es incorrecta o no coincide'));
}

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
define('APP_ROOT', '..');
@@ -37,7 +38,7 @@ if (!SP\Init::isLoggedIn()) {
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
die('<div class="error round">' . _('CONSULTA INVÁLIDA') . '</div>');
}

View File

@@ -23,6 +23,7 @@
*
*/
use SP\SessionUtil;
use SP\UserUtil;
define('APP_ROOT', '..');
@@ -32,20 +33,20 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
SP\Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
$frmAccountId = SP\Request::analyze('accountid', 0);
$frmDescription = SP\Request::analyze('description');
if (!$frmDescription) {
SP\Common::printJSON(_('Es necesaria una descripción'));
SP\Response::printJSON(_('Es necesaria una descripción'));
}
$accountRequestData = SP\Account::getAccountRequestData($frmAccountId);
@@ -72,7 +73,7 @@ if (strlen($mailto) > 1
) {
$log->writeLog();
SP\Common::printJSON(_('Solicitud enviada'), 0, "doAction('" . \SP\Controller\ActionsInterface::ACTION_ACC_SEARCH . "');");
SP\Response::printJSON(_('Solicitud enviada'), 0, "doAction('" . \SP\Controller\ActionsInterface::ACTION_ACC_SEARCH . "');");
}
SP\Common::printJSON(_('Error al enviar la solicitud'));
SP\Response::printJSON(_('Error al enviar la solicitud'));

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\SessionUtil;
use SP\UserUtil;
define('APP_ROOT', '..');
@@ -33,13 +34,13 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
$sk = SP\Request::analyze('sk', false);
if (!$sk || !SP\Common::checkSessionKey($sk)) {
SP\Common::printJSON(_('CONSULTA INVÁLIDA'));
if (!$sk || !SessionUtil::checkSessionKey($sk)) {
SP\Response::printJSON(_('CONSULTA INVÁLIDA'));
}
// Variables POST del formulario
@@ -67,7 +68,7 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_USR_PREFERENCES_GENERAL
$UserPrefs->setSortViews($sortViews);
if (!$UserPrefs->updatePreferences()) {
SP\Common::printJSON(_('Error al actualizar preferencias'));
SP\Response::printJSON(_('Error al actualizar preferencias'));
}
// Forzar la detección del lenguaje tras actualizar
@@ -77,10 +78,10 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_USR_PREFERENCES_GENERAL
SP\Session::setUserPreferences($UserPrefs);
SP\Util::reload();
SP\Common::printJSON(_('Preferencias actualizadas'), 0, $doActionOnClose);
SP\Response::printJSON(_('Preferencias actualizadas'), 0, $doActionOnClose);
} else if ($actionId === SP\Controller\ActionsInterface::ACTION_USR_PREFERENCES_SECURITY) {
if (SP\Util::demoIsEnabled() && \SP\Session::getUserLogin() === 'demo') {
SP\Common::printJSON(_('Ey, esto es una DEMO!!'));
SP\Response::printJSON(_('Ey, esto es una DEMO!!'));
}
// Variables POST del formulario
@@ -91,7 +92,7 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_USR_PREFERENCES_GENERAL
$twoFa = new \SP\Auth\Auth2FA($itemId, $userLogin);
if (!$twoFa->verifyKey($pin)) {
SP\Common::printJSON(_('Código incorrecto'));
SP\Response::printJSON(_('Código incorrecto'));
}
// No se instancia la clase ya que es necesario guardar los atributos ya guardados
@@ -100,10 +101,10 @@ if ($actionId === SP\Controller\ActionsInterface::ACTION_USR_PREFERENCES_GENERAL
$UserPrefs->setUse2Fa(\SP\Util::boolval($twoFaEnabled));
if (!$UserPrefs->updatePreferences()) {
SP\Common::printJSON(_('Error al actualizar preferencias'));
SP\Response::printJSON(_('Error al actualizar preferencias'));
}
SP\Common::printJSON(_('Preferencias actualizadas'), 0, $doActionOnClose);
SP\Response::printJSON(_('Preferencias actualizadas'), 0, $doActionOnClose);
} else {
SP\Common::printJSON(_('Acción Inválida'));
SP\Response::printJSON(_('Acción Inválida'));
}

View File

@@ -24,6 +24,7 @@
*/
use SP\Request;
use SP\UserPass;
use SP\UserUtil;
define('APP_ROOT', '..');
@@ -33,7 +34,7 @@ require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Bas
Request::checkReferer('POST');
if (!SP\Init::isLoggedIn()) {
SP\Common::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
SP\Response::printJSON(_('La sesión no se ha iniciado o ha caducado'), 10);
}
$accountId = SP\Request::analyze('accountid', false);
@@ -51,13 +52,13 @@ $account->setAccountId($accountId);
$accountData = $account->getAccountPassData();
if ($isHistory && !$account->checkAccountMPass()) {
SP\Common::printJSON(_('La clave maestra no coincide'));
SP\Response::printJSON(_('La clave maestra no coincide'));
}
if (!SP\Acl::checkAccountAccess(SP\Acl::ACTION_ACC_VIEW_PASS, $account->getAccountDataForACL()) || !SP\Acl::checkUserAccess(SP\Acl::ACTION_ACC_VIEW_PASS)) {
SP\Common::printJSON(_('No tiene permisos para acceder a esta cuenta'));
} elseif (!UserUtil::checkUserUpdateMPass()) {
SP\Common::printJSON(_('Clave maestra actualizada') . '<br>' . _('Reinicie la sesión para cambiarla'));
SP\Response::printJSON(_('No tiene permisos para acceder a esta cuenta'));
} elseif (!UserPass::checkUserUpdateMPass()) {
SP\Response::printJSON(_('Clave maestra actualizada') . '<br>' . _('Reinicie la sesión para cambiarla'));
}
$accountClearPass = SP\Crypt::getDecrypt($accountData->pass, $accountData->iv);
@@ -82,4 +83,4 @@ $data = array(
'useimage' => $useImage
);
SP\Common::printJSON($data, 0);
SP\Response::printJSON($data, 0);

View File

@@ -25,7 +25,7 @@
define('APP_ROOT', '.');
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
require APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
try {
$ApiRequest = new \SP\ApiRequest();
@@ -53,7 +53,7 @@ try {
throw new Exception(_('Acción Inválida'));
}
} catch (Exception $e) {
\SP\Common::printJSON(array($e->getMessage(), _('Ayuda Parámetros') => \SP\ApiRequest::getHelp()));
\SP\Response::printJSON(array($e->getMessage(), _('Ayuda Parámetros') => \SP\ApiRequest::getHelp()));
}
header('Content-type: application/json');

View File

@@ -122,25 +122,42 @@ class Account extends AccountBase implements AccountInterface
$Log->resetDescription();
}
if (!UserUtil::updateUsersForAccount($this->getAccountId(), $this->getAccountUsersId())) {
if (!UserAccounts::updateUsersForAccount($this->getAccountId(), $this->getAccountUsersId())) {
$Log->addDescription(_('Error al actualizar los usuarios de la cuenta'));
$Log->writeLog();
$Log->resetDescription();
}
$query = 'UPDATE accounts SET '
. 'account_customerId = :accountCustomerId,'
. 'account_categoryId = :accountCategoryId,'
. 'account_name = :accountName,'
. 'account_login = :accountLogin,'
. 'account_url = :accountUrl,'
. 'account_notes = :accountNotes,'
. 'account_userEditId = :accountUserEditId,'
. 'account_userGroupId = :accountUserGroupId,'
. 'account_dateEdit = NOW(),'
. 'account_otherUserEdit = :accountOtherUserEdit,'
. 'account_otherGroupEdit = :accountOtherGroupEdit '
. 'WHERE account_id = :accountId';
if ($this->getAccountUserGroupId()) {
$query = 'UPDATE accounts SET '
. 'account_customerId = :accountCustomerId,'
. 'account_categoryId = :accountCategoryId,'
. 'account_name = :accountName,'
. 'account_login = :accountLogin,'
. 'account_url = :accountUrl,'
. 'account_notes = :accountNotes,'
. 'account_userEditId = :accountUserEditId,'
. 'account_userGroupId = :accountUserGroupId,'
. 'account_dateEdit = NOW(),'
. 'account_otherUserEdit = :accountOtherUserEdit,'
. 'account_otherGroupEdit = :accountOtherGroupEdit '
. 'WHERE account_id = :accountId';
$data['accountUserGroupId'] = $this->getAccountUserGroupId();
} else {
$query = 'UPDATE accounts SET '
. 'account_customerId = :accountCustomerId,'
. 'account_categoryId = :accountCategoryId,'
. 'account_name = :accountName,'
. 'account_login = :accountLogin,'
. 'account_url = :accountUrl,'
. 'account_notes = :accountNotes,'
. 'account_userEditId = :accountUserEditId,'
. 'account_dateEdit = NOW(),'
. 'account_otherUserEdit = :accountOtherUserEdit,'
. 'account_otherGroupEdit = :accountOtherGroupEdit '
. 'WHERE account_id = :accountId';
}
$data['accountCustomerId'] = $this->getAccountCustomerId();
$data['accountCategoryId'] = $this->getAccountCategoryId();
@@ -149,7 +166,6 @@ class Account extends AccountBase implements AccountInterface
$data['accountUrl'] = $this->getAccountUrl();
$data['accountNotes'] = $this->getAccountNotes();
$data['accountUserEditId'] = $this->getAccountUserEditId();
$data['accountUserGroupId'] = ($this->getAccountUserGroupId()) ? $this->getAccountUserGroupId() : 'account_userGroupId';
$data['accountOtherUserEdit'] = intval($this->getAccountOtherUserEdit());
$data['accountOtherGroupEdit'] = intval($this->getAccountOtherGroupEdit());
$data['accountId'] = $this->getAccountId();
@@ -195,6 +211,7 @@ class Account extends AccountBase implements AccountInterface
. 'dst.account_login = src.acchistory_login,'
. 'dst.account_url = src.acchistory_url,'
. 'dst.account_notes = src.acchistory_notes,'
. 'dst.account_userGroupId = src.acchistory_userGroupId,'
. 'dst.account_userEditId = :accountUserEditId,'
. 'dst.account_dateEdit = NOW(),'
. 'dst.account_otherUserEdit = src.acchistory_otherUserEdit + 0,'
@@ -385,7 +402,7 @@ class Account extends AccountBase implements AccountInterface
}
if (is_array($this->getAccountUsersId())) {
if (!UserUtil::addUsersForAccount($this->getAccountId(), $this->getAccountUsersId())) {
if (!UserAccounts::addUsersForAccount($this->getAccountId(), $this->getAccountUsersId())) {
$Log->addDescription(_('Error al actualizar los usuarios de la cuenta'));
$Log->writeLog();
$Log->resetDescription();
@@ -434,7 +451,7 @@ class Account extends AccountBase implements AccountInterface
$Log->addDescription(_('Error al eliminar grupos asociados a la cuenta'));
}
if (!UserUtil::deleteUsersForAccount($this->getAccountId())) {
if (!UserAccounts::deleteUsersForAccount($this->getAccountId())) {
$Log->addDescription(_('Error al eliminar usuarios asociados a la cuenta'));
}

View File

@@ -301,7 +301,7 @@ abstract class AccountBase
if (!isset($cacheUsers[$accId])
|| time() > $cacheUsers['expires']
) {
$cacheUsers[$accId] = UserUtil::getUsersForAccount($accId);
$cacheUsers[$accId] = UserAccounts::getUsersForAccount($accId);
$cacheUsers['expires'] = time() + self::CACHE_EXPIRE_TIME;
}

View File

@@ -27,6 +27,11 @@ namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class AccountHistory par el manejo del historial de cuentas
*
* @package SP
*/
class AccountHistory extends AccountBase implements AccountInterface
{
private $_isDelete = false;
@@ -230,7 +235,7 @@ class AccountHistory extends AccountBase implements AccountInterface
'AND acchistory_mPassHash = :mPassHash';
$data['id'] = (is_null($id)) ? $this->getAccountId() : $id;
$data['mPassHash'] = Config::getConfigDbValue('masterPwd');
$data['mPassHash'] = ConfigDB::getValue('masterPwd');
return (DB::getResults($query, __FUNCTION__, $data) !== false);
}
@@ -395,7 +400,7 @@ class AccountHistory extends AccountBase implements AccountInterface
$data['accountOtherGroupEdit'] = $this->getAccountOtherGroupEdit();
$data['isModify'] = $this->isIsModify();
$data['isDelete'] = $this->isIsDelete();
$data['masterPwd'] = Config::getConfigDbValue('masterPwd');
$data['masterPwd'] = ConfigDB::getValue('masterPwd');
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
@@ -479,7 +484,7 @@ class AccountHistory extends AccountBase implements AccountInterface
$data['account_id'] = $id;
$data['isModify'] = ($isDelete === false) ? 1 : 0;
$data['isDelete'] = ($isDelete === false) ? 0 : 1;
$data['masterPwd'] = Config::getConfigDbValue('masterPwd');
$data['masterPwd'] = ConfigDB::getValue('masterPwd');
return DB::getQuery($query, __FUNCTION__, $data);
}

View File

@@ -1,62 +0,0 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace Controller;
interface ActionsI {
const ACTION__ACC_SEARCH = 1;
const ACTION_ACC_VIEW = 2;
const ACTION_ACC_VIEW_PASS = 3;
const ACTION_ACC_VIEW_HISTORY = 4;
const ACTION_ACC_EDIT = 10;
const ACTION_ACC_EDIT_PASS = 11;
const ACTION_ACC_NEW = 20;
const ACTION_ACC_COPY = 30;
const ACTION_ACC_DELETE = 40;
const ACTION_ACC_FILES = 50;
const ACTION_ACC_REQUEST = 51;
const ACTION_MGM = 60;
const ACTION_MGM_CATEGORIES = 61;
const ACTION_MGM_CUSTOMERS = 62;
const ACTION_USR = 70;
const ACTION_USR_USERS = 71;
const ACTION_USR_USERS_NEW = 711;
const ACTION_USR_USERS_EDIT = 712;
const ACTION_USR_USERS_EDITPASS = 713;
const ACTION_USR_GROUPS = 72;
const ACTION_USR_GROUPS_NEW = 721;
const ACTION_USR_GROUPS_EDIT = 722;
const ACTION_USR_PROFILES = 73;
const ACTION_USR_PROFILES_NEW = 731;
const ACTION_USR_PROFILES_EDIT = 732;
const ACTION_CFG = 80;
const ACTION_CFG_GENERAL = 81;
const ACTION_CFG_ENCRYPTION = 82;
const ACTION_CFG_ENCRYPTION_TEMPPASS = 83;
const ACTION_CFG_BACKUP = 84;
const ACTION_CFG_IMPORT = 85;
const ACTION_EVL = 90;
}

View File

@@ -79,8 +79,8 @@ class Api
if (Auth::authUserMySQL($userLogin, $userPass)
&& !UserUtil::checkUserIsDisabled($userLogin)
&& UserUtil::checkUserMPass($User)
&& UserUtil::checkUserUpdateMPass($userLogin)
&& UserPass::checkUserMPass($User)
&& UserPass::checkUserUpdateMPass($userLogin)
&& !$User->isUserChangePass()
) {
$this->_mPass = $User->getUserMPass(true);

View File

@@ -149,8 +149,8 @@ class Auth
*/
public static function authUserMySQL($userLogin, $userPass)
{
if (UserUtil::checkUserIsMigrate($userLogin)) {
if (!UserUtil::migrateUser($userLogin, $userPass)) {
if (UserMigrate::checkUserIsMigrate($userLogin)) {
if (!UserMigrate::migrateUser($userLogin, $userPass)) {
return false;
}
}
@@ -179,7 +179,7 @@ class Auth
if (UserUtil::checkUserMail($login, $email)
&& !UserUtil::checkUserIsDisabled($login)
&& !UserLdap::checkUserIsLDAP($login)
&& !UserUtil::checkPassRecoverLimit($login)
&& !UserPassRecover::checkPassRecoverLimit($login)
) {
$hash = Util::generate_random_bytes();
@@ -193,7 +193,7 @@ class Auth
$log->addDescription('');
$log->addDescription(_('Si no ha solicitado esta acción, ignore este mensaje.'));
return (Email::sendEmail($log, $email, false) && UserUtil::addPassRecover($login, $hash));
return (Email::sendEmail($log, $email, false) && UserPassRecover::addPassRecover($login, $hash));
} else {
return false;
}

View File

@@ -27,7 +27,8 @@ namespace SP\Auth;
use SP\Exts\Google2FA;
use SP\Exts\Base2n;
use SP\UserUtil;
use SP\UserPass;
use SP\Util;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
@@ -59,6 +60,10 @@ class Auth2FA
*/
private $_userLogin = '';
/**
* @param int $userId El Id de usuario
* @param string $userLogin El login de usuario
*/
public function __construct($userId, $userLogin = null)
{
$this->_userId = $userId;
@@ -66,6 +71,20 @@ class Auth2FA
$this->_initializationKey = $this->genUserInitializationKey();
}
/**
* Generar una clave de inicialización codificada en Base32
*
* @return string
*/
private function genUserInitializationKey()
{
$userIV = UserPass::getUserIVById($this->_userId);
$base32 = new Base2n(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', false, true, true);
$key = substr($base32->encode($userIV), 0, 16);
return $key;
}
/**
* @param int $userId
*/
@@ -93,25 +112,14 @@ class Auth2FA
return Google2FA::verify_key($this->_initializationKey, $key);
}
public function getUserQRUrl(){
$qrUrl = 'https://www.google.com/chart?chs=150x150&chld=M|0&cht=qr&chl=';
$qrUrl .= urlencode('otpauth://totp/sysPass:syspass/' . $this->_userLogin . '?secret=' . $this->_initializationKey . '&issuer=sysPass');
return $qrUrl;
}
/**
* Devolver el código QR de la peticíón HTTP en base64
*
* @return bool|string
*/
public function getUserQRCode()
{
$ch = curl_init($this->getUserQRUrl());
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERAGENT, "sysPass 2FA");
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
$data = curl_exec($ch);
curl_close($ch);
$data = Util::getDataFromUrl($this->getUserQRUrl());
if ($data === false) {
return false;
@@ -120,6 +128,26 @@ class Auth2FA
return base64_encode($data);
}
/**
* Devolver la cadena con la URL para solicitar el código QR
*
* @return string
*/
public function getUserQRUrl()
{
$qrUrl = 'https://www.google.com/chart?chs=150x150&chld=M|0&cht=qr&chl=';
$qrUrl .= urlencode('otpauth://totp/sysPass:syspass/' . $this->_userLogin . '?secret=' . $this->_initializationKey . '&issuer=sysPass');
return $qrUrl;
}
/**
* Comprobar el token del usuario
*
* @param int $userToken EL código del usuario
* @return bool
* @throws \Exception
*/
public function checkUserToken($userToken)
{
$timeStamp = Google2FA::get_timestamp();
@@ -130,13 +158,4 @@ class Auth2FA
return ($totp == $userToken);
}
private function genUserInitializationKey()
{
$userIV = UserUtil::getUserIVById($this->_userId);
$base32 = new Base2n(5, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567', false, true, true);
$key = substr($base32->encode($userIV), 0, 16);
return $key;
}
}

View File

@@ -23,6 +23,9 @@
*
*/
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
define('CONFIG_FILE', __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php');
define('MODEL_PATH', __DIR__);
define('CONTROLLER_PATH', __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'web');
define('VIEW_PATH', __DIR__ . DIRECTORY_SEPARATOR . 'themes');

View File

@@ -25,6 +25,8 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Clase base para guardar/obtener elementos de la caché
*/

View File

@@ -29,156 +29,41 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
/**
* Esta clase es responsable de leer y escribir la configuración del archivo config.php
* y en la base de datos
*/
class Config
class Config implements ConfigInterface
{
/**
* @var array
*/
private static $_config;
/**
* @var array
*/
private static $_cache = array();
protected static $_cache;
/**
* @var bool
*/
private static $_init = false;
protected static $_init;
/**
* @param null $key La clave a obtener
* @return mixed
*/
public static function getArrConfigValue($key = null)
{
if (!is_null($key) && isset(self::$_config[$key])) {
return self::$_config[$key];
}
return self::$_config;
}
/**
* @param $key string La clave a actualizar
* @param $value mixed El valor a actualizar
*/
public static function setArrConfigValue($key, $value)
{
// if (isset(self::$_config[$key])) {
self::$_config[$key] = $value;
// }
}
/**
* Obtener un array con la configuración almacenada en la BBDD.
* Obtiene un valor de configuración desde el archivo
*
* @return bool
*/
public static function getConfigDb()
{
$query = 'SELECT config_parameter, config_value FROM config';
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === false) {
return false;
}
foreach ($queryRes as $config) {
self::$_config[$config->config_parameter] = $config->config_value;
}
}
/**
* Guardar la configuración en la BBDD.
*
* @param bool $mkInsert realizar un 'insert'?
* @return bool
*/
public static function writeConfigDb($mkInsert = false)
{
foreach (self::$_config as $param => $value) {
if ($mkInsert) {
$query = 'INSERT INTO config VALUES (:param,:value) ON DUPLICATE KEY UPDATE config_value = :valuedup';
$data['valuedup'] = $value;
} else {
$query = 'UPDATE config SET config_value = :value WHERE config_parameter = :param';
}
$data['param'] = $param;
$data['value'] = $value;
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
}
}
Log::writeNewLogAndEmail(_('Configuración'), _('Modificar configuración'));
return true;
}
/**
* Cargar la configuración desde la BBDD a variable global $CFG.
*
* @param bool $force reescribir la variable global $CFG?
* @return bool
*/
public static function getDBConfig($force = false)
{
global $CFG;
if (isset ($CFG) && !$force) {
return true;
}
$query = 'SELECT config_parameter, config_value FROM config';
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === false) {
return false;
}
foreach ($queryRes as $config) {
$cfgParam = $config->config_parameter;
$cfgValue = $config->config_value;
if (strstr($cfgValue, "||")) {
$cfgValue = explode("||", $cfgValue);
}
$CFG["$cfgParam"] = $cfgValue;
}
return true;
}
/**
* Obtiene un valor de configuración desde el archivo config.php
*
* @param string $key clave
* @param string $param clave
* @param string $default = null valor por defecto
* @return string el valor o $default
*/
public static function getValue($key, $default = null)
public static function getValue($param, $default = null)
{
$param = Cache::getSessionCacheConfigValue($key);
$params = Cache::getSessionCacheConfigValue($param);
return (!is_null($param)) ? $param : $default;
return (!is_null($params)) ? $params : $default;
}
/**
* Lista todas las claves de configuración guardadas en config.php.
* Lista todas las claves de configuración guardadas
*
* @param bool $full obtener todas las claves y sus valores
* @return array con nombres de claves
*/
public static function getKeys($full = false)
{
self::readData();
self::readConfig();
if ($full) {
return self::$_cache;
@@ -192,20 +77,18 @@ class Config
*
* @return bool
*/
private static function readData()
public static function readConfig()
{
if (self::$_init) {
return true;
}
$configFile = self::getConfigFile();;
if (!file_exists($configFile)) {
if (!file_exists(CONFIG_FILE)) {
return false;
}
// Include the file, save the data from $CONFIG
include_once $configFile;
include_once CONFIG_FILE;
if (isset($CONFIG) && is_array($CONFIG)) {
self::$_cache = $CONFIG;
@@ -217,34 +100,24 @@ class Config
return true;
}
/**
* Devolver la ruta al archivo de configuración
*
* @return string Con la ruta
*/
private static function getConfigFile()
{
return Init::$SERVERROOT . DIRECTORY_SEPARATOR . 'config' . DIRECTORY_SEPARATOR . 'config.php';
}
/**
* Elimina una clave de la configuración.
* Esta función elimina una clave de configmgmt.php. Si no tiene permiso
* de escritura en configmgmt.php, devolverá false.
* Esta función elimina una clave de config.php. Si no tiene permiso
* de escritura en config.php, devolverá false.
*
* @param string $key clave
* @param string $param clave
* @return bool
*/
public static function deleteKey($key)
public static function deleteParam($param)
{
self::readData();
self::readConfig();
if (isset(self::$_cache[$key])) {
if (isset(self::$_cache[$param])) {
// Eliminar la clave de la caché
unset(self::$_cache[$key]);
unset(self::$_cache[$param]);
// Guardar los cambios en la configuración
self::writeData();
self::writeConfig();
}
return true;
@@ -254,8 +127,9 @@ class Config
* Escribe en archivo de configuración.
*
* @return bool
* @throws SPException
*/
public static function writeData()
public static function writeConfig()
{
// Ordenar las claves de la configuración
ksort(self::$_cache);
@@ -267,17 +141,15 @@ class Config
$content .= trim(var_export(self::$_cache, true), ',');
$content .= ";\n";
$configFile = self::getConfigFile();
// Escribir el archivo de configuración
$result = @file_put_contents($configFile, $content);
$result = @file_put_contents(CONFIG_FILE, $content);
if (!$result) {
Init::initError(_('No es posible escribir el archivo de configuración'), _('Compruebe los permisos del directorio "config"'));
throw new SPException(SPException::SP_CRITICAL, _('No es posible escribir el archivo de configuración'), _('Compruebe los permisos del directorio "config"'));
}
// Establecer los permisos del archivo de configuración
chmod($configFile, 0640);
chmod(CONFIG_FILE, 0640);
// Actualizar la caché de configuración de la sesión
Cache::setSessionCacheConfig();
@@ -290,39 +162,57 @@ class Config
*/
public static function setDefaultValues()
{
self::setValue('debug', false);
self::setValue('log_enabled', true);
self::setValue('ldap_enabled', false);
self::setValue('mail_enabled', false);
self::setValue('wiki_enabled', false);
self::setValue('demo_enabled', false);
self::setValue('files_enabled', true);
self::setValue('proxy_enabled', false);
self::setValue('checkupdates', true);
self::setValue('checknotices', true);
self::setValue('globalsearch', false);
self::setValue('account_passtoimage', false);
self::setValue('resultsascards', false);
self::setValue('files_allowed_exts', 'PDF,JPG,GIF,PNG,ODT,ODS,DOC,DOCX,XLS,XSL,VSD,TXT,CSV,BAK');
self::setValue('files_allowed_size', 1024);
self::setValue('wiki_searchurl', '');
self::setValue('wiki_pageurl', '');
self::setValue('wiki_filter', '');
self::setValue('ldap_server', '');
self::setValue('ldap_base', '');
self::setValue('ldap_group', '');
self::setValue('ldap_userattr', '');
self::setValue('mail_server', '');
self::setValue('mail_from', '');
self::setValue('site_lang', str_replace('.utf8', '', Language::$globalLang));
self::setValue('session_timeout', '300');
self::setValue('account_link', 1);
self::setValue('account_count', 12);
self::setValue('sitetheme', 'material-blue');
self::setValue('proxy_server', '');
self::setValue('proxy_port', '');
self::setValue('proxy_user', '');
self::setValue('proxy_pass', '');
self::setCacheConfigValue('debug', false);
self::setCacheConfigValue('log_enabled', true);
self::setCacheConfigValue('ldap_enabled', false);
self::setCacheConfigValue('mail_enabled', false);
self::setCacheConfigValue('wiki_enabled', false);
self::setCacheConfigValue('demo_enabled', false);
self::setCacheConfigValue('files_enabled', true);
self::setCacheConfigValue('proxy_enabled', false);
self::setCacheConfigValue('checkupdates', true);
self::setCacheConfigValue('checknotices', true);
self::setCacheConfigValue('globalsearch', false);
self::setCacheConfigValue('account_passtoimage', false);
self::setCacheConfigValue('resultsascards', false);
self::setCacheConfigValue('files_allowed_exts', 'PDF,JPG,GIF,PNG,ODT,ODS,DOC,DOCX,XLS,XSL,VSD,TXT,CSV,BAK');
self::setCacheConfigValue('files_allowed_size', 1024);
self::setCacheConfigValue('wiki_searchurl', '');
self::setCacheConfigValue('wiki_pageurl', '');
self::setCacheConfigValue('wiki_filter', '');
self::setCacheConfigValue('ldap_server', '');
self::setCacheConfigValue('ldap_base', '');
self::setCacheConfigValue('ldap_group', '');
self::setCacheConfigValue('ldap_userattr', '');
self::setCacheConfigValue('mail_server', '');
self::setCacheConfigValue('mail_from', '');
self::setCacheConfigValue('site_lang', str_replace('.utf8', '', Language::$globalLang));
self::setCacheConfigValue('session_timeout', '300');
self::setCacheConfigValue('account_link', 1);
self::setCacheConfigValue('account_count', 12);
self::setCacheConfigValue('sitetheme', 'material-blue');
self::setCacheConfigValue('proxy_server', '');
self::setCacheConfigValue('proxy_port', '');
self::setCacheConfigValue('proxy_user', '');
self::setCacheConfigValue('proxy_pass', '');
self::writeConfig();
}
/**
* Actualizar el array de parámetros de configuración
*
* @param $param string El parámetro a actualizar
* @param $value mixed El valor a actualizar
*/
public static function setCacheConfigValue($param, $value)
{
// Comprobar que la configuración está cargada
if (count(self::$_cache) === 0){
self::readConfig();
}
self::$_cache[$param] = $value;
}
/**
@@ -330,156 +220,25 @@ class Config
* Esta función establece el valor y reescribe config.php. Si el archivo
* no se puede escribir, devolverá false.
*
* @param string $key clave
* @param string $param clave
* @param string $value valor
* @return bool
*/
public static function setValue($key, $value)
public static function setValue($param, $value)
{
self::readData();
self::readConfig();
// Añadir/Modificar el parámetro
self::$_cache[$key] = $value;
self::$_cache[$param] = $value;
// Generar el hash de la configuración
self::$_cache['config_hash'] = md5(implode(self::$_cache));
// Guardar los cambios
self::writeData();
self::writeConfig();
return true;
}
/**
* Crea una clave temporal para encriptar la clave maestra y guardarla.
*
* @return bool|string
*/
public static function setTempMasterPass($maxTime = 14400)
{
// Encriptar la clave maestra con hash aleatorio generado
$randomKey = Crypt::generateAesKey(Util::generate_random_bytes());
$pass = Crypt::mkCustomMPassEncrypt($randomKey, Crypt::getSessionMasterPass());
if (!is_array($pass)) {
return false;
}
self::setConfigDbValue('tempmaster_pass', bin2hex($pass[0]), false);
self::setConfigDbValue('tempmaster_passiv', bin2hex($pass[1]), false);
self::setConfigDbValue('tempmaster_passhash', Crypt::mkHashPassword($randomKey), false);
self::setConfigDbValue('tempmaster_passtime', time(), false);
self::setConfigDbValue('tempmaster_maxtime', time() + $maxTime, false);
self::setConfigDbValue('tempmaster_attempts', 0, false);
// Guardar la clave temporal hasta que finalice la sesión
Session::setTemporaryMasterPass($randomKey);
return $randomKey;
}
/**
* Guardar un parámetro de configuración en la BBDD.
*
* @param string $param con el parámetro a guardar
* @param string $value con el valor a guardar
* @param bool $email enviar email?
* @return bool
*/
public static function setConfigDbValue($param, $value, $email = true)
{
$query = "INSERT INTO config "
. "SET config_parameter = :param,"
. "config_value = :value "
. "ON DUPLICATE KEY UPDATE config_value = :valuedup";
$data['param'] = $param;
$data['value'] = $value;
$data['valuedup'] = $value;
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
}
$log = new Log(_('Configuración'));
$log->addDescription(_('Modificar configuración'));
$log->addDescription(_('Parámetro') . ': ' . $param);
$log->addDescription(_('Valor') . ': ' . $value);
$log->writeLog();
if ($email === true) {
Email::sendEmail($log);
}
return true;
}
/**
* Comprueba si la clave temporal es válida
*
* @param string $pass clave a comprobar
* @return bool
*/
public static function checkTempMasterPass($pass)
{
$passTime = self::getConfigDbValue('tempmaster_passtime');
$passMaxTime = self::getConfigDbValue('tempmaster_maxtime');
$attempts = self::getConfigDbValue('tempmaster_attempts');
// Comprobar si el tiempo de validez se ha superado
if ($passTime !== false && time() - $passTime > $passMaxTime || $attempts >= 5) {
self::setConfigDbValue('tempmaster_pass', '', false);
self::setConfigDbValue('tempmaster_passiv', '', false);
self::setConfigDbValue('tempmaster_passhash', '', false);
return false;
}
Crypt::checkHashPass($pass, self::getConfigDbValue('tempmaster_passhash'));
$isValid = Crypt::checkHashPass($pass, self::getConfigDbValue('tempmaster_passhash'));
if (!$isValid) {
self::setConfigDbValue('tempmaster_attempts', $attempts + 1, false);
}
return $isValid;
}
/**
* Obtiene un valor desde la configuración en la BBDD.
*
* @param string $param con el parámetro de configuración
* @return false|string con el valor
*/
public static function getConfigDbValue($param)
{
$query = 'SELECT config_value FROM config WHERE config_parameter = :parameter LIMIT 1';
$data['parameter'] = $param;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
return $queryRes->config_value;
}
/**
* Devuelve la clave maestra que ha sido encriptada con la clave temporal
*
* @param $pass string con la clave utilizada para encriptar
* @return string con la clave maestra desencriptada
*/
public static function getTempMasterPass($pass)
{
$passLogin = hex2bin(self::getConfigDbValue('tempmaster_pass'));
$passLoginIV = hex2bin(self::getConfigDbValue('tempmaster_passiv'));
return Crypt::getDecrypt($passLogin, $passLoginIV, $pass);
}
/**
* Obtener la configuración de sysPass
*
@@ -487,10 +246,20 @@ class Config
*/
public static function getConfig()
{
if (self::readData()) {
if (self::readConfig()) {
return self::$_cache;
}
return false;
}
/**
* Obtener un parámetro del array de parámetros de configuración
*
* @param $param string El parámetro a obtener
*/
public static function getCacheConfigValue($param)
{
return self::$_cache[$param];
}
}

193
inc/ConfigDB.class.php Normal file
View File

@@ -0,0 +1,193 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class ConfigDB para la gestión de la configuración en la BD
*
* @package SP
*/
class ConfigDB implements ConfigInterface
{
/**
* @var array
*/
protected static $_cache;
/**
* @var bool
*/
protected static $_init;
/**
* Obtener un array con la configuración almacenada en la BBDD.
*
* @return bool
*/
public static function readConfig()
{
$query = 'SELECT config_parameter, config_value FROM config';
$queryRes = DB::getResults($query, __FUNCTION__);
if ($queryRes === false) {
return false;
}
foreach ($queryRes as $config) {
self::$_cache[$config->config_parameter] = $config->config_value;
}
}
/**
* Guardar la configuración en la BBDD.
*
* @param bool $isInsert realizar un 'insert'?
* @return bool
*/
public static function writeConfig($isInsert = false)
{
foreach (self::$_cache as $param => $value) {
if ($isInsert) {
$query = 'INSERT INTO config VALUES (:param,:value) ON DUPLICATE KEY UPDATE config_value = :valuedup';
$data['valuedup'] = $value;
} else {
$query = 'UPDATE config SET config_value = :value WHERE config_parameter = :param';
}
$data['param'] = $param;
$data['value'] = $value;
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
}
}
Log::writeNewLogAndEmail(_('Configuración'), _('Modificar configuración'));
return true;
}
/**
* Guardar un parámetro de configuración en la BBDD.
*
* @param string $param con el parámetro a guardar
* @param string $value con el valor a guardar
* @param bool $email enviar email?
* @return bool
*/
public static function setValue($param, $value, $email = true)
{
$query = "INSERT INTO config "
. "SET config_parameter = :param,"
. "config_value = :value "
. "ON DUPLICATE KEY UPDATE config_value = :valuedup";
$data['param'] = $param;
$data['value'] = $value;
$data['valuedup'] = $value;
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
}
$log = new Log(_('Configuración'));
$log->addDescription(_('Modificar configuración'));
$log->addDescription(_('Parámetro') . ': ' . $param);
$log->addDescription(_('Valor') . ': ' . $value);
$log->writeLog();
if ($email === true) {
Email::sendEmail($log);
}
return true;
}
/**
* Actualizar el array de parámetros de configuración
*
* @param $param string La clave a actualizar
* @param $value mixed El valor a actualizar
*/
public static function setCacheConfigValue($param, $value)
{
self::$_cache[$param] = $value;
}
/**
* Obtener un parámetro del el array de parámetros de configuración
*
* @param null $param La clave a obtener
* @return mixed
*/
public static function getCacheConfigValue($param = null)
{
if (!is_null($param) && isset(self::$_cache[$param])) {
return self::$_cache[$param];
}
return self::$_cache;
}
/**
* Obtiene un valor desde la configuración en la BBDD.
*
* @param string $param con el parámetro de configuración
* @param string $default El valor por defecto
* @return false|string con el valor
*/
public static function getValue($param, $default = null)
{
$query = 'SELECT config_value FROM config WHERE config_parameter = :parameter LIMIT 1';
$data['parameter'] = $param;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
return ($queryRes->config_value) ? $queryRes->config_value : $default;
}
/**
* Elimina un parámetro de la configuración.
*
* @param string $param clave
* @return bool
*/
public static function deleteParam($param)
{
$query = 'DELETE FROM config WHERE config_parameter = :param LIMIT 1';
$data['param'] = $param;
return (DB::getQuery($query, __FUNCTION__, $data) !== false);
}
}

View File

@@ -0,0 +1,84 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Interface ConfigInterface para las clases que gestionan la configuración de sysPass
*
* @package SP
*/
interface ConfigInterface
{
/**
* Obtiene un valor de configuración
*
* @param string $param El valor a obtener
* @param string $default El valor por defecto
* @return string el valor o $default
*/
static function getValue($param, $default = null);
/**
* Guardar un parámetro de configuración
*
* @param string $param El parámetro a guardar
* @param string $value El valor a guardar
* @return bool
*/
static function setValue($param, $value);
/**
* Elimina un parámetro de la configuración.
*
* @param string $param clave
* @return bool
*/
static function deleteParam($param);
/**
* Actualizar el array de parámetros de configuración
*
* @param $param string El parámetro a actualizar
* @param $value mixed El valor a actualizar
*/
static function setCacheConfigValue($param, $value);
/**
* Obtener un parámetro del array de parámetros de configuración
*
* @param $param string El parámetro a devolver
*/
static function getCacheConfigValue($param);
/**
* Obtener un array con la configuración almacenada.
*
* @return bool
*/
static function readConfig();
}

View File

@@ -115,7 +115,7 @@ class Crypt
// Comprobar si el hash está en formato anterior a 12002
if ($isMPass && strlen($originalHash) === 128) {
Config::setConfigDbValue('masterPwd', self::mkHashPassword($pwd));
ConfigDB::setValue('masterPwd', self::mkHashPassword($pwd));
Log::writeNewLog(_('Aviso'), _('Se ha regenerado el HASH de clave maestra. No es necesaria ninguna acción.'));
return (hash("sha256", substr($originalHash, 0, 64) . $pwd) == substr($originalHash, 64, 64));
@@ -219,7 +219,7 @@ class Crypt
*/
public static function mkEncrypt($data, $masterPwd = null)
{
$masterPwd = (is_null($masterPwd)) ? self::getSessionMasterPass() : $masterPwd;
$masterPwd = (is_null($masterPwd)) ? SessionUtil::getSessionMPass() : $masterPwd;
self::$strInitialVector = self::getIV();
$cryptValue = self::encrypt($data, $masterPwd, self::$strInitialVector);
@@ -227,16 +227,6 @@ class Crypt
return $cryptValue;
}
/**
* Desencriptar la clave maestra de la sesión.
*
* @return string con la clave maestra
*/
public static function getSessionMasterPass()
{
return self::getDecrypt(Session::getMPass(), Session::getMPassIV(), Session::getMPassPwd());
}
/**
* Desencriptar datos con la clave maestra.
*
@@ -248,7 +238,8 @@ class Crypt
public static function getDecrypt($cryptData, $cryptIV, $password = null)
{
if (is_null($password)) {
$password = self::getSessionMasterPass();
$password = SessionUtil::getSessionMPass();
// self::getSessionMasterPass();
}
$mcryptRes = self::getMcryptResource();

View File

@@ -0,0 +1,116 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class CryptMasterPass para la gestión de la clave maestra
*
* @package SP
*/
class CryptMasterPass
{
/**
* Crea una clave temporal para encriptar la clave maestra y guardarla.
*
* @param int $maxTime El tiempo máximo de validez de la clave
* @return bool|string
*/
public static function setTempMasterPass($maxTime = 14400)
{
// Encriptar la clave maestra con hash aleatorio generado
$randomKey = Crypt::generateAesKey(Util::generate_random_bytes());
$pass = Crypt::mkCustomMPassEncrypt($randomKey, SessionUtil::getSessionMPass());
if (!is_array($pass)) {
return false;
}
ConfigDB::setCacheConfigValue('tempmaster_pass', bin2hex($pass[0]));
ConfigDB::setCacheConfigValue('tempmaster_passiv', bin2hex($pass[1]));
ConfigDB::setCacheConfigValue('tempmaster_passhash', Crypt::mkHashPassword($randomKey));
ConfigDB::setCacheConfigValue('tempmaster_passtime', time());
ConfigDB::setCacheConfigValue('tempmaster_maxtime', time() + $maxTime);
ConfigDB::setCacheConfigValue('tempmaster_attempts', 0);
if (!ConfigDB::writeConfig(true)) {
return false;
}
// Guardar la clave temporal hasta que finalice la sesión
Session::setTemporaryMasterPass($randomKey);
return $randomKey;
}
/**
* Comprueba si la clave temporal es válida
*
* @param string $pass clave a comprobar
* @return bool
*/
public static function checkTempMasterPass($pass)
{
$passTime = ConfigDB::getValue('tempmaster_passtime');
$passMaxTime = ConfigDB::getValue('tempmaster_maxtime');
$attempts = ConfigDB::getValue('tempmaster_attempts');
// Comprobar si el tiempo de validez se ha superado
if ($passTime !== false && time() - $passTime > $passMaxTime || $attempts >= 5) {
ConfigDB::setCacheConfigValue('tempmaster_pass', '');
ConfigDB::setCacheConfigValue('tempmaster_passiv', '');
ConfigDB::setCacheConfigValue('tempmaster_passhash', '');
ConfigDB::writeConfig();
return false;
}
Crypt::checkHashPass($pass, ConfigDB::getValue('tempmaster_passhash'));
$isValid = Crypt::checkHashPass($pass, ConfigDB::getValue('tempmaster_passhash'));
if (!$isValid) {
ConfigDB::setValue('tempmaster_attempts', $attempts + 1, false);
}
return $isValid;
}
/**
* Devuelve la clave maestra que ha sido encriptada con la clave temporal
*
* @param $pass string con la clave utilizada para encriptar
* @return string con la clave maestra desencriptada
*/
public static function getTempMasterPass($pass)
{
$passLogin = hex2bin(ConfigDB::getValue('tempmaster_pass'));
$passLoginIV = hex2bin(ConfigDB::getValue('tempmaster_passiv'));
return Crypt::getDecrypt($passLogin, $passLoginIV, $pass);
}
}

View File

@@ -25,6 +25,8 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
use phpseclib\Exception\FileNotFoundException;
/**

View File

@@ -27,9 +27,13 @@ namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class CsvImport para importar cuentas desde archivos CSV
*
* @package SP
*/
class CsvImport extends CsvImportBase
{
/**
* Iniciar la importación desde XML.
*

View File

@@ -25,6 +25,13 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class CustomFieldDef para la gestión de definiciones de campos personalizados
*
* @package SP
*/
class CustomFieldDef extends CustomFieldsBase
{
/**

View File

@@ -25,7 +25,13 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class CustomFields para la gestión de campos personalizados de los módulos
*
* @package SP
*/
class CustomFields extends CustomFieldsBase
{
/**

View File

@@ -25,8 +25,15 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
use SP\Controller\ActionsInterface;
/**
* Class CustomFieldsBase para la definición de campos personalizados
*
* @package SP
*/
abstract class CustomFieldsBase
{
/**

View File

@@ -130,11 +130,13 @@ class Email
$mail->isSMTP();
$mail->CharSet = 'utf-8';
$mail->SMTPAuth = $mailAuth;
$mail->Host = $mailServer;
$mail->Port = $mailPort;
$mail->Username = $mailUser;
$mail->Password = $mailPass;
if ($mailAuth) {
$mail->SMTPAuth = $mailAuth;
$mail->Username = $mailUser;
$mail->Password = $mailPass;
}
$mail->SMTPSecure = strtolower(Config::getValue('mail_security'));
//$mail->SMTPDebug = 2;
//$mail->Debugoutput = 'error_log';

View File

@@ -27,6 +27,11 @@ namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class ImportBase abstracta para manejo de archivos de importación
*
* @package SP
*/
abstract class ImportBase
{
/**

View File

@@ -482,7 +482,7 @@ class Init
$update = false;
$configVersion = (int)str_replace('.', '', Config::getValue('version'));
$databaseVersion = (int)str_replace('.', '', Config::getConfigDbValue('version'));
$databaseVersion = (int)str_replace('.', '', ConfigDB::getValue('version'));
$appVersion = (int)implode(Util::getVersion(true));
if ($databaseVersion < $appVersion
@@ -503,9 +503,9 @@ class Init
if ($action === 'upgrade' && $hash === Config::getValue('upgrade_key', 0)) {
if (Upgrade::doUpgrade($databaseVersion)) {
Config::setConfigDbValue('version', $appVersion);
ConfigDB::setValue('version', $appVersion);
Config::setValue('maintenance', false);
Config::deleteKey('upgrade_key');
Config::deleteParam('upgrade_key');
$update = true;
}
} else {
@@ -544,17 +544,6 @@ class Init
{
$sessionLifeTime = self::getSessionLifeTime();
// Regenerar el Id de sesión periódicamente para evitar fijación
if (Session::getSidStartTime() === 0) {
Session::setSidStartTime(time());
Session::setStartActivity(time());
} else if (Session::getUserId() && time() - Session::getSidStartTime() > $sessionLifeTime / 2) {
session_regenerate_id(true);
Session::setSidStartTime(time());
// Recargar los permisos del perfil de usuario
Session::setUserProfile(Profile::getProfile(Session::getUserProfileId()));
}
// Timeout de sesión
if (Session::getLastActivity() && (time() - Session::getLastActivity() > $sessionLifeTime)) {
if (isset($_COOKIE[session_name()])) {
@@ -566,6 +555,21 @@ class Init
session_unset();
session_destroy();
session_start();
return;
}
// Regenerar el Id de sesión periódicamente para evitar fijación
if (Session::getSidStartTime() === 0) {
Session::setSidStartTime(time());
Session::setStartActivity(time());
} else if (Session::getUserId() && time() - Session::getSidStartTime() > $sessionLifeTime / 2) {
$sessionMPass = SessionUtil::getSessionMPass();
session_regenerate_id(true);
Session::setSidStartTime(time());
// Recargar los permisos del perfil de usuario
Session::setUserProfile(Profile::getProfile(Session::getUserProfileId()));
// Regenerar la clave maestra
SessionUtil::saveSessionMPass($sessionMPass);
}
Session::setLastActivity(time());

View File

@@ -199,7 +199,7 @@ class Installer
return $error;
}
Config::setConfigDbValue('version', implode(Util::getVersion(true)));
ConfigDB::setValue('version', implode(Util::getVersion(true)));
Config::setValue('installed', 1);
}
@@ -484,9 +484,9 @@ class Installer
}
// Guardar el hash de la clave maestra
Config::setArrConfigValue('masterPwd', Crypt::mkHashPassword(self::$_masterPassword));
Config::setArrConfigValue('lastupdatempass', time());
Config::writeConfigDb(true);
ConfigDB::setCacheConfigValue('masterPwd', Crypt::mkHashPassword(self::$_masterPassword));
ConfigDB::setCacheConfigValue('lastupdatempass', time());
ConfigDB::writeConfig(true);
if (!$User->updateUserMPass(self::$_masterPassword)) {
self::rollback();
@@ -508,8 +508,8 @@ class Installer
self::$_dbc->query("DROP USER '" . self::$_dbuser . "'@'" . self::$_dbhost . "';");
self::$_dbc->query("DROP USER '" . self::$_dbuser . "'@'%';");
} catch (\PDOException $e) {
Config::deleteKey('dbuser');
Config::deleteKey('dbpass');
Config::deleteParam('dbuser');
Config::deleteParam('dbpass');
}
}

View File

@@ -28,7 +28,7 @@ namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class Language para el manejo del languaje utilizado por la aplicación
* Class Language para el manejo del lenguaje utilizado por la aplicación
*
* @package SP
*/

View File

@@ -32,7 +32,6 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
*/
class Migrate
{
// private static $dbuser;
private static $_dbc; // Database connection
private static $_customersByName;
private static $_currentQuery;

View File

@@ -29,6 +29,11 @@ use CssMin;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class Minify para la gestión de archivos JS y CSS
*
* @package SP
*/
class Minify
{
/**

View File

@@ -30,7 +30,7 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
/**
* Esta clase es encargada de ejecutar acciones comunes para las funciones
*/
class Common
class Response
{
/**
* Devuelve una respuesta en formato XML con el estado y el mensaje.
@@ -95,35 +95,4 @@ class Common
header('Content-type: application/json');
exit(json_encode($json));
}
/**
* Devuelve un hash para verificación de formularios.
* Esta función genera un hash que permite verificar la autenticidad de un formulario
*
* @param bool $new si es necesrio regenerar el hash
* @return string con el hash de verificación
*/
public static function getSessionKey($new = false)
{
$hash = sha1(time());
// Generamos un nuevo hash si es necesario y lo guardamos en la sesión
if (is_null(Session::getSecurityKey()) || $new === true) {
Session::setSecurityKey($hash);
return $hash;
}
return Session::getSecurityKey();
}
/**
* Comprobar el hash de verificación de formularios.
*
* @param string $key con el hash a comprobar
* @return bool|string si no es correcto el hash devuelve bool. Si lo es, devuelve el hash actual.
*/
public static function checkSessionKey($key)
{
return (!is_null(Session::getSecurityKey()) && Session::getSecurityKey() == $key);
}
}

View File

@@ -25,6 +25,8 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Extender la clase Exception para mostrar ayuda en los mensajes
*/

View File

@@ -657,4 +657,24 @@ class Session
{
self::setSessionKey('tempmasterpass', $password);
}
/**
* Devolver el color asociado a una cuenta
*
* @return string
*/
public static function getAccountColor()
{
return self::getSessionKey('accountcolor');
}
/**
* Establece l color asociado a una cuenta
*
* @param array $color
*/
public static function setAccountColor(array $color)
{
self::setSessionKey('accountcolor', $color);
}
}

View File

@@ -25,7 +25,13 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class SessionUtil para las utilidades de la sesión
*
* @package SP
*/
class SessionUtil
{
/**
@@ -57,4 +63,60 @@ class SessionUtil
$CryptPKI = new CryptPKI();
Session::setPublicKey($CryptPKI->getPublicKey());
}
/**
* Guardar la clave maestra encriptada en la sesión
*/
public static function saveSessionMPass($masterPass)
{
$mPassPwd = Crypt::generateAesKey(session_id());
$sessionMasterPass = Crypt::mkCustomMPassEncrypt($mPassPwd, $masterPass);
Session::setMPass($sessionMasterPass[0]);
Session::setMPassIV($sessionMasterPass[1]);
return true;
}
/**
* Desencriptar la clave maestra de la sesión.
*
* @return string con la clave maestra
*/
public static function getSessionMPass()
{
$cryptPass = Crypt::generateAesKey(session_id());
return Crypt::getDecrypt(Session::getMPass(), Session::getMPassIV(), $cryptPass);
}
/**
* Devuelve un hash para verificación de formularios.
* Esta función genera un hash que permite verificar la autenticidad de un formulario
*
* @param bool $new si es necesrio regenerar el hash
* @return string con el hash de verificación
*/
public static function getSessionKey($new = false)
{
$hash = sha1(time());
// Generamos un nuevo hash si es necesario y lo guardamos en la sesión
if (is_null(Session::getSecurityKey()) || $new === true) {
Session::setSecurityKey($hash);
return $hash;
}
return Session::getSecurityKey();
}
/**
* Comprobar el hash de verificación de formularios.
*
* @param string $key con el hash a comprobar
* @return bool|string si no es correcto el hash devuelve bool. Si lo es, devuelve el hash actual.
*/
public static function checkSessionKey($key)
{
return (!is_null(Session::getSecurityKey()) && Session::getSecurityKey() == $key);
}
}

View File

@@ -24,6 +24,8 @@
*/
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
use InvalidArgumentException;
/**

View File

@@ -214,7 +214,7 @@ class Upgrade
foreach ($mapParams as $newParam => $oldParam) {
if (array_key_exists($oldParam, $currData)) {
Config::setValue($newParam, $currData[$oldParam]);
Config::deleteKey($oldParam);
Config::deleteParam($oldParam);
}
}
@@ -232,10 +232,10 @@ class Upgrade
private static function auxUpgrades($version){
switch ($version){
case 12001:
return (Profile::migrateProfiles() && UserUtil::migrateUsersGroup());
return (Profile::migrateProfiles() && UserMigrate::migrateUsersGroup());
break;
case 12002:
return (UserUtil::setMigrateUsers());
return (UserMigrate::setMigrateUsers());
break;
default:
break;

View File

@@ -42,14 +42,14 @@ class User extends UserBase
*/
public function updateUserMPass($masterPwd)
{
$configMPass = Config::getConfigDbValue('masterPwd');
$configMPass = ConfigDB::getValue('masterPwd');
if (!$configMPass) {
return false;
}
if (Crypt::checkHashPass($masterPwd, $configMPass, true)) {
$strUserMPwd = Crypt::mkCustomMPassEncrypt(self::getCypherPass($this->_userPass), $masterPwd);
$strUserMPwd = Crypt::mkCustomMPassEncrypt(self::getCypherPass(), $masterPwd);
if (!$strUserMPwd) {
return false;
@@ -106,18 +106,7 @@ class User extends UserBase
return false;
}
if ($showPass == true) {
return $clearMasterPass;
} else {
$mPassPwd = Util::generate_random_bytes(32);
Session::setMPassPwd($mPassPwd);
$sessionMasterPass = Crypt::mkCustomMPassEncrypt($mPassPwd, $clearMasterPass);
Session::setMPass($sessionMasterPass[0]);
Session::setMPassIV($sessionMasterPass[1]);
return true;
}
return ($showPass == true) ? $clearMasterPass : SessionUtil::saveSessionMPass($clearMasterPass);
}
return false;

172
inc/UserAccounts.class.php Normal file
View File

@@ -0,0 +1,172 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class UserAccounts para la gestión de usuarios en las cuentas
*
* @package SP
*/
class UserAccounts
{
/**
* Actualizar la asociación de grupos con cuentas.
*
* @param int $accountId con el Id de la cuenta
* @param array $usersId con los usuarios de la cuenta
* @return bool
*/
public static function updateUsersForAccount($accountId, $usersId)
{
if (self::deleteUsersForAccount($accountId, $usersId)) {
return self::addUsersForAccount($accountId, $usersId);
}
return false;
}
/**
* Eliminar la asociación de grupos con cuentas.
*
* @param int $accountId con el Id de la cuenta
* @param array $usersId opcional con los grupos de la cuenta
* @return bool
*/
public static function deleteUsersForAccount($accountId, $usersId = null)
{
$queryExcluded = '';
// Excluimos los usuarios actuales
if (is_array($usersId)) {
array_map('intval', $usersId);
$queryExcluded = 'AND accuser_userId NOT IN (' . implode(',', $usersId) . ')';
}
$query = 'DELETE FROM accUsers WHERE accuser_accountId = :id ' . $queryExcluded;
$data['id'] = $accountId;
return DB::getQuery($query, __FUNCTION__, $data);
}
/**
* Crear asociación de grupos con cuentas.
*
* @param int $accountId con el Id de la cuenta
* @param array $usersId con los grupos de la cuenta
* @return bool
*/
public static function addUsersForAccount($accountId, $usersId)
{
if (!is_array($usersId)) {
return true;
}
$values = '';
// Obtenemos los grupos actuales
$usersExcluded = self::getUsersForAccount($accountId);
foreach ($usersId as $userId) {
// Excluimos los usuarios actuales
if (isset($usersExcluded) && is_array($usersExcluded) && in_array($userId, $usersExcluded)) {
continue;
}
$values[] = '(' . (int)$accountId . ',' . (int)$userId . ')';
}
if (!is_array($values)) {
return true;
}
$query = 'INSERT INTO accUsers (accuser_accountId, accuser_userId) VALUES ' . implode(',', $values);
return DB::getQuery($query, __FUNCTION__);
}
/**
* Obtiene el listado de usuarios de una cuenta.
*
* @param int $accountId con el id de la cuenta
* @return array con los id de usuarios de la cuenta
*/
public static function getUsersForAccount($accountId)
{
$query = 'SELECT accuser_userId FROM accUsers WHERE accuser_accountId = :id';
$data['id'] = $accountId;
DB::setReturnArray();
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return array();
}
foreach ($queryRes as $user) {
$users[] = (int)$user->accuser_userId;
}
return $users;
}
/**
* Obtiene el listado con el nombre de los usuarios de una cuenta.
*
* @param int $accountId con el id de la cuenta
* @return false|array con los nombres de los usuarios ordenados
*/
public static function getUsersNameForAccount($accountId)
{
$query = 'SELECT user_id,'
. 'user_login '
. 'FROM accUsers '
. 'JOIN usrData ON user_Id = accuser_userId '
. 'WHERE accuser_accountId = :id';
$data['id'] = $accountId;
DB::setReturnArray();
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
foreach ($queryRes as $users) {
$usersName[$users->user_id] = $users->user_login;
}
asort($usersName, SORT_STRING);
return $usersName;
}
}

View File

@@ -25,6 +25,8 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class UserBase
*
@@ -340,7 +342,7 @@ abstract class UserBase
*/
public function addUser()
{
$passdata = UserUtil::makeUserPassHash($this->_userPass);
$passdata = UserPass::makeUserPassHash($this->_userPass);
$query = 'INSERT INTO usrData SET '
. 'user_name = :name,'
@@ -545,7 +547,7 @@ abstract class UserBase
*/
public function updateUserPass()
{
$passdata = UserUtil::makeUserPassHash($this->_userPass);
$passdata = UserPass::makeUserPassHash($this->_userPass);
$userLogin = UserUtil::getUserLoginById($this->_userId);
$query = 'UPDATE usrData SET '

View File

@@ -44,7 +44,7 @@ class UserLdap
*/
public static function newUserLDAP(User $User)
{
$passdata = UserUtil::makeUserPassHash($User->getUserPass());
$passdata = UserPass::makeUserPassHash($User->getUserPass());
$groupId = Config::getValue('ldap_defaultgroup', 0);
$profileId = Config::getValue('ldap_defaultprofile', 0);
@@ -95,7 +95,7 @@ class UserLdap
*/
public static function updateLDAPUserInDB(User $User)
{
$passdata = UserUtil::makeUserPassHash($User->getUserPass());
$passdata = UserPass::makeUserPassHash($User->getUserPass());
$query = 'UPDATE usrData SET '
. 'user_pass = :pass,'

129
inc/UserMigrate.class.php Normal file
View File

@@ -0,0 +1,129 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class UserMigrate para la migración de usuarios
*
* @package SP
*/
class UserMigrate
{
/**
* Comprobar si un usuario está migrado desde phpPMS.
*
* @param string $userLogin con el login del usuario
* @return bool
*/
public static function checkUserIsMigrate($userLogin)
{
$query = 'SELECT BIN(user_isMigrate) AS user_isMigrate FROM usrData WHERE user_login = :login LIMIT 1';
$data['login'] = $userLogin;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
return ($queryRes !== false && $queryRes->user_isMigrate == 1);
}
/**
* Actualizar la clave de un usuario desde phpPMS.
*
* @param string $userLogin con el login del usuario
* @param string $userPass con la clave del usuario
* @return bool
*
* Esta función actualiza la clave de un usuario que ha sido migrado desde phpPMS
*/
public static function migrateUser($userLogin, $userPass)
{
$passdata = UserPass::makeUserPassHash($userPass);
$query = 'UPDATE usrData SET '
. 'user_pass = :pass,'
. 'user_hashSalt = :salt,'
. 'user_lastUpdate = NOW(),'
. 'user_isMigrate = 0 '
. 'WHERE user_login = :login '
. 'AND user_isMigrate = 1 '
. 'AND (user_pass = SHA1(CONCAT(user_hashSalt,:passOld)) '
. 'OR user_pass = MD5(:passOldMd5)) LIMIT 1';
$data['pass'] = $passdata['pass'];
$data['salt'] = $passdata['salt'];
$data['login'] = $userLogin;
$data['passOld'] = $userPass;
$data['passOldMd5'] = $userPass;
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
}
$log = new Log(__FUNCTION__);
$log->addDescription(_('Usuario actualizado'));
$log->addDescription('Login: ' . $userLogin);
$log->writeLog();
Email::sendEmail($log);
return true;
}
/**
* Migrar el grupo de los usuarios a la nueva tabla
*/
public static function migrateUsersGroup()
{
$query = 'SELECT user_id, user_groupId FROM usrData';
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
foreach ($queryRes as $user) {
if (!Groups::addUsersForGroup(array($user->user_groupId), $user->user_id)) {
Log::writeNewLog(_('Migrar Grupos'), sprintf('%s (%s)'), _('Error al migrar grupo del usuario'), $user->user_id);
}
}
return true;
}
/**
* Establecer el campo isMigrate de cada usuario
*/
public static function setMigrateUsers()
{
$query = 'UPDATE usrData SET user_isMigrate = 1';
return DB::getQuery($query, __FUNCTION__);
}
}

166
inc/UserPass.class.php Normal file
View File

@@ -0,0 +1,166 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class UserPass para la gestión de las claves de un usuario
*
* @package SP
*/
class UserPass
{
/**
* @var int El último id de una consulta de actualización
*/
public static $queryLastId = 0;
/**
* Comprueba la clave maestra del usuario.
*
* @param User $User
* @return bool
*/
public static function checkUserMPass(User $User)
{
$userMPass = $User->getUserMPass(true);
if ($userMPass === false) {
return false;
}
$configHashMPass = ConfigDB::getValue('masterPwd');
if ($configHashMPass === false) {
return false;
}
// Comprobamos el hash de la clave del usuario con la guardada
return Crypt::checkHashPass($userMPass, $configHashMPass, true);
}
/**
* Comprobar si el usuario tiene actualizada la clave maestra actual.
*
* @param string $login opcional con el login del usuario
* @return bool
*/
public static function checkUserUpdateMPass($login = null)
{
$userId = (!is_null($login)) ? UserUtil::getUserIdByLogin($login) : Session::getUserId();
if ($userId === 0) {
return false;
}
$configMPassTime = ConfigDB::getValue('lastupdatempass');
if ($configMPassTime === false) {
return false;
}
$query = 'SELECT user_lastUpdateMPass FROM usrData WHERE user_id = :id LIMIT 1';
$data['id'] = $userId;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
$ret = ($queryRes !== false && $queryRes->user_lastUpdateMPass > $configMPassTime);
return $ret;
}
/**
* Modificar la clave de un usuario.
*
* @param $userId
* @param $userPass
* @return bool
*/
public static function updateUserPass($userId, $userPass)
{
$passdata = self::makeUserPassHash($userPass);
$userLogin = UserUtil::getUserLoginById($userId);
$query = 'UPDATE usrData SET '
. 'user_pass = :pass,'
. 'user_hashSalt = :salt,'
. 'user_isChangePass = 0,'
. 'user_lastUpdate = NOW() '
. 'WHERE user_id = :id LIMIT 1';
$data['pass'] = $passdata['pass'];
$data['salt'] = $passdata['salt'];
$data['id'] = $userId;
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
}
self::$queryLastId = DB::$lastId;
Log::writeNewLogAndEmail(_('Modificar Clave Usuario'), sprintf('%s : %s', Html::strongText(_('Login')), $userLogin));
return true;
}
/**
* Crear la clave de un usuario.
*
* @param string $userPass con la clave del usuario
* @return array con la clave y salt del usuario
*/
public static function makeUserPassHash($userPass)
{
$salt = Crypt::makeHashSalt();
$userPass = crypt($userPass, $salt);
return array('salt' => $salt, 'pass' => $userPass);
}
/**
* Obtener el IV del usuario a partir del Id.
*
* @param int $id El id del usuario
* @return string El hash
*/
public static function getUserIVById($id)
{
$query = 'SELECT user_mIV FROM usrData WHERE user_id = :id LIMIT 1';
$data['id'] = $id;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
return $queryRes->user_mIV;
}
}

View File

@@ -0,0 +1,130 @@
<?php
/**
* sysPass
*
* @author nuxsmin
* @link http://syspass.org
* @copyright 2012-2015 Rubén Domínguez nuxsmin@syspass.org
*
* This file is part of sysPass.
*
* sysPass is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* sysPass is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with sysPass. If not, see <http://www.gnu.org/licenses/>.
*
*/
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class UserPassRecover para la gestión de recuperaciones de claves de usuarios
*
* @package SP
*/
class UserPassRecover
{
/**
* Tiempo máximo para recuperar la clave
*/
const MAX_PASS_RECOVER_TIME = 3600;
/**
* Número de intentos máximos para recuperar la clave
*/
const MAX_PASS_RECOVER_LIMIT = 3;
const USER_LOGIN_EXIST = 1;
const USER_MAIL_EXIST = 2;
/**
* Comprobar el hash de recuperación de clave.
*
* @param string $hash con el hash de recuperación
* @return int con el Id del usuario
*/
public static function checkHashPassRecover($hash)
{
$query = 'SELECT userpassr_userId FROM usrPassRecover '
. 'WHERE userpassr_hash = :hash '
. 'AND userpassr_used = 0 '
. 'AND userpassr_date >= :date '
. 'ORDER BY userpassr_date DESC LIMIT 1';
$data['hash'] = $hash;
$data['date'] = time() - self::MAX_PASS_RECOVER_TIME;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
return $queryRes->userpassr_userId;
}
/**
* Marcar como usado el hash de recuperación de clave.
*
* @param string $hash con el hash de recuperación
* @return bool
*/
public static function updateHashPassRecover($hash)
{
$query = 'UPDATE usrPassRecover SET userpassr_used = 1 WHERE userpassr_hash = :hash';
$data['hash'] = $hash;
return DB::getQuery($query, __FUNCTION__, $data);
}
/**
* Comprobar el límite de recuperaciones de clave.
*
* @param string $login con el login del usuario
* @return bool
*/
public static function checkPassRecoverLimit($login)
{
$query = 'SELECT userpassr_userId ' .
'FROM usrPassRecover ' .
'WHERE userpassr_userId = :id ' .
'AND userpassr_used = 0 ' .
'AND userpassr_date >= :date';
$data['id'] = UserUtil::getUserIdByLogin($login);
$data['date'] = time() - self::MAX_PASS_RECOVER_TIME;
return (DB::getQuery($query, __FUNCTION__, $data) === false || DB::$lastNumRows >= self::MAX_PASS_RECOVER_LIMIT);
}
/**
* Insertar un registro de recuperación de clave.
*
* @param string $login con el login del usuario
* @param string $hash con el hash para el cambio
* @return bool
*/
public static function addPassRecover($login, $hash)
{
$query = 'INSERT INTO usrPassRecover SET '
. 'userpassr_userId = :userId,'
. 'userpassr_hash = :hash,'
. 'userpassr_date = UNIX_TIMESTAMP(),'
. 'userpassr_used = 0';
$data['userId'] = UserUtil::getUserIdByLogin($login);
$data['hash'] = $hash;
return DB::getQuery($query, __FUNCTION__, $data);
}
}

View File

@@ -34,126 +34,8 @@ defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'
*/
class UserUtil
{
/**
* Tiempo máximo para recuperar la clave
*/
const MAX_PASS_RECOVER_TIME = 3600;
/**
* Número de intentos máximos para recuperar la clave
*/
const MAX_PASS_RECOVER_LIMIT = 3;
const USER_LOGIN_EXIST = 1;
const USER_MAIL_EXIST = 2;
/**
* @var int El último id de una consulta de actualización
*/
public static $queryLastId = 0;
/**
* Comprobar si un usuario está migrado desde phpPMS.
*
* @param string $userLogin con el login del usuario
* @return bool
*/
public static function checkUserIsMigrate($userLogin)
{
$query = 'SELECT BIN(user_isMigrate) AS user_isMigrate FROM usrData WHERE user_login = :login LIMIT 1';
$data['login'] = $userLogin;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
return ($queryRes !== false && $queryRes->user_isMigrate == 1);
}
/**
* Actualizar la clave de un usuario desde phpPMS.
*
* @param string $userLogin con el login del usuario
* @param string $userPass con la clave del usuario
* @return bool
*
* Esta función actualiza la clave de un usuario que ha sido migrado desde phpPMS
*/
public static function migrateUser($userLogin, $userPass)
{
$passdata = UserUtil::makeUserPassHash($userPass);
$query = 'UPDATE usrData SET '
. 'user_pass = :pass,'
. 'user_hashSalt = :salt,'
. 'user_lastUpdate = NOW(),'
. 'user_isMigrate = 0 '
. 'WHERE user_login = :login '
. 'AND user_isMigrate = 1 '
. 'AND (user_pass = SHA1(CONCAT(user_hashSalt,:passOld)) '
. 'OR user_pass = MD5(:passOldMd5)) LIMIT 1';
$data['pass'] = $passdata['pass'];
$data['salt'] = $passdata['salt'];
$data['login'] = $userLogin;
$data['passOld'] = $userPass;
$data['passOldMd5'] = $userPass;
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
}
$log = new Log(__FUNCTION__);
$log->addDescription(_('Usuario actualizado'));
$log->addDescription('Login: ' . $userLogin);
$log->writeLog();
Email::sendEmail($log);
return true;
}
/**
* Crear la clave de un usuario.
*
* @param string $userPass con la clave del usuario
* @return array con la clave y salt del usuario
*/
public static function makeUserPassHash($userPass)
{
$salt = Crypt::makeHashSalt();
$userPass = crypt($userPass, $salt);
return array('salt' => $salt, 'pass' => $userPass);
}
/**
* Comprobar si el usuario tiene actualizada la clave maestra actual.
*
* @param string $login opcional con el login del usuario
* @return bool
*/
public static function checkUserUpdateMPass($login = null)
{
$userId = (!is_null($login)) ? self::getUserIdByLogin($login) : Session::getUserId();
if ($userId === 0) {
return false;
}
$configMPassTime = Config::getConfigDbValue('lastupdatempass');
if ($configMPassTime === false) {
return false;
}
$query = 'SELECT user_lastUpdateMPass FROM usrData WHERE user_id = :id LIMIT 1';
$data['id'] = $userId;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
$ret = ($queryRes !== false && $queryRes->user_lastUpdateMPass > $configMPassTime);
return $ret;
}
/**
* Obtener el Id de usuario a partir del login.
@@ -176,108 +58,6 @@ class UserUtil
return (int)$queryRes->user_id;
}
/**
* Actualizar la asociación de grupos con cuentas.
*
* @param int $accountId con el Id de la cuenta
* @param array $usersId con los usuarios de la cuenta
* @return bool
*/
public static function updateUsersForAccount($accountId, $usersId)
{
if (self::deleteUsersForAccount($accountId, $usersId)) {
return self::addUsersForAccount($accountId, $usersId);
}
return false;
}
/**
* Eliminar la asociación de grupos con cuentas.
*
* @param int $accountId con el Id de la cuenta
* @param array $usersId opcional con los grupos de la cuenta
* @return bool
*/
public static function deleteUsersForAccount($accountId, $usersId = null)
{
$queryExcluded = '';
// Excluimos los usuarios actuales
if (is_array($usersId)) {
array_map('intval', $usersId);
$queryExcluded = 'AND accuser_userId NOT IN (' . implode(',', $usersId) . ')';
}
$query = 'DELETE FROM accUsers WHERE accuser_accountId = :id ' . $queryExcluded;
$data['id'] = $accountId;
return DB::getQuery($query, __FUNCTION__, $data);
}
/**
* Crear asociación de grupos con cuentas.
*
* @param int $accountId con el Id de la cuenta
* @param array $usersId con los grupos de la cuenta
* @return bool
*/
public static function addUsersForAccount($accountId, $usersId)
{
if (!is_array($usersId)) {
return true;
}
$values = '';
// Obtenemos los grupos actuales
$usersExcluded = self::getUsersForAccount($accountId);
foreach ($usersId as $userId) {
// Excluimos los usuarios actuales
if (isset($usersExcluded) && is_array($usersExcluded) && in_array($userId, $usersExcluded)) {
continue;
}
$values[] = '(' . (int)$accountId . ',' . (int)$userId . ')';
}
if (!is_array($values)) {
return true;
}
$query = 'INSERT INTO accUsers (accuser_accountId, accuser_userId) VALUES ' . implode(',', $values);
return DB::getQuery($query, __FUNCTION__);
}
/**
* Obtiene el listado de usuarios de una cuenta.
*
* @param int $accountId con el id de la cuenta
* @return array con los id de usuarios de la cuenta
*/
public static function getUsersForAccount($accountId)
{
$query = 'SELECT accuser_userId FROM accUsers WHERE accuser_accountId = :id';
$data['id'] = $accountId;
DB::setReturnArray();
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return array();
}
foreach ($queryRes as $user) {
$users[] = (int)$user->accuser_userId;
}
return $users;
}
/**
* Comprobar si un usuario está deshabilitado.
@@ -298,100 +78,6 @@ class UserUtil
return $ret;
}
/**
* Comprobar el hash de recuperación de clave.
*
* @param string $hash con el hash de recuperación
* @return int con el Id del usuario
*/
public static function checkHashPassRecover($hash)
{
$query = 'SELECT userpassr_userId FROM usrPassRecover '
. 'WHERE userpassr_hash = :hash '
. 'AND userpassr_used = 0 '
. 'AND userpassr_date >= :date '
. 'ORDER BY userpassr_date DESC LIMIT 1';
$data['hash'] = $hash;
$data['date'] = time() - self::MAX_PASS_RECOVER_TIME;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
return $queryRes->userpassr_userId;
}
/**
* Marcar como usado el hash de recuperación de clave.
*
* @param string $hash con el hash de recuperación
* @return bool
*/
public static function updateHashPassRecover($hash)
{
$query = 'UPDATE usrPassRecover SET userpassr_used = 1 WHERE userpassr_hash = :hash';
$data['hash'] = $hash;
return DB::getQuery($query, __FUNCTION__, $data);
}
/**
* Comprobar el límite de recuperaciones de clave.
*
* @param string $login con el login del usuario
* @return bool
*/
public static function checkPassRecoverLimit($login)
{
$query = 'SELECT userpassr_userId ' .
'FROM usrPassRecover ' .
'WHERE userpassr_userId = :id ' .
'AND userpassr_used = 0 ' .
'AND userpassr_date >= :date';
$data['id'] = self::getUserIdByLogin($login);
$data['date'] = time() - self::MAX_PASS_RECOVER_TIME;
return (DB::getQuery($query, __FUNCTION__, $data) === false || DB::$lastNumRows >= self::MAX_PASS_RECOVER_LIMIT);
}
/**
* Obtiene el listado con el nombre de los usuarios de una cuenta.
*
* @param int $accountId con el id de la cuenta
* @return false|array con los nombres de los usuarios ordenados
*/
public static function getUsersNameForAccount($accountId)
{
$query = 'SELECT user_id,'
. 'user_login '
. 'FROM accUsers '
. 'JOIN usrData ON user_Id = accuser_userId '
. 'WHERE accuser_accountId = :id';
$data['id'] = $accountId;
DB::setReturnArray();
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
foreach ($queryRes as $users) {
$usersName[$users->user_id] = $users->user_login;
}
asort($usersName, SORT_STRING);
return $usersName;
}
/**
* Comprobar si un usuario y email existen.
*
@@ -430,49 +116,6 @@ class UserUtil
return $queryRes->user_email;
}
/**
* Insertar un registro de recuperación de clave.
*
* @param string $login con el login del usuario
* @param string $hash con el hash para el cambio
* @return bool
*/
public static function addPassRecover($login, $hash)
{
$query = 'INSERT INTO usrPassRecover SET '
. 'userpassr_userId = :userId,'
. 'userpassr_hash = :hash,'
. 'userpassr_date = UNIX_TIMESTAMP(),'
. 'userpassr_used = 0';
$data['userId'] = self::getUserIdByLogin($login);
$data['hash'] = $hash;
return DB::getQuery($query, __FUNCTION__, $data);
}
/**
* Obtener el IV del usuario a partir del Id.
*
* @param int $id El id del usuario
* @return string El hash
*/
public static function getUserIVById($id)
{
$query = 'SELECT user_mIV FROM usrData WHERE user_id = :id LIMIT 1';
$data['id'] = $id;
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
return $queryRes->user_mIV;
}
/**
* Actualiza el último inicio de sesión del usuario en la BBDD.
*
@@ -488,29 +131,6 @@ class UserUtil
return DB::getQuery($query, __FUNCTION__, $data);
}
/**
* Comprueba la clave maestra del usuario.
*
* @param User $User
* @return bool
*/
public static function checkUserMPass(User $User)
{
$userMPass = $User->getUserMPass(true);
if ($userMPass === false) {
return false;
}
$configHashMPass = Config::getConfigDbValue('masterPwd');
if ($configHashMPass === false) {
return false;
}
// Comprobamos el hash de la clave del usuario con la guardada
return Crypt::checkHashPass($userMPass, $configHashMPass, true);
}
/**
* Obtener los datos de un usuario.
@@ -627,39 +247,6 @@ class UserUtil
return DB::getResults($query, __FUNCTION__, $data);
}
/**
* Modificar la clave de un usuario.
*
* @param $userId
* @param $userPass
* @return bool
*/
public static function updateUserPass($userId, $userPass)
{
$passdata = UserUtil::makeUserPassHash($userPass);
$userLogin = UserUtil::getUserLoginById($userId);
$query = 'UPDATE usrData SET '
. 'user_pass = :pass,'
. 'user_hashSalt = :salt,'
. 'user_isChangePass = 0,'
. 'user_lastUpdate = NOW() '
. 'WHERE user_id = :id LIMIT 1';
$data['pass'] = $passdata['pass'];
$data['salt'] = $passdata['salt'];
$data['id'] = $userId;
if (DB::getQuery($query, __FUNCTION__, $data) === false) {
return false;
}
self::$queryLastId = DB::$lastId;
Log::writeNewLogAndEmail(_('Modificar Clave Usuario'), sprintf('%s : %s', Html::strongText(_('Login')), $userLogin));
return true;
}
/**
* Obtener el login de usuario a partir del Id.
@@ -681,36 +268,4 @@ class UserUtil
return $queryRes->user_login;
}
/**
* Migrar el grupo de los usuarios a la nueva tabla
*/
public static function migrateUsersGroup()
{
$query = 'SELECT user_id, user_groupId FROM usrData';
$queryRes = DB::getResults($query, __FUNCTION__, $data);
if ($queryRes === false) {
return false;
}
foreach ($queryRes as $user) {
if (!Groups::addUsersForGroup(array($user->user_groupId), $user->user_id)) {
Log::writeNewLog(_('Migrar Grupos'), sprintf('%s (%s)'), _('Error al migrar grupo del usuario'), $user->user_id);
}
}
return true;
}
/**
* Establecer el campo isMigrate de cada usuario
*/
public static function setMigrateUsers()
{
$query = 'UPDATE usrData SET user_isMigrate = 1';
return DB::getQuery($query, __FUNCTION__);
}
}

View File

@@ -25,9 +25,6 @@
namespace SP;
use CssMin;
use phpseclib\Crypt\RSA;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
@@ -199,7 +196,7 @@ class Util
*/
public static function getVersionString()
{
return '1.2-rc4';
return '1.2-rc5';
}
/**
@@ -312,7 +309,7 @@ class Util
*/
public static function getVersion($retBuild = false)
{
$build = '04';
$build = '05';
$version = array(1, 2, 0);
if ($retBuild) {
@@ -548,7 +545,7 @@ class Util
}
/**
* Obtener datos desde una URL
* Obtener datos desde una URL usando CURL
*
* @param $url string La URL
* @return bool|string

View File

@@ -25,6 +25,8 @@
namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Clase XmlExport para realizar la exportación de las cuentas de sysPass a formato XML
*

View File

@@ -27,6 +27,11 @@ namespace SP;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
* Class XmlImportBase abstracta para manejar archivos de importación en formato XML
*
* @package SP
*/
abstract class XmlImportBase extends ImportBase
{
/**

File diff suppressed because it is too large Load Diff

View File

@@ -199,7 +199,7 @@
<form method="post" enctypr="multipart/form-data" name="upload_form" id="fileUpload">
<input type="file" id="inFile" name="inFile"/>
</form>
<div id="dropzone" class="round"
<div id="dropzone" class="round active-tooltip"
data-files-ext="<?php echo $filesAllowedExts; ?>"
title="<?php echo _('Soltar archivos aquí (max. 5) o click para seleccionar') . '<br><br>' . _('Tamaño máximo de archivo') . ' ' . $maxFileSize . ' MB'; ?>">
<img src="imgs/upload.png" alt="upload" class="opacity50"/>

View File

@@ -1,19 +1,16 @@
<div ID='debuginfo' class='round'>
<h3>DEBUG INFO</h3>
<ul>
<li>RENDER -> <?php use SP\Config;
use SP\Crypt;
echo $time; ?> sec</li>
<li>RENDER -> <?php echo $time; ?> sec</li>
<li>MEM -> Init: <?php echo $memInit; ?> KB - End: <?php echo $memEnd; ?> KB -
Total: <?php echo $memEnd - $memInit; ?> KB
</li>
<li>SESSION:
<pre><?php echo print_r($_SESSION, true) ?></pre>
</li>
<li>MASTER PASS: <?php echo Crypt::getSessionMasterPass(); ?></li>
<li>MASTER PASS: <?php echo \SP\SessionUtil::getSessionMPass(); ?></li>
<li>CONFIG FILE:
<pre><?php echo print_r(Config::getKeys(true), true); ?></pre>
<pre><?php echo print_r(SP\Config::getKeys(true), true); ?></pre>
</li>
</div>

View File

@@ -1,8 +1,5 @@
<!-- Start Tab - Encryption -->
<div id="tabs-<?php use SP\Acl;
use SP\Common;
echo $encryption_tabIndex; ?>">
<div id="tabs-<?php echo $encryption_tabIndex; ?>">
<div id="title" class="midroundup titleNormal">
<?php echo _('Clave Maestra'); ?>

View File

@@ -1,7 +1,5 @@
<div id="title" class="midroundup titleNormal">
<?php use SP\Common;
echo _('Registro de Eventos'); ?>
<?php echo _('Registro de Eventos'); ?>
</div>
<?php if (!$events): ?>

View File

@@ -1,8 +1,5 @@
<!-- Start Tab - Import -->
<div id="tabs-<?php use SP\Acl;
use SP\Common;
echo $import_tabIndex; ?>">
<div id="tabs-<?php echo $import_tabIndex; ?>">
<div id="title" class="midroundup titleNormal">
<?php echo _('Importar phpPMS'); ?>
</div>

View File

@@ -241,7 +241,7 @@
<form method="post" enctype="multipart/form-data" name="upload_form" id="fileUpload">
<input type="file" id="inFile" name="inFile"/>
</form>
<div id="dropzone" class="round"
<div id="dropzone" class="round active-tooltip"
data-files-ext="<?php echo $filesAllowedExts; ?>"
title="<?php echo _('Soltar archivos aquí (max. 5) o click para seleccionar') . '<br><br>' . _('Tamaño máximo de archivo') . ' ' . $maxFileSize . ' MB'; ?>">
<i class="material-icons md-60 fg-green80">cloud_upload</i>

View File

@@ -1,19 +1,16 @@
<div ID='debuginfo' class='round'>
<h3>DEBUG INFO</h3>
<ul>
<li>RENDER -> <?php use SP\Config;
use SP\Crypt;
echo $time; ?> sec</li>
<li>RENDER -> <?php echo $time; ?> sec</li>
<li>MEM -> Init: <?php echo $memInit; ?> KB - End: <?php echo $memEnd; ?> KB -
Total: <?php echo $memEnd - $memInit; ?> KB
</li>
<li>SESSION:
<pre><?php echo print_r($_SESSION, true) ?></pre>
</li>
<li>MASTER PASS: <?php echo Crypt::getSessionMasterPass(); ?></li>
<li>MASTER PASS: <?php echo SP\SessionUtil::getSessionMPass(); ?></li>
<li>CONFIG FILE:
<pre><?php echo print_r(Config::getKeys(true), true); ?></pre>
<pre><?php echo print_r(SP\Config::getKeys(true), true); ?></pre>
</li>
</div>

View File

@@ -1,8 +1,5 @@
<!-- Start Tab - Encryption -->
<div id="tabs-<?php use SP\Acl;
use SP\Common;
echo $encryption_tabIndex; ?>">
<div id="tabs-<?php echo $encryption_tabIndex; ?>">
<div id="title" class="midroundup titleNormal">
<?php echo _('Clave Maestra'); ?>

View File

@@ -1,6 +1,5 @@
<div id="title" class="midroundup titleNormal">
<?php use SP\Common;
echo _('Registro de Eventos'); ?>
<?php echo _('Registro de Eventos'); ?>
</div>
<?php if (!$events): ?>

View File

@@ -1,8 +1,5 @@
<!-- Start Tab - Import -->
<div id="tabs-<?php
use SP\Common;
echo $import_tabIndex; ?>">
<div id="tabs-<?php echo $import_tabIndex; ?>">
<div id="title" class="midroundup titleNormal">
<?php echo _('Importar CSV/XML'); ?>
</div>
@@ -223,7 +220,7 @@ echo $import_tabIndex; ?>">
<script>
$(function () {
// Preparar la zona de importación
sysPassUtil.Common.importFile('<?php echo Common::getSessionKey(true); ?>');
sysPassUtil.Common.importFile('<?php echo SP\SessionUtil::getSessionKey(true); ?>');
$("#help_import_button").click(function () {
$("#help_import").dialog("open");

View File

@@ -83,7 +83,6 @@
<label class="mdl-switch mdl-js-switch mdl-js-ripple-effect" for="sort_views">
<input type="checkbox" id="sort_views" class="mdl-switch__input fg-blue100"
name="sort_views" <?php echo ($chkSortViews) ? 'checked' : ''; ?>/>
<span class="mdl-switch__label"><?php echo _('Activar'); ?></span>
</label>
</td>
</tr>

View File

@@ -43,7 +43,7 @@
<td class="descField"><?php echo _('Perfil'); ?></td>
<td class="valField">
<select id="selProfile" name="profileid"
class="select-box sel-chosen-profile" required>
class="select-box sel-chosen-profile" required <?php echo $isDisabled; ?>>
<option value="0"></option>
<?php foreach ($profiles as $id => $name): ?>
<option
@@ -57,7 +57,7 @@
<td class="descField"><?php echo _('Grupo'); ?></td>
<td class="valField">
<select id="selGroup" name="groupid"
class="select-box sel-chosen-usergroup" required>
class="select-box sel-chosen-usergroup" required <?php echo $isDisabled; ?>>
<option value="0"></option>
<?php foreach ($groups as $id => $name): ?>
<option

View File

@@ -25,7 +25,7 @@
define('APP_ROOT', '.');
require_once APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
require APP_ROOT . DIRECTORY_SEPARATOR . 'inc' . DIRECTORY_SEPARATOR . 'Base.php';
if (!\SP\Init::checkPostLoginActions()) {
$controller = new SP\Controller\MainC(null, 'main');

View File

@@ -28,11 +28,14 @@ namespace SP\Controller;
use SP\Account;
use SP\AccountHistory;
use SP\Acl;
use SP\Common;
use SP\Response;
use SP\CustomFields;
use SP\Groups;
use SP\Session;
use SP\SessionUtil;
use SP\SPException;
use SP\UserAccounts;
use SP\UserPass;
use SP\UserUtil;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
@@ -78,7 +81,7 @@ class AccountC extends Controller implements ActionsInterface
$this->view->assign('chkUserEdit', '');
$this->view->assign('chkGroupEdit', '');
$this->view->assign('gotData', $this->isGotData());
$this->view->assign('sk', Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
}
/**
@@ -166,7 +169,7 @@ class AccountC extends Controller implements ActionsInterface
if (!Acl::checkUserAccess($this->getAction())) {
$this->showError(self::ERR_PAGE_NO_PERMISSION);
return false;
} elseif (!UserUtil::checkUserUpdateMPass()) {
} elseif (!UserPass::checkUserUpdateMPass()) {
$this->showError(self::ERR_UPDATE_MPASS);
return false;
} elseif ($this->_id > 0 && !Acl::checkAccountAccess($this->_action, $this->_account->getAccountDataForACL())) {
@@ -186,7 +189,7 @@ class AccountC extends Controller implements ActionsInterface
// $this->view->assign('accountParentId', $this->getAccount()->getAccountParentId());
$this->view->assign('accountIsHistory', $this->getAccount()->getAccountIsHistory());
$this->view->assign('accountOtherUsers', $this->getAccount()->getAccountUsersId());
$this->view->assign('accountOtherUsersName', UserUtil::getUsersNameForAccount($this->getId()));
$this->view->assign('accountOtherUsersName', UserAccounts::getUsersNameForAccount($this->getId()));
$this->view->assign('accountOtherGroups', $this->getAccount()->getAccountUserGroupsId());
$this->view->assign('accountOtherGroupsName', \SP\Groups::getGroupsNameForAccount($this->getId()));
$this->view->assign('changesHash', $this->getAccount()->calcChangesHash());
@@ -299,7 +302,7 @@ class AccountC extends Controller implements ActionsInterface
*/
private function setAccountDetails()
{
$this->_account->setAccountUsersId(UserUtil::getUsersForAccount($this->getId()));
$this->_account->setAccountUsersId(UserAccounts::getUsersForAccount($this->getId()));
$this->_account->setAccountUserGroupsId(Groups::getGroupsForAccount($this->getId()));
}

View File

@@ -28,6 +28,7 @@ namespace SP\Controller;
use SP\ApiTokens;
use SP\CustomFieldDef;
use SP\CustomFields;
use SP\SessionUtil;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
@@ -57,7 +58,7 @@ class AccountsMgmtC extends Controller implements ActionsInterface
parent::__construct($template);
$this->view->assign('isDemo', \SP\Util::demoIsEnabled());
$this->view->assign('sk', \SP\Common::getSessionKey());
$this->view->assign('sk', SessionUtil::getSessionKey());
}
/**
@@ -71,7 +72,7 @@ class AccountsMgmtC extends Controller implements ActionsInterface
return;
}
$this->view->assign('sk', \SP\Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$categoriesTableProp = array(
'tblId' => 'tblCategories',
@@ -130,7 +131,7 @@ class AccountsMgmtC extends Controller implements ActionsInterface
return;
}
$this->view->assign('sk', \SP\Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$customersTableProp = array(
'tblId' => 'tblCustomers',
@@ -244,7 +245,7 @@ class AccountsMgmtC extends Controller implements ActionsInterface
$this->view->addTemplate('files');
$this->view->assign('sk', \SP\Common::getSessionKey());
$this->view->assign('sk', SessionUtil::getSessionKey());
}
/**
@@ -258,7 +259,7 @@ class AccountsMgmtC extends Controller implements ActionsInterface
return;
}
$this->view->assign('sk', \SP\Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$tableProp = array(
'tblId' => 'tblCustomFields',

View File

@@ -26,8 +26,10 @@
namespace SP\Controller;
use SP\Config;
use SP\ConfigDB;
use SP\Language;
use SP\Session;
use SP\SessionUtil;
use SP\Themes;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
@@ -51,7 +53,7 @@ class ConfigC extends Controller implements ActionsInterface
parent::__construct($template);
$this->view->assign('tabs', array());
$this->view->assign('sk', \SP\Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$this->view->assign('isDemoMode', (\SP\Util::demoIsEnabled() && !Session::getUserIsAdminApp()));
$this->view->assign('isDisabled', (\SP\Util::demoIsEnabled() && !Session::getUserIsAdminApp()) ? 'DISABLED' : '');
}
@@ -122,9 +124,9 @@ class ConfigC extends Controller implements ActionsInterface
$this->view->addTemplate('encryption');
$this->view->assign('lastUpdateMPass', \SP\Config::getConfigDbValue("lastupdatempass"));
$this->view->assign('tempMasterPassTime', \SP\Config::getConfigDbValue("tempmaster_passtime"));
$this->view->assign('tempMasterMaxTime', \SP\Config::getConfigDbValue("tempmaster_maxtime"));
$this->view->assign('lastUpdateMPass', ConfigDB::getValue("lastupdatempass"));
$this->view->assign('tempMasterPassTime', ConfigDB::getValue("tempmaster_passtime"));
$this->view->assign('tempMasterMaxTime', ConfigDB::getValue("tempmaster_maxtime"));
$this->view->assign('tempMasterPass', Session::getTemporaryMasterPass());
$this->view->append('tabs', array('title' => _('Encriptación')));

View File

@@ -25,6 +25,8 @@
namespace SP\Controller;
use SP\SessionUtil;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
/**
@@ -48,7 +50,7 @@ class EventlogC extends Controller implements ActionsInterface
{
parent::__construct($template);
$this->view->assign('sk', \SP\Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
}
/**
@@ -88,11 +90,11 @@ class EventlogC extends Controller implements ActionsInterface
*/
public function checkClear()
{
if ($this->view->clear && $this->view->sk && \SP\Common::checkSessionKey($this->view->sk)) {
if ($this->view->clear && $this->view->sk && SessionUtil::checkSessionKey($this->view->sk)) {
if (\SP\Log::clearEvents()) {
\SP\Common::printJSON(_('Registro de eventos vaciado'), 0, "sysPassUtil.Common.doAction(" . ActionsInterface::ACTION_EVL . "); sysPassUtil.Common.scrollUp();");
\SP\Response::printJSON(_('Registro de eventos vaciado'), 0, "sysPassUtil.Common.doAction(" . ActionsInterface::ACTION_EVL . "); sysPassUtil.Common.scrollUp();");
} else {
\SP\Common::printJSON(_('Error al vaciar el registro de eventos'));
\SP\Response::printJSON(_('Error al vaciar el registro de eventos'));
}
}
}

View File

@@ -59,7 +59,7 @@ class MainC extends Controller implements ActionsInterface
$this->view->addTemplate('header');
$this->view->addTemplate('body-start');
$this->view->assign('sk', \SP\Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$this->view->assign('appInfo', Util::getAppInfo());
$this->view->assign('appVersion', Util::getVersionString());
$this->view->assign('isDemoMode', Util::demoIsEnabled());
@@ -186,13 +186,13 @@ class MainC extends Controller implements ActionsInterface
'checkaccess' => 1),
array(
'name' => self::ACTION_USR,
'title' => _('Gestión de Usuarios'),
'title' => _('Usuarios y Accesos'),
'img' => 'users.png',
'icon' => 'account_box',
'checkaccess' => 1),
array(
'name' => self::ACTION_MGM,
'title' => _('Gestión de Clientes y Categorías'),
'title' => _('Elementos y Personalización'),
'img' => 'appmgmt.png',
'icon' => 'group_work',
'checkaccess' => 1),

View File

@@ -26,6 +26,8 @@
namespace SP\Controller;
use SP\Session;
use SP\SessionUtil;
use SP\UserAccounts;
use SP\UserUtil;
defined('APP_ROOT') || die(_('No es posible acceder directamente a este archivo'));
@@ -43,6 +45,30 @@ class SearchC extends Controller implements ActionsInterface
* @var bool
*/
private $_filterOn = false;
/**
* Colores para resaltar las cuentas
*
* @var array
*/
private $_colors = array(
'2196F3',
'03A9F4',
'00BCD4',
'009688',
'4CAF50',
'8BC34A',
'CDDC39',
'FFC107',
'795548',
'607D8B',
'9E9E9E',
'FF5722',
'F44336',
'E91E63',
'9C27B0',
'673AB7',
'3F51B5',
);
/**
* Constructor
@@ -53,7 +79,7 @@ class SearchC extends Controller implements ActionsInterface
{
parent::__construct($template);
$this->view->assign('sk', \SP\Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$this->setVars();
}
@@ -170,26 +196,6 @@ class SearchC extends Controller implements ActionsInterface
$this->view->assign('wikiPageUrl', \SP\Config::getValue('wiki_pageurl'));
}
$colors = array(
'2196F3',
'03A9F4',
'00BCD4',
'009688',
'4CAF50',
'8BC34A',
'CDDC39',
'FFC107',
'795548',
'607D8B',
'9E9E9E',
'FF5722',
'F44336',
'E91E63',
'9C27B0',
'673AB7',
'3F51B5',
);
$this->setSortFields();
$objAccount = new \SP\Account();
@@ -213,19 +219,10 @@ class SearchC extends Controller implements ActionsInterface
$show = ($accView || $accViewPass || $accEdit || $accCopy || $accDel);
// Se asigna el color de forma aleatoria a cada cliente
$color = array_rand($colors);
if (!isset($customerColor) || !array_key_exists($account->account_customerId, $customerColor)) {
$customerColor[$account->account_customerId] = '#' . $colors[$color];
}
$hexColor = $customerColor[$account->account_customerId];
// Obtenemos datos si el usuario tiene acceso a los datos de la cuenta
if ($show) {
$secondaryGroups = \SP\Groups::getGroupsNameForAccount($account->account_id);
$secondaryUsers = UserUtil::getUsersNameForAccount($account->account_id);
$secondaryUsers = UserAccounts::getUsersNameForAccount($account->account_id);
$secondaryAccesses = '<em>(G) ' . $account->usergroup_name . '*</em><br>';
@@ -257,7 +254,7 @@ class SearchC extends Controller implements ActionsInterface
'category_name' => $account->category_name,
'customer_name' => \SP\Html::truncate($account->customer_name, $maxTextLength),
'customer_link' => ($wikiEnabled) ? $wikiSearchUrl . $account->customer_name : '',
'color' => $hexColor,
'color' => $this->pickAccountColor($account->account_customerId),
'url' => $account->account_url,
'url_short' => \SP\Html::truncate($account->account_url, $maxTextLength),
'url_islink' => (preg_match("#^https?://.*#i", $account->account_url)) ? true : false,
@@ -312,4 +309,28 @@ class SearchC extends Controller implements ActionsInterface
)
));
}
/**
* Seleccionar un color para la cuenta
*
* @param int $id El id del elemento a asignar
* @return mixed
*/
private function pickAccountColor($id)
{
$accountColor = Session::getAccountColor();
if (!isset($accountColor)
|| !is_array($accountColor)
|| !isset($accountColor[$id])
) {
// Se asigna el color de forma aleatoria a cada id
$color = array_rand($this->_colors);
$accountColor[$id] = '#' . $this->_colors[$color];
Session::setAccountColor($accountColor);
}
return $accountColor[$id];
}
}

View File

@@ -25,13 +25,14 @@
namespace SP\Controller;
use SP\Common;
use SP\Response;
use SP\CustomFields;
use SP\DB;
use SP\Groups;
use SP\Log;
use SP\Profile;
use SP\Session;
use SP\SessionUtil;
use SP\Template;
use SP\UserUtil;
use SP\Util;
@@ -64,7 +65,7 @@ class UsersMgmtC extends Controller implements ActionsInterface
parent::__construct($template);
$this->view->assign('isDemo', Util::demoIsEnabled());
$this->view->assign('sk', Common::getSessionKey());
$this->view->assign('sk', SessionUtil::getSessionKey());
}
/**
@@ -74,7 +75,7 @@ class UsersMgmtC extends Controller implements ActionsInterface
{
$this->setAction(self::ACTION_USR_USERS);
$this->view->assign('sk', Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
if (!$this->checkAccess()) {
return;
@@ -175,7 +176,7 @@ class UsersMgmtC extends Controller implements ActionsInterface
{
$this->setAction(self::ACTION_USR_GROUPS);
$this->view->assign('sk', Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
if (!$this->checkAccess()) {
return;
@@ -233,7 +234,7 @@ class UsersMgmtC extends Controller implements ActionsInterface
{
$this->setAction(self::ACTION_USR_PROFILES);
$this->view->assign('sk', Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
if (!$this->checkAccess()) {
return;
@@ -372,7 +373,7 @@ class UsersMgmtC extends Controller implements ActionsInterface
$this->view->assign('actionId', self::ACTION_USR_USERS_EDITPASS);
// Obtener de nuevo el token de seguridad por si se habñia regenerado antes
$this->view->assign('sk', Common::getSessionKey());
$this->view->assign('sk', SessionUtil::getSessionKey());
}
/**

View File

@@ -28,6 +28,7 @@ namespace SP\Controller;
use SP\Auth\Auth2FA;
use SP\Language;
use SP\Session;
use SP\SessionUtil;
use SP\Themes;
use SP\UserPreferences;
@@ -65,7 +66,7 @@ class UsersPrefsC extends Controller implements ActionsInterface
$this->view->assign('tabs', array());
$this->view->assign('sk', \SP\Common::getSessionKey(true));
$this->view->assign('sk', SessionUtil::getSessionKey(true));
$this->_userId = Session::getUserId();
$this->_userPrefs = UserPreferences::getPreferences($this->_userId);
}