如何验证使用pssport

时间:2016-08-02 02:51:55

标签: node.js

代码错误,无法运行真实结果。我发布了真实username和真password,但重定向/login,我不明白为什么是错的,请看我编写的代码跟passport.org如何使用护照。

我的代码:

var express=require("express");
var cookieParser=require("cookie-parser");
var session=require("express-session");
var passport=require("passport");
var LocalStrategy=require("passport-local").Strategy;
var util=require("util");
var url=require("url");
var querystring=require("querystring");
var flash=require("connect-flash");


var app=new express();
app.use(flash());
app.use(cookieParser());
app.use(session({ secret: 'keyboard cat' }));
app.use(passport.initialize());
 app.use(passport.session());
app.get("/hello$",function(req,res){
 res.send("Hello World");
});

passport.use(new LocalStrategy(
  function (username, password, done) {
    console.log('haha');
    var user = {
        id: '1',
        u: 'u',
        p: 'p'
    };

     if (username !== user.u) {
        return done(null, false, { message: 'Incorrect username.' });
    }
    if (password !== user.p) {
        return done(null, false, { message: 'Incorrect password.' });
    }
    return done(null, user);
    }
     ));
    app.post('/login',function(req,res,next){
    var post="";
    req.on("data",function(chunk){
        post+=chunk;
    });
    req.on("end",function (){
        console.log(util.inspect(querystring.parse(post)));
        next();
    })
   },
  passport.authenticate('local', { successRedirect: '/hhhh',
    failureRedirect: '/login',
    failureFlash: true })
  );

 app.get('/logout', function (req, res) {
   req.logout();
   res.redirect('/');
  });

  app.get('/users', isLoggedIn,function (req,res){
     res.send("authenticate is ok");
   });

  var server=app.listen(9000,function (){
       console.log("the web is start");
   });

    function isLoggedIn(req, res, next) {
       if (req.isAuthenticated())
       return next();
       res.redirect('/');
       }

谢谢大家!

0 个答案:

没有答案