Search code examples
javascripthtmlauthenticationpromiseprompt

(HTML/Js) Authentication Using Prompts and Promises


I have a bit of code below:

async function authenticateUser() {
        let authenticated = false;
        socketTx = io();
        socketRx = io.connect();

        var user = prompt("Please enter username", "");
        var pass = prompt("Please enter your password", "");

        socketTx.emit('authChannel', {username: user, password: pass});

        let promise = new Promise((resolve, reject) => {
              socketRx.on('authChannel', function(auth) {
                //console.log(auth);
                resolve(auth); 
              });
        });

        authenticated = await promise;
        console.log(authenticated)
        if (authenticated == false) {
          user;
          pass;
        } else {authenticated == true}
      }

The socketTx is sending the user/pass data to the server for PAM authentication in Node.js. socketRx receives a true/false for whether the user was authenticated.

The desired behavior is for the prompts to spam the user until the right "login" information is provided. I thought I captured this behavior in calling the variables user/pass again once the authentication is verified to be false but the prompts do not display a second (or more) time(s). I can confirm that I receive the correct info at console.log(authenticated).

Is there something obvious I am missing?

Thanks in advance.


Solution

  • As per comment:

    async function authenticateUser() {
            let authenticated = false;
            socketTx = io();
            socketRx = io.connect();
    
            var user = prompt("Please enter username", "");
            var pass = prompt("Please enter your password", "");
    
            socketTx.emit('authChannel', {username: user, password: pass});
    
            let promise = new Promise((resolve, reject) => {
                  socketRx.on('authChannel', function(auth) {
                    //console.log(auth);
                    resolve(auth); 
                  });
            });
    
            authenticated = await promise;
            console.log(authenticated)
            if (authenticated == false) {
              authenticateUser(); // recall method
            } else {authenticated == true}
          }