skip to Main Content

I want to check if the user and pass is matched and also their indexes since im using array of objects im using localstorage and javascriptfor this activity

//find user if exist
    var founduser = accounts.find(e =>{
        return e.user === user
    })

    //find pass if exist
    var foundpass = accounts.find(e =>{
        return e.pass === pass
    })

    //find index of user
    var indexofuser = accounts.indexOf(founduser)

    //find index of pass
    var indexofpass = accounts.indexOf(foundpass)

    //check if either 2 of them is undefined
    if( foundpass != undefined || founduser != undefined){

        //check if the index are matched
        if( indexofuser === indexofpass){
            alert("logged in successfully")
        }
        //return an alert if its not matched
        else{
            alert("Wrong Password Please try again")
        }
    }

    //return an alert if on of it is undefined
    else{
        alert("Wrong Password Please try again")
    }

2

Answers


  1. You can use .find() but make your callback function only return true if both the account’s user and pass properties match:

    const foundUser = accounts.find(account => account.user === user && account.pass === pass);
    
    if (foundUser) {
      alert("logged in successfully");
    } else {
      alert("Wrong Password Please try again");
    }
    

    This should give you the same behaviour as your existing code as you’re logging the same thing in both else blocks. However, do consider the following security implications of:

    • Letting the end user know the password was incorrect. This typically implies that the username is correct (which an attacker might not know originally), although in your code it doesn’t give away too much as you show the incorrect password message in both cases.
    • Performing a .find() can potentially open you up to timing attacks which allows the user to guess what the username / passwords are based on how long your code takes to run
    • How you store your user accounts and passwords. Make sure only the backend has access to user account information such as hashed+salted passwords and usernames. Do not store sensitive account information in local storage (as regular JavaScript code can access this easily).

    So don’t use the above code in production for implementing a username + password system. Use it as an exercise to learn how to find objects in an array that match criteria.

    Login or Signup to reply.
  2. // check for the username & password in one go
    var founduser = accounts.find(e =>{
        return (e.user === user && e.pass === pass)
    })
    
    //check if it is undefined
    if(founduser){
        alert("logged in successfully")
    }
    //return an alert if its is undefined or not matched
    else{
      alert("Wrong Password Please try again")
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search