views:

105

answers:

5

Hi All,

This is for a Java script course that Im taking...

I need to create a simple user-login script. When the page loads a prompt pops up asking for the user name. If the correct username is entered, another prompt is displayed asking for a password.

If both the username and valid, then you a sucessful message, otherwise you get a failure message.

I've written all of the code, but am having trouble with validating the username and password. You can see in my code that I'm using two array lists. One for users and another for passwords. When I run my code, if I type in the correct username and password for user1, it validates, BUT if I enter user1 and the password for user2, it still validates.

<script type="text/javascript">
//Input from user
    var userId = prompt("Enter UserID", "");
        userId_lowercase = userId.toLowerCase();


//Username and Password Arrays
    var userIdList = new Array();
        userIdList[0] = "user1";
        userIdList[1] = "user2";
        userIdList[2] = "user3";

    var passwordList = new Array();
        passwordList[0] = "pass1";
        passwordList[1] = "pass2";
        passwordList[2] = "pass3";

//Process input and check for authentication

    //Check for correct userId

        var userIdFound;

        for (index in userIdList) 
        {
            if (userId_lowercase == userIdList[index]) 
            {
                userIdFound = "Y";
                break;
            }
        }

        if (userIdFound == "Y") 
        {
            document.write("<p>" + userId + " was Found</p>"); ;
            //Check for correct Password
            var password = prompt("Enter Password", "");
            var passwordFound;

            for (index in passwordList) 
            {
                if (password == passwordList[index]) //  This is where I need help, 
                                                     //  how do I say 
                                                     //  "if password is from the passwordList && it matches the userId index selected"

                {
                    passwordFound = "Y";
                    break;
                }
            }

            if (passwordFound == "Y") 
            {
                document.write("<p>Welcome to the class!</p>"); 
            }
            else 
            {
                document.write("<p>Error: Password is not valid.</p>"); 
            }//END Password Check

        } 
        else 

        {
            document.write("<p>" + userId + " was NOT found</p>"); 
        }//END USERID Check

</script>
+2  A: 

Rather than using arrays, use objects as associative arrays:

var Users = {
    root: 'god',
    fred: 'derf',
    luser: 'password'
};

// you can access object properties using dot syntax:
User.root
// or using array syntax with a string as index
User['root'];
// when the name is stored in a variable, array syntax is the only option
var name='root';
User[name];

It's a good thing this is homework, otherwise I'd have to smack you with a board of cluefulness due to the inherent insecurity.

You should also look into using the DOM API rather than the antiquated document.write.

<script type="text/javascript">
  ...
  function reportLogin(msg) {
    var loginMsg = document.getElementById('LoginMsg');
    if (loginMsg.firstChild) {
      loginMsg.firstChild.nodeValue=msg;
    } else {
      loginMsg.appendChild(document.createTextNode(msg))
    }
  }
</script>
...
<p id="LoginMsg"></p>

or

<script type="text/javascript">
  ...
  function reportLogin(msg) {
    document.getElementById('LoginMsg').firstChild.nodeValue=msg;
  }
</script>
...
<p id="LoginMsg"> </p>

(Note the space in #LoginMsg.)

outis
A: 

You will need to check the index of the username against the password. Once you have the username save that index to a variable say indexOfUserName and check that index against your password array. So instead of if (password == passwordList[index]) check if (password == passwordList[indexOfUserName])

Jeff Schmidt
+1  A: 

Here is where I would use a hash table (associative array)

var users = {
user1:"pass1",
user2:"pass2",
user3:"pass3"
}; 

Now you can test like this:

function checkValidUser(userId, userPwd) {
  return ( users[userId] == userPwd );
}

Very simple.

Robusto
Don't give away too much, considering this is homework.
outis
The idea's okay, but if the user enters a name that's not correct and cancels the password dialog, you will end up with `undefined == null` which is true. There are several easy fixes, but using javascript for this isn't really secure anyway.
Matthew Crumley
Yeah, Matt, you can use the === operator to solve that problem. Crockett recommends always using that anyway. I also started into a lecture about the insecurity of using Javascript for password for validation, but this is homework, after all, so I assumed it would not be a real-life scenario.
Robusto
+2  A: 

First of all, I wouldn't use for-in, I'd use a simple for loop to iterate over the array. Then you could store the index that matches the user name to compare it to the password array:

var index;
var userIndex;
for (index = 0; index < userIdList.length; index++) {
            if (userId_lowercase == userIdList[index]) 
            {
                userIndex = index;
                userIdFound = "Y";
                break;
            }
}

Then, in your password loop you'd say:

if (password == passwordList[index] && index == userIndex)
{
    passwordFound = "Y";
    break;
}

That's the simple way around the problem. I don't know how much you've learned but you could also use an array of objects:

var userLogins = [{user:"user1", password:"pass1"},...etc];

And then loop through that array once after asking for the name and password and seeing if they match:

for (index = 0; index < userLogins.length; index++) {
    if (userLogins.user == userId_lowercase && userLogins.password == password) {
        //Do stuff here
    }
}

The thing to keep in mind is that you have to link the user name to the password somehow. The way you're currently doing this is by the index in both arrays, but that isn't guaranteed. It'd be much better to link the two bits of information in some way, as in the array of objects above.

Bob
I'm very grateful for you passing on your knowledge. This helped a bunch. I've always had a problem with loops. Working on these projects is really helping me understand them.I agree with what alot of people have mentioned about using Javascript to authenticate a user. But this project has helped me understand how to work with arrays and loops.Again, you guys rock!BTW - The StackoverFlow community is BEST!
NoDinero
A: 

If you want to make your teacher regrets her question, here's a special version:

    var users = { user1:true, user2:true, user3:true },
        pwds = {user1:'pw1', user2:'pw2', user3:'pw3'};

    function theUser(userId){
        return {
            hasThePassword:function(pwd){
                return users[userId] && pwds[userId] === pwd;
            }
        };
    }
    if( theUser( prompt('Enter UserID', '') ).hasThePassword( prompt('Enter Password', '') )){
        alert('user ok');
    }else{
        alert('wrong user or password');
    };

;-)

Mic