How to know which user is logged in with ajax requests? [closed]

0

I have a problem with my ajax functions, I made a simple login with a request get to a REST server asking for the data of userName, password and id and I compare it with the entered data userName and password and if it matches one it redirects me to the main page that is in another html, in this I want to show that user is logged, his name and password, and as at the time he redirects all the data to be consulted so I made a global variable of type int that initialize to 0, and in the logueo pass the id to another global function where I parsed the id and save it in my variable and to see that if I get the value I put the variable in a console.log and if I save the value obtained the problem falls when I finish doing this in the validation redirects me to my main page and even if I save the id in another global function with the variable at the moment of loading the new page, the data is lost and I need to save the id to be able to show the user's information through another ajax request but only asking the user with that id

In this part I do the Get request and compare the results with the entered data and I get the id of this user

function valida() {

        var nombre1 = $("#nombre").val();
        var password1= $("#password").val();

        $.ajax({
            type: "GET",
            url: "http://localhost/Tatiaxca/API/Usuario/",

            success: function(response){                
                console.log("success");

             $.each(response, function(i, value){
                    var nombreA=value.Nombre;
                    var passwordA=value.password;
                    var id=value.IdUsuario;

                    if (passwordA == password1 & nombreA == nombre1) {
                        console.log("usuario encontrado");
                        console.log(id, passwordA, nombreA);
                        idl=parseInt(id);
                        console.log(idl);
                        datoid(idl)
                    location.href="menur.html";


                    }
                    else{
                    notFound();
                }
        }); 
            }

        });
};

in this last part died a notification, it is also the function of verifico that receives the id in the vaiable and also this the function with the query to know that user is logged in but does not receive anything the variable in spite of that already happens the value.

function notFound() {
                 var $toastContent = $('<span>Registro no encontrado</span>');
                     Materialize.toast($toastContent, 2000);
            }


           function datoid(a) {
       //         idl=parseInt(a.id);
                console.log(idl)
            }

          function userlog() {  
console.log(idl, "paso");
    var html1='<li id="';
    var htmlid='" style="background-color: black;"><h4 style="color: blue;">'; //aqui recupero los nombre y el id
    var html2='</h4></li>'
    $.ajax({
    url: 'http://localhost/Tatiaxca/API/Usuario/'+idl, // url del recurso
    type: "GET", // podría ser get, post, put o delete.
    data:{
        IdUsuario:idl
    },
    success: function (response) {
        console.log(response);
        $.each(response, function(i, value){
            var nombreB=value.nombre;
            console.log(nombreB);
            $("ul.nombre").append(html1+ido+htmlid+"hola :"+nombreB+html2);
 
                
        })  
    }

    });
}

This is my code in the part where my global variable is and where I verify that the fields are not empty

var idl = 0;
$(document).ready(function(){

});

function credenciales(){
        var nombre1 = $("#nombre").val();
        var password1 = $("#password").val();
        userL=nombre1.length;
        passL=password1.length;
        if(userL<1 || passL <1){
            var $toastContent = $('<span>Por favor, ingrese credenciales</span>');
                     Materialize.toast($toastContent, 2000);
        }
    else{
        valida();
    }
}
    
asked by MARCO ANTONIO LUNA SALAS 04.04.2018 в 09:33
source

1 answer

1

First of all let me tell you that the way you are doing the login is insecure, you are making a call to the API that returns all users with their respective password and doing the check on the client, any to see your calls in AJAX could see all the credentials, but hey, that for another question.

As for maintaining the user ID, you could use the localStorage to keep it in the current session, having an object with the id and the maximum duration of the log.

The validation code would look something like this:

function valida() {

    var nombre1 = $("#nombre").val();
    var password1 = $("#password").val();

    $.ajax({
        type: "GET",
        url: "http://localhost/Tatiaxca/API/Usuario/",

        success: function (response) {
            console.log("success");

            $.each(response, function (i, value) {
                var nombreA = value.Nombre;
                var passwordA = value.password;
                var id = value.IdUsuario;

                if (passwordA == password1 & nombreA == nombre1) {

                    /// Crear un objeto date y agregarle una hora
                    var today = new Date();
                    today.setHours(today.getHours() + 1);

                    /// objeto con el id usuario y la hora maxima para estar logeado
                    var obj = {
                        id: parseInt(id),
                        maxdate: today
                    }

                    /// Lo guardas en localstorage
                    localStorage.setItem("currentUser",JSON.stringify(obj));

                    console.log("usuario encontrado");
                    console.log(id, passwordA, nombreA);
                    idl = parseInt(id);
                    console.log(idl);
                    datoid(idl)
                    location.href = "menur.html";


                } else {
                    notFound();
                }
            });
        }

    });
};

Then in the main load of the application, you check if the object exists in localStorage and there are two possibilities:

  • If it exists - > Look at the time, if it is less than the current one, it is logged and you update the time, if it is longer, you have to login.

  • If it does not exist - > You have to log in.

I hope I have helped you.

    
answered by 04.04.2018 / 10:54
source