Mostafa Ghadimi
Mostafa Ghadimi

Reputation: 6736

access the user._id in nodejs

I'm pretty new with node.js and I'm trying to implement simple user registration and login form using Node.js, Express, bcrypt, express-session and mongoose.

Whenever the user log in, I want to set the value of req.session.userID to user's id. When I trace the code I can't find the problem. I followed up the tutorial in this link and everything seems to be similar.

Schema:

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

var bcrypt = require('bcrypt');

var userSchema = new Schema({
    teamName: {
        type: String,
        unique: true,
        trim: true,
        required: true
    },
    faculty: {
        type: String,
        required: true
    },
    email: {
        required: true,
        unique: true,
        trim: true,
        type: String
    },
    password: {
        required: true,
        type: String
    },
    score: {
        type: Number,
        default: 0
    }
});

userSchema.pre('save', function(next) {
    var user = this;
    bcrypt.hash(user.password, 10, function(err, hash) {
        if (err) return next(err)
        user.password = hash;
        next();
    });
});

userSchema.statics.authenticate = (email, password, callback) => {
    userModel.findOne({email: email}, (err, user) => {
        if (err) return callback(err);
        else if (!user) {
            console.log('User not found!')
        }
        else {
            bcrypt.compare(password, user.password, (err, result) => {
                if (result) {
                    callback(null, true)
                }
                else {
                    return callback()
                }
            })
        }
    })
}

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

server:

var userModel = require('./../models/users');
router.post('/login', (req, res) => {
    var email = req.body.email;
    var password = req.body.password;
    userModel.authenticate(email, password, (err, user) => {
        console.log(user)
        if (err) {
            console.log(err)
        }
        else if (!user) {
            console.log('Wrong Password')
        }
        else {
            req.session.userId = user._id;
            console.log(req.session.userId);

        }
    })
});

Where I have logged the value of req.session.userId it returns undefined! Where is the problem?

Upvotes: 1

Views: 830

Answers (1)

Edrian
Edrian

Reputation: 608

The problem is that the callback is returning TRUE. the callback should be returning the user data. callback(null, user)

bcrypt.compare(password, user.password, (err, result) => {
                if (result) {
                    callback(null, true)
                }

Should be

bcrypt.compare(password, user.password, (err, result) => {
                if (result) {
                    callback(null, user)
                }

Upvotes: 1

Related Questions