Sugestão para melhoria de sistema de login

Enviada por Rogerio Pancini Pereira 
Rogerio Pancini Pereira
Sugestão para melhoria de sistema de login
12 de December de 2018 às 11:38AM
Bom dia pessoal.

Há algum tempo venho melhorando um sistema de login, que sempre uso.
Está bem próximo do que preciso.
O único porém, que não consigo melhorar é que, depois de um tempo, a sessão expira e o site desloga.
Já tentei mudar vários parâmetros, mas nada deu efeito.

Vou colocar aqui tudo o que tenho hoje e, se alguém puder dar uma sugestão, eu agradeço.

Login:
if (!function_exists("GetSQLValueString")){
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = ""){

/******* Conexão com o bando de dados *******/
include "Conexao/config.php";

mysqli_select_db($config, $database_config);
mysqli_set_charset($config,"utf8");
/******* Conexão com o bando de dados *******/

if (PHP_VERSION < 6) {
$theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
}

$theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($config, $theValue) : mysqli_escape_string($config, $theValue);

switch ($theType) {
case "text":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "long":
case "int":
$theValue = ($theValue != "") ? intval($theValue) : "NULL";
break;
case "double":
$theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
break;
case "date":
$theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
break;
case "defined":
$theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
break;
}
return $theValue;
}
}

// *** Validate request to login to this site.
if (!isset($_SESSION)) {
session_start();
}

$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
$_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['email'])) {
$loginUsername = strip_tags(trim($_POST['email']));
$password = sha1(strip_tags(trim($_POST['senha'])));

if($_POST['remember']) {
$year = time() + 31536000;
setcookie('remember_me', $loginUsername, $year);
}
elseif(!$_POST['remember']) {
if(isset($_COOKIE['remember_me'])) {
$past = time() - 100;
setcookie(remember_me, gone, $past);
}
}

$MM_fldUserAuthorization = "nivel";
$MM_redirectLoginSuccess = "".URL::getBase()."home";
$MM_redirectLoginFailed = "".URL::getBase()."login";
$MM_redirecttoReferrer = false;
mysqli_select_db($config, $database_config);

$LoginRS__query = sprintf("SELECT email, senha, id_funcao FROM usuario WHERE email=%s AND senha=%s", GetSQLValueString($loginUsername, "text"), GetSQLValueString($password, "text"));

$LoginRS = mysqli_query($config, $LoginRS__query) or die(mysqli_error($config));
$loginFoundUser = mysqli_num_rows($LoginRS);
if ($loginFoundUser) {
while($loginStrGroup = mysqli_fetch_array($LoginRS)){
$nivel = $loginStrGroup['id_funcao'];
}

if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}

//declare two session variables and assign them
$_SESSION['MM_Username'] = $loginUsername;
$_SESSION['MM_UserGroup'] = $nivel;

if (isset($_SESSION['PrevUrl']) && false) {
$MM_redirectLoginSuccess = $_SESSION['PrevUrl'];
}
header("Location: " . $MM_redirectLoginSuccess );
}else{
header("location: ".URL::getBase()."login/mensagem/1");
}
}



Restrict (Que acredito não conseguir controlar o tempo da sessão)

if(!isset($_SESSION)){
session_start();
}

$pagina_link = $array_pgn[2];

$sql_v_1 = mysqli_query($config, "SELECT id FROM recursos WHERE url = '$array_pgn[2]'") or die(mysqli_error($config));

if(@mysqli_num_rows($sql_v_1) <= '0'){
echo "
<div class=\"col-lg-6\">
<div class=\"alert alert-danger\">
<strong>Erro!</strong> $erro
</div>
</div>
";
}else{
while($r_sql_v_1 = mysqli_fetch_array($sql_v_1)){
$recurso_pagina = $r_sql_v_1[0];
}
}

$sql_v_2 = mysqli_query($config, "SELECT id_funcao FROM permissaodafuncao WHERE id_recurso = '$recurso_pagina'") or die(mysqli_error($config));

if(@mysqli_num_rows($sql_v_2) <= '0'){
echo "
<div class=\"col-lg-6\">
<div class=\"alert alert-danger\">
<strong>Erro!</strong> $erro
</div>
</div>
";
}else{
while($r_sql_v_2 = mysqli_fetch_array($sql_v_2)){
$array_usuarios_autorizados[] = $r_sql_v_2[0];
}
}

if(!empty($array_usuarios_autorizados)){
$usuarios_autorizados = implode(",",$array_usuarios_autorizados);
}else{
$usuarios_autorizados = "";
}

$MM_authorizedUsers = $usuarios_autorizados;
$MM_donotCheckaccess = "false";

// *** Restrict Access To Page: Grant or deny access to this page
function isAuthorized($strUsers, $strGroups, $UserName, $UserGroup) {
// For security, start by assuming the visitor is NOT authorized.
$isValid = False;

// When a visitor has logged into this site, the Session variable MM_Username set equal to their username.
// Therefore, we know that a user is NOT logged in if that Session variable is blank.
if (!empty($UserName)) {
// Besides being logged in, you may restrict access to only certain users based on an ID established when they login.
// Parse the strings into arrays.
$arrUsers = Explode(",", $strUsers);
$arrGroups = Explode(",", $strGroups);
if (in_array($UserName, $arrUsers)) {
$isValid = true;
}
// Or, you may restrict access to only certain users based on their username.
if (in_array($UserGroup, $arrGroups)) {
$isValid = true;
}
if (($strUsers == "") && false) {
$isValid = true;
}
}
return $isValid;
}

$MM_restrictGoTo = "login";
if (!((isset($_SESSION['MM_Username'])) && (isAuthorized("",$MM_authorizedUsers, $_SESSION['MM_Username'], $_SESSION['MM_UserGroup'])))) { //tempo
$MM_qsChar = "/";
$MM_referrer = $_SERVER['PHP_SELF'];
if (strpos($MM_restrictGoTo, "?")) $MM_qsChar = "&";
if (isset($_SERVER['QUERY_STRING']) && strlen($_SERVER['QUERY_STRING']) > 0)
$MM_referrer .= "?" . $_SERVER['QUERY_STRING'];
//$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "verificacao-de-acesso=" . urlencode($MM_referrer);
$MM_restrictGoTo = $MM_restrictGoTo. $MM_qsChar . "erro/2";
//header("Location: ". $MM_restrictGoTo);
header("Location: ". $dir_base.$MM_restrictGoTo);
exit;
}

O Restrict é o que gerencia enquanto o usuário está logado.
Você precisa estar logado no PHPBrasil.com para poder enviar mensagens para os nossos fóruns.

Faça o login aqui.