使用nodeJS登录系统

时间:2016-10-10 06:14:31

标签: node.js mongodb passport.js mongo-shell

我在localhost上登录系统,注册页面正在运行但登录页面没有。它一直显示我无效的密码。 顺便说一句,我使用mongodb作为我的数据库。 在我的mongodb上,我能够查看存储在mongo shell上的那些数据。

我感谢那些能够审核这些代码的人。谢谢!

图像: showing invalid password image

这是我的代码:

app.js

var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var mongo = require('mongodb');
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/loginapp');
var db = mongoose.connection;

var routes = require('./routes/index');
var users = require('./routes/users');

//Init App
var app = express();

//View Engine
app.set('views', path.join(__dirname, 'views')); //handle view
app.engine('handlebars', exphbs({defaultLayout:'layout'})); //set default view to layout
app.set('view engine', 'handlebars'); //set view engine to handlebars

//BodyParser Middleware (Configuration)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());

//Set static folder (public folder.. stylesheet,images)
app.use(express.static(path.join(__dirname, 'public')));

//Express Session (Middleware for express session)
app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
}));

//Passport init
app.use(passport.initialize());
app.use(passport.session());

//Express Validator (Middleware for validator)
app.use(expressValidator({
    errorFormatter: function(param, msg, value) {
        var namespace = param.split('.')
        , root  = namespace.shift() 
        , formParam = root;

    while(namespace.length) {
        formParam += '[' + namespace.shift() + ']';
    }
    return {
        param : formParam,
        msg : msg,
        value : value
    };
    }
}));
//connect flash
app.use(flash());

//Global Vars (global func)
app.use(function (req, res,next) {
    res.locals.success_msg = req.flash('success_msg');
    res.locals.error_msg = req.flash('error_msg');
    res.locals.error = req.flash('error');
    res.locals.user = req.user || null;
    next();
});

//Middleware for route files
app.use('/', routes); //map to routes index files
app.use('/users', users);

//Set Port (start the server)
app.set('port', (process.env.PORT || 3000));

app.listen(app.get('port'), function(){
    console.log('Sever started on port '+app.get('port'));
});

路由/用户

var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

var User = require('../models/user');

// Register
router.get('/register', function(req, res){
    res.render('register');
});

// Login
router.get('/login', function(req, res){
    res.render('login');
});

// Register User
router.post('/register', function(req, res){
    //Get all the stuff into variable 
    var name = req.body.name;
    var email = req.body.email;
    var username = req.body.username;
    var password = req.body.password;
    var password2 = req.body.password2;

    //Validation
    req.checkBody('name', 'Name is required').notEmpty();
    req.checkBody('email', 'Email is required').notEmpty();
    req.checkBody('email', 'Email is not valid').isEmail();
    req.checkBody('username', 'Username is required').notEmpty();
    req.checkBody('password', 'Password is required').notEmpty();
    req.checkBody('password2', 'Passwords do not match').equals(req.body.password);

    var errors = req.validationErrors();

    if(errors){
        res.render('register',{
            errors:errors
        });
    } else { 
        var newUser = new User({
            name: name,
            email: email,
            username: username,
            password: password
        });

        User.createUser(newUser, function(err, user){
            if(err) throw err;
            console.log(user);
        });

        req.flash('success_msg', 'You are registed and can now login');

        res.redirect('/users/login');
    }
});

passport.use(new LocalStrategy(
  function(username, password, done) {
   User.getUserByUsername(username, function(err, user){
    if(err) throw err;
    if(!user){
        return done(null, false, {message: 'Unknown User'});
    }

    User.comparePassword(password, user.password, function(err, isMatch){
        if(err) throw err;
        if(isMatch){
            return done(null, user);
        } else {
            return done(null, false, {message: 'Invalid password'});
        }
    });
   });
  }));

passport.serializeUser(function(user, done) {
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  User.getUserById(id, function(err, user) {
    done(err, user);
  });
});


router.post('/login',
  passport.authenticate('local', {successRedirect:'/', failureRedirect:'/users/login',failureFlash: true}),
  function(req, res) {
    res.redirect('/');
  });

router.get('/logout', function(req, res){
    req.logout();

    req.flash('success_msg', 'You are logged out');

    res.redirect('/users/login');
});

module.exports = router;

模型/用户

var mongoose = require('mongoose'); 
//hash password
var bcrypt = require('bcryptjs'); 

//User schema
var UserSchema = mongoose.Schema({
    username: {
        type: String,
        index: true
    },
    password: {
        type: String
    },
    email: {
        type: String
    },
    name: {
        type: String
    }
});

//Variable that can access outside this file
var User = module.exports = mongoose.model('User', UserSchema);

//User function
module.exports.createUser = function(newUser, callback) {
        bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash("newUser.password", salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

module.exports.getUserByUsername = function(username, callback){
    var query = {username: username};
    User.findOne(query, callback);
}

module.exports.getUserById = function(id, callback){
    User.findById(id, callback);
}

module.exports.comparePassword = function(candidatePassword, hash, callback){
    bcrypt.compare(candidatePassword, hash, function(err, isMatch) {
        if(err) throw err;
        callback(null, isMatch);
    });
}

1 个答案:

答案 0 :(得分:3)

你这里有个错误

module.exports.createUser = function(newUser, callback) {
        bcrypt.genSalt(10, function(err, salt) {
        bcrypt.hash("newUser.password", salt, function(err, hash) {
            newUser.password = hash;
            newUser.save(callback);
        });
    });
}

一定是

bcrypt.hash(newUser.password, salt, function(err, hash) {
//__________^______________^ removed quotes
    newUser.password = hash;
    newUser.save(callback);
});

因此,当用户注册时,它的密码设置为"newUser.password",但不是实际用户的密码