I recently worked on a system for the company I work for and would love some feedback on the following class for managing sessions. I don't claim to be a PHP guru but I like to think I gave it a try!
<?php
/*
* CLASS: Session
*
* @author Nathan Fitzgerald
*/
class Session {
var $user;
private $auth_key = SECURE_AUTH_KEY;
const COOKIE_DOMAIN = '.mydomain.com';
/*
* INIT
*/
public function __construct() {
if(!session_id()) session_start();
$this->checkRememberCookie();
}
/*
* Set Session Notice
* @param $message (string)
* @param $context (string)
*/
public function setSessionNotice($message, $context) {
$_SESSION['bcqa_session_message'] = $message;
$_SESSION['bcqa_session_message_context'] = $context;
}
/*
* Get Session Notice
* @return html
*/
public function getSessionNotice() {
global $core;
if( !isset($_SESSION['bcqa_session_message_context']) || !isset($_SESSION['bcqa_session_message']) ) return;
switch($_SESSION['bcqa_session_message_context']):
case 'success':
$icon = 'fa fa-check-circle';
break;
case 'danger':
$icon = 'fa-exclamation-circle';
break;
case 'info':
$icon = 'fa-info-circle';
break;
case 'warning':
$icon = 'fa-exclamation-triangle';
break;
endswitch;
?>
<div class="container<?php if($core->isAdmin()): ?>-fluid<?php endif; ?>">
<div class="alert alert-dismissible alert-<?php echo $_SESSION['bcqa_session_message_context']; ?>" role="alert">
<button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<i class="fa <?php echo $icon; ?>"></i> <?php echo $_SESSION['bcqa_session_message']; ?>
</div>
</div>
<?php
$this->destroySessionNotice();
}
/*
* Destroy Session Notice
*/
public function destroySessionNotice() {
unset($_SESSION['bcqa_session_message']);
unset($_SESSION['bcqa_session_message_context']);
}
/*
* Check if User has Checked Remember Me and Login Automatically
*/
public function checkRememberCookie() {
global $mysql, $core;
if( !$this->isUserLoggedIn() ):
if( isset($_COOKIE['bc_qandq_auth']) && $_COOKIE['bc_qandq_auth'] == md5($this->auth_key) && isset($_COOKIE['bc_qanda_user_id'])) {
$user_q = $mysql->query('
SELECT * FROM bc_users
WHERE user_id = "'.$_COOKIE['bc_qanda_user_id'].'"
');
if(!$user_q->is_empty()) {
$user = $user_q->fetchObject();
$this->authenticate($user->username, $user->password);
} else {
$this->logout();
}
}
endif;
}
/*
* Login
*/
public function authenticate($username, $password, $redirect = false, $remember = false) {
global $mysql, $core;
if( !BraveHelpers::isValidMD5($password) ) {
$password = md5($password);
}
$user_q = $mysql->query('
SELECT * FROM bc_users
WHERE username = "'.$username.'"
AND password = "'.$password.'"
');
if(!$user_q->is_empty()) {
$this->user = $user_q->fetchObject();
unset($this->user->password);
unset($this->user->key);
// Do actual login...
$_SESSION['bc_qandq_auth'] = md5($this->auth_key);
$_SESSION['user_id'] = $this->user->user_id;
$_SESSION['user_info'] = (array) $this->user;
if($remember) {
// Set Cookies (7 days)
setcookie('bc_qandq_auth', md5($this->auth_key), time()+3600*168, '/', self::COOKIE_DOMAIN);
setcookie('bc_qanda_user_id', $this->user->user_id, time()+3600*168, '/', self::COOKIE_DOMAIN);
}
// Update Last Login & Login Count
$mysql->update('bc_users',
array(
'date_lastlogin' => BraveHelpers::date('Y-m-d H:i:s'),
'login_count' => $this->user->login_count+1
),
array(
'user_id' => $this->user->user_id
)
);
$this->setSessionNotice('You have been logged in successfully.', 'success');
} else {
$this->setSessionNotice('<strong>ERROR:</strong> Invalid username or password combination.', 'danger');
}
$return_url = $core->getSystemBaseUrl();
if( $redirect ) {
$return_url = $redirect;
}
if( $this->user->role == 'admin' && !$redirect) {
$return_url = $core->getAdminUrl();
}
$this->_redirect($return_url);
}
/*
* Logout
*/
public function logout() {
// Destroy Session Variables
unset($_SESSION['bc_qandq_auth']);
unset($_SESSION['user_id']);
unset($_SESSION['user_info']);
// Destroy Cookies
if( isset($_COOKIE['bc_qandq_auth']) && isset($_COOKIE['bc_qanda_user_id'])) {
setcookie('bc_qandq_auth', 0, time()-3600*24, '/', self::COOKIE_DOMAIN);
setcookie('bc_qanda_user_id', 0, time()-3600*24, '/', self::COOKIE_DOMAIN);
}
}
/*
* Is the user logged in?
*/
public function isUserLoggedIn() {
if( isset($_SESSION['bc_qandq_auth']) && $_SESSION['bc_qandq_auth'] == md5($this->auth_key) && isset($_SESSION['user_id']) ) {
return true;
}
return false;
}
public function doAuthChecks() {
global $core;
if( !$this->isUserLoggedIn() ) {
$this->setSessionNotice('You need to be logged in to view that page.', 'warning');
$this->_redirect($core->getSystemBaseUrl().'?redirect_to='.$core->getCurrentUrl());
}
}
/*
* Redirect
*/
public function _redirect($url) {
header('Location: '.$url);
exit;
}
public function getLogoutUrl() {
global $core;
return $core->getSystemBaseUrl('logout');
}
public function getUserInfo($key) {
return $_SESSION['user_info'][$key];
}
public function checkPermissions() {
global $core;
if( $this->getUserInfo('role') == 'admin' ) {
return true;
}
$core->_dead('You do not have permission to view that page.', 'error');
}
}
?>