How to add token based authentication to login

Hello everyone, I am very new and confused. I am following this Udemy tutorial: https://www.udemy.com/course/the-complete-web-development-bootcamp/. I set up a username and password on userDB using Mongo using Robo 3T. The login works, but if I put a wrong login that does not match what I have in my database, the website just gets stuck and keeps trying to “load”.

Hello man!
The route followed by the situation you described (login failed) is app.post("/login") i guess. If the app get stuck probably you have not a res.render on error ( the screenshot is cut :confused: ).

About the token auth i think you will add a middleware later in that tutorial (but you need other to follow the tutorial about that i suppose :stuck_out_tongue: ).

Good luck!

1 Like

Thank you so much! I have a redirect on error but it still keeps circling and trying to load.
11%20AM

1 Like

Uhm, have you tried res.redirect("/login");?

1 Like

Yes I have! It does the same thing, keeps loading. :sweat_smile:

Oh^^
As far as i understand you’re missing one path there, and it’s exactly the one triggered when foundUser exists but the password doesn’t match ^^

If (err) excludes that foundUser is null/undefined, ( if err does not exists, foundUser must do), so you can remove that conditional to simplify the syntax ^^
Add the else clause to the if(foundUser.password === password) and add a `res.redirect("/login") there, it should work!

1 Like

Thank you so much aaa I"m so grateful! Sorry what do you mean by adding the else clause? From what I understand, is that I get rid of the if statement above first? And I now just have this.

else{
        if (foundUser){
          if (foundUser.password === password){
            res.redirect("counter");
          }
        }
      }

I figured it out by the way! Just in case this helps you too! :slight_smile:

1 Like

Sorry what do you mean by adding the else clause?

..., function(err, foundUser){
   if(err){
      console.log(err);
      res.redirect("/login");
   } else {
      if (foundUser){
         if (foundUser.password === password){
            res.redirect("/counter");
         } else { // <--- add this 'else'; this is the path your request wasn't able to find
            res.redirect("/login"); // <-- password doesn't match. Back to login!
         }
...

This is what i meant^^
However the solution proposed in SO is better imho: the if's are used as checks, if nothing match then the ‘normal’ path is executed (res.redirect("/counter"));

I’m happy you solved, have a good day! :smiley:

1 Like

You are so kind! Thank you for the help too! Have a good day as well!

1 Like