Node js中的护照模块问题

时间:2017-09-24 07:46:48

标签: node.js mongodb express passport.js

我正在尝试在使用mongodb的Node js登录系统中使用护照。 我在app.js文件中包含了护照模块和本地策略。

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var expressValidator=require('express-validator');
var cookieParser = require('cookie-parser');

var session= require("express-session");
var passport=require("passport");
var LocalStrategy=require('passport-local').Strategy;
var bodyParser = require('body-parser');
var multer=require("multer");
var flash=require('connect-flash');
var mongo=require('mongodb');
var mongoose=require('mongoose');
var db=mongoose.connection;

在用户路由文件中,我已声明用户

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

var User=require('../models/users');
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.get('/register', function(req, res, next) {
    res.render('register',{
      "title":'Register'
    });

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

});
router.post('/register', function(req, res, next){
    //get the form values
    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;


//Check for image filed
if(req.files&&req.files.profileimage){
    console.log('Uploading file....');
    //File Info
    var profileimageoriginalname =req.files.profileimage.originalname;
    var profileimagename=req.files.profileimage.name;
    var profileimageMime=req.files.profileimage.mimetype;
    var profileimagePath=req.files.profileimage.path;
    var profileimageExt=req.files.profileimage.extension;
    var profileimageSize=req.files.profileimage.size;

}else{
    //Set a default image
    var profileimageName="noimage.png";

}
//Form Validation
req.checkBody('name',"nAME FILED IS REquiered").notEmpty();
req.checkBody('email',"email FILED IS REquiered").isEmail();

req.checkBody('username',"UsernamenAME FILED IS REquiered").notEmpty();
req.checkBody('password',"password FILED IS REquiered").notEmpty();
req.checkBody('password2',"password font marchjFILED IS REquiered").equals(req.body.password);
//Check for errors
    var errors = req.validationErrors();
    if(errors){
        res.render('register',{
            errors:errors,
            name:name,
            email:email,
            username:username,
            password:password,
            password2:password2
        });

    }else{
        var newUser=new User({
            name:name,
            email:email,
            username:username,
            password:password,
            profileimage:profileimagename


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

        });
        //Sucess message
        req.flash('success',"You are now registered and may login");
        res.location('/');
        res.redirect('/');
    }

});
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){
      console.log("Unknown 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{
          console.log("invalid password");
          return done(null,false,{message:"invalid passwors"});
      }
  });

});
}
));

router.post('/login',passport.authenticate('local',{failureRedirect:"/users/login/",failureFlash:"Wrong login or pass"}),function(req,res){
console.log("Authentication Successfully done");
req.flash('success',"You are loged in");
res.redirect('/');
});
module.exports = router;

我也为我的用户登录创建了一个模块

var mongoose=require('mongoose');
var bcrypt=require('bcrypt');
mongoose.connect('mongodb://localhost/nodeAuth', { useMongoClient: true });
var db=mongoose.connection;

//User scheme
var UserSchema=mongoose.Schema({
    usernam:{
        type:String,
        index:true
    },
    password:{
        type:String,required:true,bcrypt:true
    },
    email:{
        type:String
    },
    name:{
        type:String
    },
    profileimage:{
        type:String
    }


});
var User=module.exports=mongoose.model('User',UserSchema);
module.exports.comparePassword=function(candidatePassword,hash,callback){
    bcrypt.compare(candidatePassword,hash,function(err,isMatch){
        if(err) return callback(err);
        callback(null,isMatch);
    });
}

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.createUser=function(newUser,callback){
    bcrypt.hash(newUser.password, 10,function(err,hash){
if(err)throw err;
//Set hashed password
        newUser.password=hash;
        //create User
        newUser.save(callback)
    });

}

但它的回归毫无意义。 COuld有人帮忙吗? 我认为它主要与护照模块连接,但我也绝对没有错误,我可以调试。 我mongodb它显示了我的整个数据库。我正在尝试使用我以前在我的数据库中注册的登录名登录并且工作正常,但它没有返回任何内容。它只是重新拍摄页。

1 个答案:

答案 0 :(得分:0)

查看您的架构:

//User scheme
var UserSchema=mongoose.Schema({
    usernam:{
        type:String,
        index:true
    },
...

它应该是" usernamE" :)