护照身份验证显示错误消息,而不是成功消息

时间:2018-12-07 12:47:15

标签: javascript node.js mongodb express passport.js

我是node的新手,正在尝试使用通行证进行身份验证,但是它不能正常工作。注册效果很好,并且用户已存储在数据库中,但是尝试登录不起作用。它将继续在failureFlash上​​显示以下消息:'Invalid username or password''Invalid username or password'即使对于数据库中的用户也是如此。不知道问题所在。

这是我的代码
用于路线的users.js

var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({dest: './uploads'});
var User = require('../models/user');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;

/* GET users listing. */
//On click of register, render registration page
  router.get('/register', function(req, res, next) {
  res.render('register', {title: 'Register', errors: ''});//render register page    and set error object to '' initially
  });

//On click of login, render login page
  router.get('/login', function(req, res, next) {
  res.render('login', {title: 'Login'}); //Render login page and set title to  login(to make the navbtn active **bootstrap) 
  });


//On login, take to Members Area
  router.post('/login',
  passport.authenticate('local', 
  {successRedirect:'/users/members', 
   failureRedirect: '/users/login', 
   failureFlash: 'Invalid username or password'
  }), //set up passport as middleware for authentication
  function(req, res) {
    req.flash('success', 'You are now logged in');
    res.redirect('/users/members');
 /*  res.render('members', {title: 'Members'}); */
 });

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

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

  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) return done(err);
    if(isMatch){
      return done(null, user);
    } else {
      return done(null, false, {message: 'Invalid password'});
     }
   });
  });
}));

//On submit of registration, take to login page **using multer middleware allows us access to file uploads (images)
  router.post('/register', upload.single('ProfileImage'), function(req, res,  next) {
  //Store the inputs of the form in an object, **it can be stored independently in different variables or even an array 
  var details = {
    name: req.body.name,
    email: req.body.email,
    username: req.body.username,
    password: req.body.password,
    password2: req.body.password2
  };

  //what happens when there's a file and no file
  if(req.file){
    console.log('Uploading file...');
    var ProfileImage = req.file.filename;
  } else {
    console.log('No file was uploaded');
    var ProfileImage = 'noimage.jpg';
  } 

  //Form Validator
  req.checkBody('name', 'Name field is required.').isLength({min:1}); 
  req.checkBody('email', 'Email field is required').isLength({min:1});
  req.checkBody('email', 'Email is not valid').isEmail();
  req.checkBody('username', 'Username field is required').isLength({min:1});
  req.checkBody('password', 'Password field is required').isLength({min:1});
  req.checkBody('password2',  'Password do not match').equals(details.password); //compares the password and confirmpassword inputs ensuring that it is equal


  //check errors
  var errors = req.validationErrors(); //if there are errors store in error variable

  if(errors){

    console.log(details.ProfileImage);
    res.render('register', {title: 'Register', errors: errors}) //if error  occurs re-render th register page and now update the error object with errors to  pass into view

  } else { //create a new user based on the user schema
    var newUser = new User({
      name: details.name,
      email: details.email,
      username: details.username,
      password: details.password,
      profileimage: ProfileImage
    });
   //store in database model
    User.createUser(newUser, function(err, user){
      if(err) throw err;
      console.log(user);
    });
    //send message on success
    req.flash('success', 'You are now registered and can now login');
    res.location('/');
    res.redirect('/');
   }


  });


module.exports = router;

**my App.js**  


//Import core modules and installed modules

  var createError = require('http-errors');
  var express = require('express');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var cookieParser = require('cookie-parser');
  var bodyParser = require('body-parser');
  var session = require('express-session');
  var passport = require('passport');
  var ExpressValidator = require('express-validator');
  var LocalStrategy = require('passport-local').Strategy;
  var multer = require('multer');
  var upload = multer({dest: './uploads'});
  var flash =require('connect-flash');
  var bcrypt =require('bcryptjs');
  var mongo = require('mongodb');
  var mongoose = require('mongoose');
  var db = mongoose.Connection;


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

//initialize express function and store in a variable
  var app = express();

// view engine setup
  app.set('views', path.join(__dirname, 'views'));
  app.set('view engine', 'ejs');

//set up middleware
  app.use(logger('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: false }));
  app.use(cookieParser());
  app.use(express.static(path.join(__dirname, 'public')));

//handle sessions
  app.use(session({
    secret: 'secret',
    saveUninitialized: true,
    resave: true
  }));


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

//***Place express validator before the routing else it won't validate***

//express 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
         };
      }
  }));

//express message
  app.use(require('connect-flash')());
  app.use(function (req, res, next){
    res.locals.messages = require('express-messages')(req, res);
    next();
  });


//routing
  app.use('/', indexRouter);
  app.use('/users', usersRouter);


// catch 404 and forward to error handler
  app.use(function(req, res, next) {
    next(createError(404));
  });

// error handler
  app.use(function(err, req, res, next) {
  // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
   res.status(err.status || 500);
   res.render('error');
  });

   module.exports = app;

   **my user.js** for model  


  var mongoose = require('mongoose'); //require mongoose

  mongoose.Promise = global.Promise;

  mongoose.connect('mongodb://localhost/nodeauth', {useNewUrlParser: true}); //connect mongoose to database

  var db = mongoose.connection; //store db connection in a variable

  var bcrypt =require('bcryptjs');

//create user schema
  var userSchema = mongoose.Schema({
     username: {
        type: String,
        createIndex: true
     },
     password: {
        type: String
     },
     email: {
        type: String
     },
     name: {
        type: String
     },
     profileimage: {
        type: String
     }
  });


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

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

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

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


  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);
          });
      });

  } 

0 个答案:

没有答案