-1

first of all, thank you for trying to help me. I am just starting out with node and js and i have quite some things to learn. I am simply just doing a college task where i have to make a login functionality, without actually registering the user but instead writing default users in an js array without databases only for testing purposes.

I created the users array:

 const userDB = [

{ 

   email: "chris@gmail.com",
    password: "chris"

},

{

    email: "jack@gmail.com",
    password: "jack"
}
  ];
   module.exports = { userDB };

And here is my js function:

   app.post('/login', async (req, res) => {
try{

    for (var i = 0; i < users.length; i++) {
        let foundUser = users.find((data) => req.body.email === data.email);
        if (foundUser) {

        let submittedPass = req.body.password; 
        let storedPass = foundUser.password; 

        const passwordMatch = await bcrypt.compare(submittedPass, storedPass);
        if (passwordMatch) {
            let usrname = foundUser.username;
            res.send(`<div align ='center'><h2>login successful</h2></div><br><br><br><div align ='center'><h3>Hello ${usrname}</h3></div><br><br><div align='center'><a href='/login.html'>logout</a></div>`);
        } else {
        res.send("<div align ='center'><h2>Invalid email or password</h2></div><br><br><div align ='center'><a href='/login.html'>login again</a></div>");
        }
    }

        else {

        let fakePass = `$2b$$10$ifgfgfgfgfgfgfggfgfgfggggfgfgfga`;
        await bcrypt.compare(req.body.password, fakePass);

        res.send("<div align ='center'><h2>Invalid email or password</h2></div><br><br><div 
           align='center'><a href='/login.html'>login again<a><div>");
    }
}
}

But whenever i try to log in the default user from the array it just says invalid email/password. Any help would be gladly appreciated!!

Henry Twist
  • 5,666
  • 3
  • 19
  • 44
BabyK
  • 1
  • [The difference between Java and JavaScript](https://stackoverflow.com/questions/245062/whats-the-difference-between-javascript-and-java). – Henry Twist Apr 24 '21 at 00:33

1 Answers1

0

I guess, that this line will return undefined:

let usrname = foundUser.username

since your user model does not have a property called username.

Furthermore you should narrow down the error: do you get your "invalid" response from the nested if/else or from the main? Are you sure that you have a foundUser? Try to console.log() your expected values.

PixAff
  • 309
  • 4
  • 14
  • I edited it but still i can't log in. Maybe i am checking wrong here? What is the proper way to check from a user array on the back end when i put email and password on the front end? – BabyK Apr 24 '21 at 00:47
  • start to debug from top to bottom: `console.log(users)` does that work? `console.log(foundUser)` does that work, and so on. And If you have a `try` - you also want to have a `catch` – PixAff Apr 24 '21 at 00:54