Check Login and Password

1

I have the following function to login:

function login(username, password, callback) {
        var myResponse;
        var systemUser;

        Users.getByLogin(username)
        .then(function (response) {
            systemUser = response.data;
        });

        // Linha testada
        console.log("Senha: " + systemUser.password);
        console.log("Senha informada: " + password);

        if (typeof systemUser == "undefined") {
            myResponse = { success: false, message: "Usuário inexistente!" };
        } else if (password == systemUser.password) {
            myResponse = { success: true, user: systemUser };
        } else {
            myResponse = { success: false, message: "Usuário ou senha incorretos!" };
        }

        callback(myResponse);
    }

Normally the TypeError: Cannot read property 'password' of undefined error occurs.

If I declare the variable systemUser out of the function, looking at the comment line Linha testada , the value gives undefined the first time I call the method, but the second time passes.

    
asked by anonymous 16.06.2016 / 20:17

1 answer

1

This happens because the Users.getByLogin() method is asynchronous.

Your error occurs because at the time the console.log("Senha: " + systemUser.password); line is executed the return of getByLogin has not yet occurred; systemUser is still a null variable.

Once the result is returned, the function specified in .then() is executed. Modify your code as suggested below:

function login(username, password, callback) {
    var myResponse;
    var systemUser;

    Users.getByLogin(username)
    .then(function (response) {
        systemUser = response.data;

        // Linha testada
        console.log("Senha: " + systemUser.password);
        console.log("Senha informada: " + password);

        if (typeof systemUser == "undefined") {
            myResponse = { success: false, message: "Usuário inexistente!" };
        } else if (password == systemUser.password) {
            myResponse = { success: true, user: systemUser };
        } else {
            myResponse = { success: false, message: "Usuário ou senha incorretos!" };
        }

        callback(myResponse);
    });
}
    
16.06.2016 / 20:21