Refactor PHP session handling during login/logout

Changed:
- move $_SESSION handling to SessionManager
- code cleanup

Signed-off-by: VirtualTam <virtualtam@flibidi.net>
This commit is contained in:
VirtualTam 2018-02-17 01:14:58 +01:00
parent db45a36a53
commit 49f1832316
2 changed files with 53 additions and 36 deletions

View file

@ -9,9 +9,15 @@ class SessionManager
/** Session expiration timeout, in seconds */ /** Session expiration timeout, in seconds */
public static $INACTIVITY_TIMEOUT = 3600; public static $INACTIVITY_TIMEOUT = 3600;
/** Name of the cookie set after logging in **/
public static $LOGGED_IN_COOKIE = 'shaarli_staySignedIn';
/** Local reference to the global $_SESSION array */ /** Local reference to the global $_SESSION array */
protected $session = []; protected $session = [];
/** ConfigManager instance **/
protected $conf = null;
/** /**
* Constructor * Constructor
* *
@ -84,4 +90,38 @@ public static function checkId($sessionId)
return true; return true;
} }
/**
* Store user login information after a successful login
*
* @param array $server The global $_SERVER array
*/
public function storeLoginInfo($server)
{
// Generate unique random number (different than phpsessionid)
$this->session['uid'] = sha1(uniqid('', true) . '_' . mt_rand());
$this->session['ip'] = client_ip_id($server);
$this->session['username'] = $this->conf->get('credentials.login');
$this->session['expires_on'] = time() + self::$INACTIVITY_TIMEOUT;
}
/**
* Logout a user by unsetting all login information
*
* See:
* - https://secure.php.net/manual/en/function.setcookie.php
*
* @param string $webPath path on the server in which the cookie will be available on
*/
public function logout($webPath)
{
if (isset($this->session)) {
unset($this->session['uid']);
unset($this->session['ip']);
unset($this->session['username']);
unset($this->session['visibility']);
unset($this->session['untaggedonly']);
}
setcookie(self::$LOGGED_IN_COOKIE, 'false', 0, $webPath);
}
} }

View file

@ -197,11 +197,11 @@ function setup_login_state($conf, $sessionManager)
$userIsLoggedIn = false; // Shaarli is not configured yet. $userIsLoggedIn = false; // Shaarli is not configured yet.
$loginFailure = true; $loginFailure = true;
} }
if (isset($_COOKIE['shaarli_staySignedIn']) && if (isset($_COOKIE[SessionManager::$LOGGED_IN_COOKIE])
$_COOKIE['shaarli_staySignedIn']===STAY_SIGNED_IN_TOKEN && && $_COOKIE[SessionManager::$LOGGED_IN_COOKIE] === STAY_SIGNED_IN_TOKEN
!$loginFailure) && !$loginFailure
{ ) {
fillSessionInfo($conf, $sessionManager); $sessionManager->storeLoginInfo($_SERVER);
$userIsLoggedIn = true; $userIsLoggedIn = true;
} }
// If session does not exist on server side, or IP address has changed, or session has expired, logout. // If session does not exist on server side, or IP address has changed, or session has expired, logout.
@ -209,7 +209,7 @@ function setup_login_state($conf, $sessionManager)
|| ($conf->get('security.session_protection_disabled') === false && $_SESSION['ip'] != client_ip_id($_SERVER)) || ($conf->get('security.session_protection_disabled') === false && $_SESSION['ip'] != client_ip_id($_SERVER))
|| time() >= $_SESSION['expires_on']) || time() >= $_SESSION['expires_on'])
{ {
logout(); $sessionManager->logout(WEB_PATH);
$userIsLoggedIn = false; $userIsLoggedIn = false;
$loginFailure = true; $loginFailure = true;
} }
@ -230,20 +230,6 @@ function setup_login_state($conf, $sessionManager)
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
// Session management // Session management
/**
* Load user session
*
* @param ConfigManager $conf Configuration Manager instance.
* @param SessionManager $sessionManager SessionManager instance
*/
function fillSessionInfo($conf, $sessionManager)
{
$_SESSION['uid'] = sha1(uniqid('',true).'_'.mt_rand()); // Generate unique random number (different than phpsessionid)
$_SESSION['ip'] = client_ip_id($_SERVER);
$_SESSION['username']= $conf->get('credentials.login');
$_SESSION['expires_on'] = time() + $sessionManager::$INACTIVITY_TIMEOUT;
}
/** /**
* Check that user/password is correct. * Check that user/password is correct.
* *
@ -259,7 +245,7 @@ function check_auth($login, $password, $conf, $sessionManager)
$hash = sha1($password . $login . $conf->get('credentials.salt')); $hash = sha1($password . $login . $conf->get('credentials.salt'));
if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash')) { if ($login == $conf->get('credentials.login') && $hash == $conf->get('credentials.hash')) {
// Login/password is correct. // Login/password is correct.
fillSessionInfo($conf, $sessionManager); $sessionManager->storeLoginInfo($_SERVER);
logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful'); logm($conf->get('resource.log'), $_SERVER['REMOTE_ADDR'], 'Login successful');
return true; return true;
} }
@ -274,18 +260,6 @@ function isLoggedIn()
return $userIsLoggedIn; return $userIsLoggedIn;
} }
// Force logout.
function logout() {
if (isset($_SESSION)) {
unset($_SESSION['uid']);
unset($_SESSION['ip']);
unset($_SESSION['username']);
unset($_SESSION['visibility']);
unset($_SESSION['untaggedonly']);
}
setcookie('shaarli_staySignedIn', FALSE, 0, WEB_PATH);
}
// ------------------------------------------------------------------------------------------ // ------------------------------------------------------------------------------------------
// Process login form: Check if login/password is correct. // Process login form: Check if login/password is correct.
if (isset($_POST['login'])) { if (isset($_POST['login'])) {
@ -303,10 +277,13 @@ function logout() {
if (!empty($_POST['longlastingsession'])) { if (!empty($_POST['longlastingsession'])) {
$_SESSION['longlastingsession'] = 31536000; // (31536000 seconds = 1 year) $_SESSION['longlastingsession'] = 31536000; // (31536000 seconds = 1 year)
$expiration = time() + $_SESSION['longlastingsession']; // calculate relative cookie expiration (1 year from now) $expiration = time() + $_SESSION['longlastingsession']; // calculate relative cookie expiration (1 year from now)
setcookie('shaarli_staySignedIn', STAY_SIGNED_IN_TOKEN, $expiration, WEB_PATH); setcookie($sessionManager::$LOGGED_IN_COOKIE, STAY_SIGNED_IN_TOKEN, $expiration, WEB_PATH);
$_SESSION['expires_on'] = $expiration; // Set session expiration on server-side. $_SESSION['expires_on'] = $expiration; // Set session expiration on server-side.
$cookiedir = ''; if(dirname($_SERVER['SCRIPT_NAME'])!='/') $cookiedir=dirname($_SERVER["SCRIPT_NAME"]).'/'; $cookiedir = '';
if (dirname($_SERVER['SCRIPT_NAME']) != '/') {
$cookiedir = dirname($_SERVER["SCRIPT_NAME"]) . '/';
}
session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side session_set_cookie_params($_SESSION['longlastingsession'],$cookiedir,$_SERVER['SERVER_NAME']); // Set session cookie expiration on client side
// Note: Never forget the trailing slash on the cookie path! // Note: Never forget the trailing slash on the cookie path!
session_regenerate_id(true); // Send cookie with new expiration date to browser. session_regenerate_id(true); // Send cookie with new expiration date to browser.
@ -676,7 +653,7 @@ function renderPage($conf, $pluginManager, $LINKSDB, $history, $sessionManager,
if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout')) if (isset($_SERVER['QUERY_STRING']) && startsWith($_SERVER['QUERY_STRING'], 'do=logout'))
{ {
invalidateCaches($conf->get('resource.page_cache')); invalidateCaches($conf->get('resource.page_cache'));
logout(); $sessionManager->logout(WEB_PATH);
header('Location: ?'); header('Location: ?');
exit; exit;
} }