req.isAuthenticated()始终为false,PassportJs + nodeJS + dynamoDb

时间:2017-03-16 05:54:32

标签: javascript node.js express amazon-dynamodb

我是网络编程的新手,我必须为我的学校开发类似Instagram的版本。我们在ReactJS中有前端,现在我们必须在nodeJS中开发服务器,使用护照用于日志,使用dynamoDb用于所有数据库(它将部署在亚马逊服务上)。

我现在使用Passport遇到问题,当我打电话给req.isAuthenticated()时,它总是返回false,我真的不知道为什么。 这是我的代码: 的 Index.js

const express       = require('express');
const session       = require('express-session');
const cookieParser  = require('cookie-parser');
const flash         = require('connect-flash');
const passport      = require('passport');
...
const app = express();
...
app.use(cookieParser());

require('./common/passport')(passport);

app.use(session({
    cookie : {
    maxAge: 3600000, // see below
    secure: false
},
secret: 'khugugjh',
resave: true,
saveUninitialized: true
})); // session secret

app.use(passport.initialize());
app.use(passport.session()); // persistent login      
...
require('./controllers/sample-controller')(app, passport);
const port = process.env.PORT || 3000;
app.listen(port);

passport.js

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

// used to deserialize the user
passport.deserializeUser(function(email, done) {
  docClient.getItem({"TableName":tableName,"Key": {"email":{"S":email}}}, function(err,data){
if (err)
    done(err,data);
else
    done(err,data.Item)
 })
});

...

passport.use('local-login', new LocalStrategy({
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true
},
function(req, email, password, done) { 
email = req.body.email;
password = req.body.password;
var params = {
        TableName: tableName,
        Key:{
            "email": email
        }
    };
    docClient.get(params, function(err,data){
    if (err){
        return done(err);
    }
    if (isEmpty(data)){
        return done(null, false, "KO"); // req.flash is the way to set flashdata using connect-flash
    }
    if (password != data.Item.password){
        return done(null, false, "KO"); // create the loginMessage and save it to session as flashdata
    }else{
        return done(null, {email: data.Item.email});
    }
});
}));

最后: 的样品controller.js

...  
app.post('/login', passport.authenticate('local-login'), (req, res) => {

    res.send("OK");
});
...
   app.get('/profile', isLoggedIn, (req, res) => {

    console.log("AUTHENTIFIE !");
});

function isLoggedIn(req, res, next) {

    console.log(req.sessionStore.sessions);
    if (req.isAuthenticated())
        return next();
    console.log("UNAUTHORIZED");
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

由于您未经过身份验证,因此您没有数据库的连接实例,使用带有dynamodb的here

护照时,本地策略会有一个片段