2016-05-11 54 views
0

我在執行我的NodeJS應用程序上的本地護照時遇到了一些麻煩。我不明白我在這裏做錯了什麼。我將在這裏列出重要代碼這個問題。護照本地策略不會被調用NodeJS

app.js

var passport = require('passport'); 
var LocalStrategy = require('passport-local').Strategy; 
var bodyParser = require('body-parser'); 
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(bodyParser.json()); 
app.use(passport.initialize()); 
app.use(passport.session()); 

users.js

var express = require('express'); 
var router = express.Router(); 
var passport = require('passport'); 
var LocalStrategy = require('passport-local').Strategy; 
var User = require('../models/user.js'); 

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) { 
     console.log('Entered passport'); // This doesn't even happen 
     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); 
       } 
       console.log('Invalid Password'); 
       return done(null, false, { 
        message: 'Invalid Password' 
       }); 
      }); 
      return done(null, user); 
     }); 
    } 
)); 

router.post('/login', passport.authenticate('local', { 
    successRedirect: '/', 
    failureRedirect: '/users/login', 
    failureFlash: 'Invalid username or password' 
}), function(req, res) { 
    console.log("Authentication Successfull!"); 
    req.flash('success', 'You are logged in'); 
    res.redirect('/'); 
}); 

user.js的(模型):

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) return callback(err); 
     callback(null, isMatch); 
    }); 
} 

我沒有得到任何語法錯誤。在users.js中,我想將消息記錄到控制檯,但它甚至沒有到達那裏。當我剛剛在console.log中輸入函數時,登錄的post函數被激發,但現在看起來沒有。它只是重新加載頁面(看起來像)。任何幫助表示讚賞。

回答

0

嘗試裝入session中間件護照initilized前:

var session = require('express-session') 

app.use(session({ secret: 'xxxxxxx' })); 
app.use(passport.initialize()); 
app.use(passport.session()); 
+0

當我使用一個祕密,我得到一個消息,說是棄用 – Patrick2607

相關問題