Login Security with PHP and AJAX safely targeting

Asked

Viewed 199 times

1

Recently I had to make a login system with access levels, but when directing the user to a given page hit me a question regarding the security of the code. Ignore the validations, I will show only the part that hit me the doubt...

I’ve always done it this way:

//JS 
$(document).ready(function(){

    $("#btnEntrar").click(function(){

        //Recebendo os dados do formulário
        var email = $("#email").val();
        var senha = $("#senha").val();

        //Enviando dados para o PHP
        $.post('valida-login.php',
                {email : email, senha : senha},

            //Resposta do PHP
            function(retorno){

                // Validação OK
                if (retorno == 'nivel_1') {

                    // Mensagem
                    $('.retorno').html('Login sucesso!');
                    setTimeout(function(){ location.href = "cpanel-adm.php"; }, 2000);

                }else{

                    // Mensagem
                    $('.retorno').html('Login sucesso!');
                    setTimeout(function(){ location.href = "cpanel-clt.php"; }, 2000);

                }
            })
        }
        return false;
    })
})

File validates-login.php

<?php 

//Sessão iniciada
session_start();

//Recebendo o formulário via Post pelo Ajax
$email = $_POST['email'];
$senha = $_POST['senha'];

//Fui no banco e verifiquei o nível de usuário

if(nivel == 1){

   $_SESSION['email'] = $email;
   echo 'nivel_1';

}else{

    $_SESSION['email'] = $email;
    echo 'nivel_2';
}
?>

This works well and has several examples like this on the web. Now the other way I found it is by doing the steering this way:

//OBSERVE QUE A FUNÇÃO DE RETORNO NÃO DIZ NADA DE DIRECIONAMENTO DE PÁGINA
    $(document).ready(function(){

        $("#btnEntrar").click(function(){

            //Recebendo os dados do formulário
            var email = $("#email").val();
            var senha = $("#senha").val();

            //Enviando dados para o PHP
            $.post('valida-login.php',
                    {email : email, senha : senha},

                //Resposta do PHP
                function(retorno){

                    // Validação OK
                    $('.retorno').html(retorno);

                })
            }
            return false;
        })
    })

And the targeting is now done "hidden" in PHP:

<?php 

    //Sessão iniciada
    session_start();

    //Recebendo o formulário via Post pelo Ajax
    $email = $_POST['email'];
    $senha = $_POST['senha'];

    //Fui no banco e verifiquei o nível de usuário

    if(nivel == 1){

       $_SESSION['email'] = $email;
       echo "<script> document.location = 'cpanel-adm.php' </script>";

    }else{

        $_SESSION['email'] = $email;
        echo "<script> document.location = 'cpanel-clt.php' </script>";
    }
    ?>

I wonder if this is optional or certain way is wrong and tends to be more conducive to future attacks.

1 answer

2


Just return the redirect url and scroll to the session, not the middle of PHP.

And you can make a function (or in the Construct) an access level validator with the scroll of the session, if you reverse the order (1 user and 2 admin), it becomes easier for you to work.

JS

if(retorno != 'error')
   window.location.href = retorno;

PHP

$data = $_POST;

//Fui no banco e verifiquei o nível de usuário
if( in_array($nivel, [1,2]) ):
   $_SESSION['email'] = $data['email'];
   $_SESSION['role']  = $nivel;
endif;

switch ($nivel) {
    case 1:
        print 'cpanel-clt.php';
        break;
    case 2:
        print 'cpanel-adm.php';
        break;
    default:
        print 'error';
        break;
}

After that, you can do a function and call where needed, sort of like this:

//SOMENTE ADMIN ACESSA
verificar_nivel(2);

//FUNÇÃO
public function verificar_nivel($nivel_minimo = 1) {

   if(!isset($_SESSION['role']) || $_SESSION['role'] < $nivel_minimo)
      header("Location: logout.php");

}
  • I understood Matheus, cool! Quite different from what I had thought. But the way I did you considered insecure or wrong? Or is it just different than what you did?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.