0

I am trying to check the credentials of a user who is trying to login. Even though I am entering the right credentials that are already present in the database, I am getting the output as "User not found." Below is the code snippet. I hope you can help. Please be specific because I am a beginner and I am trying really hard. Thanks.

app.post('/login',function(req,res){
    credential.findOne({uname: req.body.uname, password:req.body.password}, function(err,isMatch){
        if(err){
            res.status(500).send(err);
        }
        else{
        if(isMatch){
            res.status(200).send("You are logged in succesfully.");
        }
        else{
            res.status(200).send("User not found");
        }
    }
});
});

https://github.com/tahseen09/login

Tahseen Rahman
  • 97
  • 3
  • 13
  • 1) Try consoling `req.body` and seen if you are getting correct values in API. 2) Try consoling `isMatch ` and see if its an empty object. – Arbaz Siddiqui Sep 30 '18 at 10:17
  • 1
    I suppose that you are encrypting your user password when creating user and in this case you cant send plain text to into query. Can you please in credential.findOne set only uname: req.body.uname and check if returns anything. Good sample f authentication you can check here : https://medium.freecodecamp.org/learn-how-to-handle-authentication-with-node-using-passport-js-4a56ed18e81e – Nezir Sep 30 '18 at 10:24
  • 1
    @Nezir I am not encrypting anything. It's a very basic app to get my concepts clear. – Tahseen Rahman Sep 30 '18 at 10:38
  • 1
    @ArbazSiddiqui You were right, the values are null for both of them. How can I correct it? Please help me. – Tahseen Rahman Sep 30 '18 at 10:42
  • 1
    There could be multiple reason for body in the api to be empty. Try following : 1) Try hitting the api with postman and send `uname` and `password` in body. 2) If you are using express, check if the `body-parser` plugin is configured correctly. – Arbaz Siddiqui Sep 30 '18 at 10:52
  • 1
    If `isMatch` is null and `err` is null, it means that it doesn't find the user in your database. It is logic because it is displaying you `User not found` which corresponds to this case. Do you check if the user exist in your database ? (in command line) – ElJackiste Sep 30 '18 at 11:16
  • @TahseenRahman don't forget to add body-parser package to your express app. https://www.npmjs.com/package/body-parser – Ron537 Sep 30 '18 at 14:24
  • @ElJackiste Yes, I have already checked and the user I am trying for exists in the database. Thanks for the help. – Tahseen Rahman Sep 30 '18 at 15:15
  • @Ron537 I am using dependencies such as express, body-parser, mongoose. – Tahseen Rahman Sep 30 '18 at 15:15
  • @TahseenRahman having it as dependency is not enough, you should use it and apply it to your express app. Take a look at this [question](https://www.google.co.il/url?sa=t&source=web&rct=j&url=https://stackoverflow.com/questions/24543847/req-body-empty-on-posts&ved=2ahUKEwjf36qopOPdAhWSposKHZ6BB38QjjgwAHoECAYQAQ&usg=AOvVaw3Jbroyp7YSrJrUU-Le6Z3j) – Ron537 Sep 30 '18 at 17:50

1 Answers1

1

Your code should works.

You need to check if the problem is not from another place.

An example :

var Schema = require('mongoose').Schema;

var userSchema = new Schema({
  uname: {
    type: String,
    required: true
  },

  password: {
    type: String,
    required: true
  }
});

module.exports = require('mongoose').model('User', userSchema);

var User = require('pathToUserModel');

app.post('/login', function(req, res) {
  User.findOne({
      uname: req.body.uname,
      password: req.body.password
    }, function(err, user) {
      if (err) { return res.status(500).send(err); }

      if (!user) { return res.status(200).send("User not found"); }

      return res.status(200).send("You are logged in succesfully.");
    }
  });
});
<form action="/login" method="POST">
  <input type="text" name="email" placeholder="your email">
  <input type="password" name="password" placeholder="your password">
  
  <input type="submit" value="submit">
</form>

You need to check if you have the user stored in your database or it will not works. To do that you can access your database in command line :

  • Open a command line prompt
  • type mongo
  • type use nameOfYourDB You need to replace nameOfYourDB by your database name
  • type db.users.find() : users is the name of your collection

Then you can see what is stored in your DB.

Your database should also be started on your system with mongod and your app should be connected to the database with something like require('mongoose').connect('mongodb://127.0.0.1/nameofYourDB', { /* options */ }); (still need to replace nameOfYourDB).

You should keep in mind that it is just an example to understand the logic. In production you should do more work as validate form, hash passwords with a salt and a derivation function etc.

ElJackiste
  • 4,011
  • 5
  • 23
  • 36
  • 1
    Yes. Thank you so much. I understand it has to be a lot more secure but all I am trying to do here is to take it slow and make it work. I hope you understand. – Tahseen Rahman Sep 30 '18 at 15:17
  • Of course, that why i put the whole example. Are you doing like that (or something similar) ? – ElJackiste Sep 30 '18 at 15:18
  • The npm package you are using. What's that? – Tahseen Rahman Sep 30 '18 at 15:19
  • 1
    Which one ? `require('pathToUserModel');` ? – ElJackiste Sep 30 '18 at 15:24
  • 1
    @TahseenRahman If it's that, it's not a npm package, it's the way to require the model. You need to replace it by the path of the file where your model is defined. In my example, it is the file where i defined the schema. – ElJackiste Sep 30 '18 at 15:33
  • This is the github link for the code: https://github.com/tahseen09/login – Tahseen Rahman Sep 30 '18 at 16:05
  • 1
    @TahseenRahman I download your project, it works good. I can register a user and then login without error. The user is created in database. Everything is fine. Maybe you don't send a good request to your server because me i was using form than i created in your project. – ElJackiste Sep 30 '18 at 17:47
  • 1
    @TahseenRahman I downloaded your project, run `npm install` then `npm i express` & `npm i mongoose` because they was not in the package.json file. Then i created the database, ran it, created HTML form and run your server. I didn't change your code. It works fine. – ElJackiste Sep 30 '18 at 17:58
  • 1
    @TahseenRahman you're welcome. About the database, you should firstly open a terminal and type `mongod` to start mongoDB. Then you should check if your database exist by opening an **other terminal** (don't close the first one) and type `mongo` then `use login` in your case (i will create the database if it doesn't exist). Then you can run your node process to start your server in another terminal. MongoDB process should be running in the same time of your server to access the database. Don't forgot to validate this answer if it fix your problem. – ElJackiste Sep 30 '18 at 18:30