req.user是未定义节点+快递+护照+猫鼬

时间:2018-07-18 05:01:10

标签: javascript node.js express passport.js

当我使用

INSERT INTO grades
(firstname, subject, date, grade) -- Assuming the ID is a serial
(SELECT firstname, subject, CURRENT_DATE, :grade
 FROM   (SELECT firstname,
                subject, 
                LAST_VALUE(grade) OVER (PARTITION BY firstname ORDER BY date DESC)
                  AS last_grade
         FROM   grades) g
 WHERE  firstname = :name AND subject= :subject AND :grade <> last_grade)

我有消息

console.log(req.session);

但使用

Session {cookie:{ path: '/',_expires: null,originalMaxAge: null,httpOnly:true },passport: { user: 5b427a2d117d7c3f6087db8a } }

给我console.log(req.user);

undefined

授权方法:

const express = require('express');
const passport = require('passport');
const session = require('express-session');
const bodyParser = require('body-parser');
const cors = require('cors');
const morgan = require('morgan');
const jwt = require('jsonwebtoken');
var mongoose = require('mongoose');
var MongoStore = require('connect-mongo')(session);

mongoose.connect('mongodb://localhost:27017/posts');
var db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error"));
db.once("open", function(callback){
    console.log("Connection Succeeded");
});

var User = require("../models/user");
var Post = require("../models/post");
var Girl = require("../models/girl");
//load passport strategies

require('../config/passport/passport.js')(passport);

const app = express();
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(cors());

// For Passport
app.use(session({
    secret: 'keyboard cat',
    resave: true,
    saveUninitialized: true,
    store: new MongoStore({
        mongooseConnection: db
    })
}));


app.use(passport.initialize());
app.use(passport.session());

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

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

尝试吸引用户的方法

 app.post('/signin', function(req, res) {
    User.findOne({
       username: req.body.username
    }, function(err, user) {
      if (err) throw err;

      if (!user) {
        res.status(401).send({success: false, msg: 'Authentication failed. User not found.'});
      } else {
        // check if password matches
        user.comparePassword(req.body.password, function (err, isMatch) {
          if (isMatch && !err) {
              // if user is found and password is right create a token
              var token = jwt.sign(user.toJSON(), 'nodeauthsecret');
              res.json({success: true, token: 'JWT ' + token});
          } else {
              res.status(401).send({success: false, msg: 'Authentication failed. Wrong password.'});
          }
       });
    }
});

请帮助。我如何理解保存在会话中的用户,但我不知道如何接纳他

4 个答案:

答案 0 :(得分:0)

您定义了护照会议吗?

app.use(passport.initialize());
app.use(passport.session());

答案 1 :(得分:0)

编辑:

在mongo会话之前进行passport.initialize和password.session

您的代码应如下所示

require('../config/passport/passport.js')(passport);

const app = express();
app.use(morgan('combined'));
app.use(bodyParser.json());
app.use(cors());

// For Passport
app.use(passport.initialize());
app.use(passport.session());


// Replacing your app.use(passport.session()); with the one you've written 
//      with all other options

app.use(session({
    secret: 'keyboard cat',
    resave: true,
    saveUninitialized: true,
    store: new MongoStore({
        mongooseConnection: db
    })
}));


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

passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

当前您正在写两次app.use(passport.session())

答案 2 :(得分:0)

我所需要的只是添加

app.post('/add_girl', passport.authenticate('jwt', { session: true}),(req, res) => {

答案 3 :(得分:0)

  1. 如果使用的是低版本Express会话(

    var express = require('express');
    var cookieParser = require('cookie-parser');
    var session = require('express-session');
    var app = express();
    app.use(cookieParser()) // before use session middleware
    app.use(session({secret: 'your secret'}));
    
  2. 中间件的订购可能是个问题。

  3. 如果使用的是HTTP连接,则必须删除以下安全选项。

     app.use(session({
       secret: 'your secret',
       resave: false,
       saveUninitialized: true,
       // cookie: { secure: true } // remove this line if you are using a HTTP connection
    }))