护照会话无效

时间:2018-04-29 13:10:09

标签: node.js express passport.js

我正在尝试使用快递和护照建立登录系统。

据我所知,我可以使用req.user访问用户ID并正确存储他们的操作,如果Passport工作正常,则req.isAuthenticated()将为true,但它不起作用。< / p>

出于某种原因,req.user始终未定义,req.isAuthenticated()始终为false。

这是我的 app.js - &gt;

const express = require('express');
const http = require('http');
const session = require('express-session');
const bodyParser = require('body-parser');

const passport = require('passport');

const route = require('./controllers/core');          **// CORE.JS**

const app = express();

app.set('view engine', 'ejs');

app.use('/css', express.static('css'));
app.use('/js', express.static('js'));
app.use('/themify', express.static('themify'));

app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: false
    //cookie: { secure: true }
}));

app.use(bodyParser.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(passport.session());

app.use(route);

//core(app);

app.listen(3000);

这是我的 core.js

const router = require('express').Router();

const passport = require('passport');
const bodyParser = require('body-parser');
const mysql      = require('mysql');
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'pharmate',
    dateStrings: 'date'
});


const urlencodedParser = bodyParser.urlencoded({ extended: false });

router.get('/index', function(req,res){
    console.log(req.user);
});

router.post('/index', urlencodedParser, function(req,res){

    var email = req.body.email;
    var pass = req.body.password;
    connection.query("SELECT `Pharmacy_ID`, `Email`, `Password` FROM `pharmacy` WHERE Email = ? AND Password = ?", [email, pass], function (error, results, fields) {
        if (error) res.send(error);//throw error;
        else{
            if(results.length>0){

                req.login(results[0], function(err){
                    res.redirect('index');
                });
            }
            else{
                res.redirect('login');
            }
        }
    });

});


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

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

module.exports = router;

任何帮助将不胜感激。提前谢谢。

1 个答案:

答案 0 :(得分:0)

您应该处理以下身份验证:

app.post('/login',
  passport.authenticate('local', {
    successRedirect: '/secret',
    failureRedirect: '/login',
  })
);

您是否设置了护照本地策略?