Skip to content

Commit

Permalink
unacms#4293 Session authentication
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Trofimov committed Mar 31, 2023
1 parent 575f17f commit 151b2d6
Show file tree
Hide file tree
Showing 12 changed files with 104 additions and 46 deletions.
2 changes: 1 addition & 1 deletion inc/classes/BxDolCmts.php
Original file line number Diff line number Diff line change
Expand Up @@ -1776,7 +1776,7 @@ protected function _getAuthorId ()

protected function _getAuthorPassword ()
{
return isMember() ? $_COOKIE['memberPassword'] : "";
return getLoggedPassword();
}

protected function _getAuthorIp ()
Expand Down
2 changes: 1 addition & 1 deletion inc/classes/BxDolDb.php
Original file line number Diff line number Diff line change
Expand Up @@ -689,7 +689,7 @@ public function error($aError)
bx_log('sys_db', "$sErrorType\n" .
(empty($aError['message']) ? '' : " Error: {$aError['message']}\n") .
(empty($aError['query']) ? '' : " Query: {$aError['query']}\n") .
(empty($_COOKIE['memberID']) ? '' : " Account ID: {$_COOKIE['memberID']}\n")
(getLoggedId() ? '' : " Account ID: " . getLoggedId() . "\n")
);

bx_show_service_unavailable_error_and_exit($sOutput);
Expand Down
2 changes: 1 addition & 1 deletion inc/classes/BxDolObject.php
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,7 @@ protected function _getAuthorId ()

protected function _getAuthorPassword ()
{
return isMember() ? $_COOKIE['memberPassword'] : "";
return getLoggedPassword();
}

protected function _getAuthorIp ()
Expand Down
6 changes: 3 additions & 3 deletions inc/classes/BxDolPush.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,9 @@ public static function getNotificationsCount($iProfileId = 0, &$aBubbles = null)
{
$iMemberIdCookie = null;
$bLoggedMemberGlobals = null;
if ($iProfileId && $iProfileId != bx_get_logged_profile_id()) {
if (!empty($_COOKIE['memberID']))
$iMemberIdCookie = $_COOKIE['memberID'];
if ($iProfileId && $iProfileId != bx_get_logged_profile_id()) {
if (getLoggedId())
$iMemberIdCookie = getLoggedId();
if (!empty($GLOBALS['logged']['member']))
$bLoggedMemberGlobals = $GLOBALS['logged']['member'];
$oProfile = BxDolProfile::getInstance($iProfileId);
Expand Down
20 changes: 15 additions & 5 deletions inc/classes/BxDolSession.php
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,15 @@ function start()
if (defined('BX_DOL_CRON_EXECUTE') || defined('BX_MANIFEST'))
return true;

if ($this->exists($this->sId)) {
if ($this->iUserId == getLoggedId())
return true;
$this->destroy(false);
if (getParam('sys_session_auth')) {
$this->exists($this->sId);
}
else {
if ($this->exists($this->sId)) {
if ($this->iUserId == getLoggedId())
return true;
$this->destroy(false);
}
}

/**
Expand All @@ -81,7 +86,7 @@ function start()
bx_logout();

// try to restore user's old session
if (isLogged() && defined('BX_DOL_SESSION_RESTORATION') && constant('BX_DOL_SESSION_RESTORATION')) {
if (!getParam('sys_session_auth') && isLogged() && defined('BX_DOL_SESSION_RESTORATION') && constant('BX_DOL_SESSION_RESTORATION')) {
$this->sId = $this->oDb->getOldSession(getLoggedId());
if ($this->sId)
$this->exists($this->sId); // it exists for sure but required for initializing some data there
Expand Down Expand Up @@ -139,6 +144,11 @@ function setUserId($iUserId)
$this->save();
}

function getUserId()
{
return $this->iUserId;
}

function setValue($sKey, $mixedValue)
{
if(empty($this->sId))
Expand Down
6 changes: 3 additions & 3 deletions inc/classes/BxDolTemplate.php
Original file line number Diff line number Diff line change
Expand Up @@ -2921,7 +2921,7 @@ function _parseContent($sContent, $aVariables, $mixedKeyWrapperHtml = null)
catch(Exception $oException) {
bx_log('sys_template', "Error in _parseContent method. Cannot parse template insertion (<bx_include... />).\n" .
" Error ({$oException->getCode()}): {$oException->getMessage()}\n" .
(!empty($_COOKIE['memberID']) ? " Account ID: {$_COOKIE['memberID']}\n" : "")
(getLoggedId() ? " Account ID: " . getLoggedId() . "\n" : "")
);

return '';
Expand All @@ -2948,7 +2948,7 @@ function _parseContent($sContent, $aVariables, $mixedKeyWrapperHtml = null)
catch(Exception $oException) {
bx_log('sys_template', "Error in _parseContent method. Cannot parse System Keys.\n" .
" Error ({$oException->getCode()}): {$oException->getMessage()}\n" .
(!empty($_COOKIE['memberID']) ? " Account ID: {$_COOKIE['memberID']}\n" : "")
(getLoggedId() ? " Account ID: " . getLoggedId() . "\n" : "")
);

return '';
Expand Down Expand Up @@ -3054,7 +3054,7 @@ function _compileContent($sContent, $aVarName, $iVarDepth, $aVarValues, $mixedKe
if(($iCode = $oException->getCode()) != 1)
bx_log('sys_template', "Error in _compileContent method. Cannot parse template insertion (<bx_include... />).\n" .
" Error ({$iCode}): {$oException->getMessage()}\n" .
(!empty($_COOKIE['memberID']) ? " Account ID: {$_COOKIE['memberID']}\n" : "")
(getLoggedId() ? " Account ID: " . getLoggedId() . "\n" : "")
);

return false;
Expand Down
97 changes: 68 additions & 29 deletions inc/profiles.inc.php
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,21 @@ function isLogged()
*/
function getLoggedId()
{
return isset($_COOKIE['memberID']) && (!empty($GLOBALS['logged']['member']) || !empty($GLOBALS['logged']['admin'])) ? (int)$_COOKIE['memberID'] : 0;
if (getParam('sys_session_auth')) {
return (!empty($GLOBALS['logged']['member']) || !empty($GLOBALS['logged']['admin'])) ? BxDolSession::getInstance()->getUserId() : 0;
}
else {
return isset($_COOKIE['memberID']) && (!empty($GLOBALS['logged']['member']) || !empty($GLOBALS['logged']['admin'])) ? (int)$_COOKIE['memberID'] : 0;
}
}

/**
* @return logged in account password
*/
function getLoggedPassword()
{
return isset($_COOKIE['memberPassword']) && ($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) ? $_COOKIE['memberPassword'] : '';
$oAccount = BxDolAccount::getInstance();
return ($GLOBALS['logged']['member'] || $GLOBALS['logged']['admin']) && $oAccount ? BxDolAccountQuery::getInstance()->getPassword($oAccount->id()) : "";
}

/**
Expand Down Expand Up @@ -100,11 +106,13 @@ function bx_login($iId, $bRememberMe = false)
if (!$sPassword)
return false;

$iCookieTime = $bRememberMe ? time() + 60 * getParam('sys_session_lifetime_in_min') : 0;
bx_setcookie("memberID", $iId, $iCookieTime, 'auto');
$_COOKIE['memberID'] = $iId;
bx_setcookie("memberPassword", $sPassword, $iCookieTime, 'auto', '', 'auto', true /* http only */);
$_COOKIE['memberPassword'] = $sPassword;
if (!getParam('sys_session_auth')) {
$iCookieTime = $bRememberMe ? time() + 60 * getParam('sys_session_lifetime_in_min') : 0;
bx_setcookie("memberID", $iId, $iCookieTime, 'auto');
$_COOKIE['memberID'] = $iId;
bx_setcookie("memberPassword", $sPassword, $iCookieTime, 'auto', '', 'auto', true /* http only */);
$_COOKIE['memberPassword'] = $sPassword;
}

BxDolSession::getInstance()->setUserId($iId);

Expand All @@ -127,24 +135,26 @@ function bx_login($iId, $bRememberMe = false)
*/
function bx_logout($bNotify = true)
{
if (!isset($_COOKIE['memberID']))
if (!($iMemberId = BxDolSession::getInstance()->getUserId()))
return;

if ($bNotify && isMember())
bx_alert('account', 'logout', (int)$_COOKIE['memberID']);
bx_alert('account', 'logout', $iMemberId);

bx_audit(
$_COOKIE['memberID'],
$iMemberId,
'bx_accounts',
'_sys_audit_action_account_logout',
array('content_title' => '', 'data' => ['display_info' => ['User agent' => (isset($_SERVER["HTTP_USER_AGENT"]) ? $_SERVER["HTTP_USER_AGENT"] : '')]])
);

bx_setcookie('memberID', '', time() - 96 * 3600);
bx_setcookie('memberPassword', '', time() - 96 * 3600, 'auto', '', 'auto', true /* http only */);
if (!getParam('sys_session_auth')) {
bx_setcookie('memberID', '', time() - 96 * 3600);
bx_setcookie('memberPassword', '', time() - 96 * 3600, 'auto', '', 'auto', true);

unset($_COOKIE['memberID']);
unset($_COOKIE['memberPassword']);
unset($_COOKIE['memberID']);
unset($_COOKIE['memberPassword']);
}

BxDolSession::getInstance()->destroy();
}
Expand All @@ -159,27 +169,46 @@ function check_logged()
BX_DOL_ROLE_MEMBER => 'member'
);

$bID = isset($_COOKIE['memberID']);
$sID = $bID ? bx_process_input($_COOKIE['memberID']) : false;

$bPassword = isset($_COOKIE['memberPassword']);
$sPassword = $bPassword ? bx_process_input($_COOKIE['memberPassword']) : false;

$bLogged = false;
foreach ($aAccTypes as $iRole => $sValue) {
if ($GLOBALS['logged'][$sValue] = ($sID && !bx_check_login($sID, $sPassword, $iRole))) {
BxDolSession::getInstance();
$bLogged = true;
break;
$bID = false;
$sID = 0;

if (getParam('sys_session_auth')) {
$o = BxDolSession::getInstance();
$sID = $o->getUserId();
if ($sID && $oAccount = BxDolAccount::getInstance((int)$sID)) {
$aAccountInfo = $oAccount->getInfo();
foreach ($aAccTypes as $iRole => $sValue) {
if ($GLOBALS['logged'][$sValue] = ((int)$aAccountInfo['role'] & $iRole)) {
$bLogged = true;
$bID = true;
break;
}
}
}
}
else {
$bID = isset($_COOKIE['memberID']);
$sID = $bID ? bx_process_input($_COOKIE['memberID']) : false;

$bPassword = isset($_COOKIE['memberPassword']);
$sPassword = $bPassword ? bx_process_input($_COOKIE['memberPassword']) : false;

foreach ($aAccTypes as $iRole => $sValue) {
if ($GLOBALS['logged'][$sValue] = ($sID && !bx_check_login($sID, $sPassword, $iRole))) {
BxDolSession::getInstance();
$bLogged = true;
break;
}
}
}

if($bID && $bPassword && $bLogged) {
if($bID && $bLogged) {
header("Cache-Control: no-cache, no-store, must-revalidate");
bx_alert('account', 'logged', getLoggedId());
}

if(($bID || $bPassword) && !$bLogged)
if($bID && !$bLogged)
bx_logout(false);
}

Expand Down Expand Up @@ -286,8 +315,18 @@ function bx_require_authentication ($bStudio = false, $bAjaxMode = false, $sForc
if ($bStudio)
$iRole = BX_DOL_ROLE_ADMIN;

$sID = isset($_COOKIE['memberID']) ? bx_process_input($_COOKIE['memberID']) : false;
$sPassword = isset($_COOKIE['memberPassword']) ? bx_process_input($_COOKIE['memberPassword']) : false;
$sID = 0;
$sPassword = '';

if (getParam('sys_session_auth')) {
$o = BxDolSession::getInstance();
$sID = $o->getUserId();
$sPassword = $sID ? BxDolAccountQuery::getInstance()->getPassword($sID) : '';
}
else {
$sID = isset($_COOKIE['memberID']) ? bx_process_input($_COOKIE['memberID']) : false;
$sPassword = isset($_COOKIE['memberPassword']) ? bx_process_input($_COOKIE['memberPassword']) : false;
}

if (bx_check_login($sID, $sPassword, $iRole)) {
bx_login_form($bStudio, $bAjaxMode, $sForceRelocate);
Expand Down
1 change: 1 addition & 0 deletions install/sql/system.sql
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,7 @@ INSERT INTO `sys_options`(`category_id`, `name`, `caption`, `value`, `type`, `ex
(@iCategoryId, 'sys_transcoder_queue_storage', '_adm_stg_cpt_option_sys_transcoder_queue_storage', '', 'checkbox', '', '', '', '', 105),

(@iCategoryId, 'sys_session_lifetime_in_min', '_adm_stg_cpt_option_sys_session_lifetime_in_min', '129600', 'digit', '', '', '', '', 110),
(@iCategoryId, 'sys_session_auth', '_adm_stg_cpt_option_sys_session_auth', '', 'checkbox', '', '', '', '', 112),

(@iCategoryId, 'sys_account_activation_letter', '_adm_stg_cpt_option_sys_account_activation_letter', '', 'checkbox', '', '', '', '', 120),

Expand Down
10 changes: 8 additions & 2 deletions logout.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,14 @@

bx_import('BxDolLanguages');

if (isset($_COOKIE['memberID']) && isset($_COOKIE['memberPassword']))
bx_logout();
if (getParam('sys_session_auth')) {
if (isset($_COOKIE['memberSession']) && BxDolSession::getInstance()->getUserId())
bx_logout();
}
else {
if (isset($_COOKIE['memberID']) && isset($_COOKIE['memberPassword']))
bx_logout();
}

$oTemplate = BxDolTemplate::getInstance();
$oTemplate->setPageNameIndex (BX_PAGE_TRANSITION);
Expand Down
1 change: 1 addition & 0 deletions modules/boonex/english/data/langs/system/en.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1672,6 +1672,7 @@
<string name="_adm_stg_cpt_option_sys_template_cache_minify_js_enable"><![CDATA[Enable lessening for JS files (cache should be enabled)]]></string>
<string name="_adm_stg_cpt_option_sys_transcoder_queue_storage"><![CDATA[Remote video transcoding (requires special setup)]]></string>
<string name="_adm_stg_cpt_option_sys_session_lifetime_in_min"><![CDATA[Session lifetime (min)]]></string>
<string name="_adm_stg_cpt_option_sys_session_auth"><![CDATA[Session authentication]]></string>
<string name="_adm_stg_cpt_option_sys_default_curl_timeout"><![CDATA[cURL - default timeout]]></string>
<string name="_adm_stg_cpt_option_sys_ssl_allow_untrusted"><![CDATA[cURL - trust unsigned certificates or not verified hosts]]></string>
<string name="_adm_stg_cpt_option_sys_csp_frame_ancestors"><![CDATA['Content-Security-Policy: frame-ancestors' header value]]></string>
Expand Down
2 changes: 1 addition & 1 deletion modules/boonex/profiler/classes/BxProfiler.php
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ function _logBegin ($s)
{
$sDate = date ($this->_sLogDateFormat);
return "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\n" . $sDate . " " . $s . "\n" .
(isset($_COOKIE['memberID']) ? "User ID: " . $_COOKIE['memberID'] . "\n" : '') .
(getLoggedId() ? "User ID: " . getLoggedId() . "\n" : '') .
"User role: " . ($GLOBALS['logged']['admin'] ? 'admin' : ($GLOBALS['logged']['member'] ? 'member' : 'guest')) . "\n";
}

Expand Down
1 change: 1 addition & 0 deletions modules/boonex/russian/data/langs/system/ru.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1650,6 +1650,7 @@
<string name="_adm_stg_cpt_option_sys_template_cache_minify_js_enable"><![CDATA[Задействовать уменьшение для файлов JS (кэш должен быть задействован)]]></string>
<string name="_adm_stg_cpt_option_sys_transcoder_queue_storage"><![CDATA[Удалённая раскодировка видео (требуется дополнительная настройка)]]></string>
<string name="_adm_stg_cpt_option_sys_session_lifetime_in_min"><![CDATA[Время жизни сессии (в минутах)]]></string>
<string name="_adm_stg_cpt_option_sys_session_auth"><![CDATA[Аутентификация черех сессию]]></string>
<string name="_adm_stg_cpt_option_sys_default_curl_timeout"><![CDATA[cURL - Таймаут по умолчанию]]></string>
<string name="_adm_stg_cpt_option_sys_ssl_allow_untrusted"><![CDATA[cURL - доверять неподписанным сертификатам или неподтвержденным хостам]]></string>
<string name="_adm_stg_cpt_option_sys_csp_frame_ancestors"><![CDATA[Значение заголовка 'Content-Security-Policy: frame-ancestors']]></string>
Expand Down

0 comments on commit 151b2d6

Please sign in to comment.