Home > front end >  Node Mongo Express - I can register a user but I cannot login
Node Mongo Express - I can register a user but I cannot login

Time:11-21

I create an app.js file and an user.js file to register an user, send the data to mongodb and then to log in the user. I can register the user but if I try to log in it does not work. If I try to log in an user that "the user does not exist" I get the proper message so I think the problem is after the line 50 in the app.js file or in the related user.js in User.isCorrectPassword but I can't solve it. Any suggestion?

**app.js**

//declaring const express, path, bodyParser, app
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const app = express();

const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const User = require('./user');


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use(express.static(path.join(__dirname, 'public')));

const mongo_uri = 'mongodb srv://mongo:******@****.****.mongodb.net/test?retryWrites=true&w=majority';

mongoose.connect(mongo_uri, function (err) {
    if (err) {
        throw err;
    } else {
        console.log(`successfully connected to ${mongo_uri}`);
    }
});


app.post('/register', function (req, res) {
    const { firstName, lastName, username, password } = req.body;

    const user = new User({ firstName, lastName, username, password });

    user.save(err => {
        if (err) {
            res.status(500).send('error for user registration');
        } else {
            res.status(200).send('registration complete');
        }
    });
});

app.post('/autenticate', function (req, res) {
    const { username, password } = req.body;

    User.findOne({ username }, function (err, user) {
        if (err) {
            res.status(500).send('error for user registration');
        } else if (!user) {
            res.status(500).send('the user does not exist');
        } else {
            User.isCorrectPassword(password, function (err, result) {
                if (err) {
                    res.status(500).send('autentication error');
                } else if (result) {
                    res.status(200).send('User autenticated');
                } else {
                    res.status(500).send('User and/or password wrong');
                }
            });
        }
    });
});


app.listen(3000, function () {
    console.log('server started');
})
module.exports = app;

user.js


const mongoose = require('mongoose'); //inluding mongoose
const bcrypt = require('bcrypt'); //to encrypt the password

const saltRounds = 10; //how many time the algorytm repite to encrypt

// we specify the field we need for the registration
const UserSchema = new mongoose.Schema({
    firstName: { type: String, required: true },
    lastName: { type: String, required: true },
    username: { type: String, required: true, unique: true }, //user has to be unique
    password: { type: String, required: true }
});

// we could execute the function before data ara saved
UserSchema.pre('save', function (next) {
    if (this.isNew || this.isModified('password')) {
        const document = this;

        bcrypt.hash(document.password, saltRounds, function (err, hashedPassword) {
            if (err) {
                next(err);
            } else {
                document.password = hashedPassword;
                next();
            }
        });
    } else {
        next();
    }
});

UserSchema.methods.isCorrectPassword = function (candidatePassword, callback) {
    bcrypt.compare(candidatePassword, this.password, function (err, same) {
        if (err) {
            callback(err);
        } else {
            callback(err, same);
        }
    });
}

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

CodePudding user response:

app.post('/autenticate', function (req, res) {
    const { username, password } = req.body;

    User.findOne({ username }).then(
      (user, err)=> {
        if (err) {
            res.status(500).send('some error occured');
        } else if (!user) {
            res.status(500).send('the user does not exist');
        } else {
          if(!bcrypt.compareSync(password,user.password))
              return res.status(401).send("wrong password");
            return res.status(200).send('autenticated successfully');            
        }
    }
    )
});
  • Related