护照要求用户未在请求中持久存在-

时间:2018-11-29 04:20:48

标签: node.js express passport.js

使用password.js本地策略,我试图使用req.user获取当前用户ID,以便可以将配方和用户ID存储在数据库中。问题似乎出在我应用程序的配置文件中的passport.js文件的反序列​​化部分附近。每当我出于某种原因点击/ api / saveRecipe路由时,它都会反序列化,然后req用户将不再可用。

注意:我正在使用前端的react在后端服务器上进行身份验证。

下面是我的server.js文件

问题:调用护照.authenticate('local')后,req.user可用,但是一旦api / saveRecipe路由被点击,req.user将不再可用。

在S.O.上研究了此主题之后看来,这通常与服务器文件设置中的顺序有关,但我已经查看并查看了,我相信我的设置正确...

const express = require("express");
const bodyParser = require("body-parser");
const session = require("express-session");
const routes = require("./routes");

// Requiring passport as we've configured it
let passport = require("./config/passport");

const sequelize = require("sequelize");

// const routes = require("./routes");
const app = express();
var db = require("./models");
const PORT = process.env.PORT || 3001;

// Define middleware here
app.use(express.urlencoded({ extended: true }));
app.use(express.json());

// passport stuff
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(express.static("public"));

// We need to use sessions to keep track of our user's login status
// app.use(cookieParser('cookit'));
app.use(
  session({ 
    secret: "cookit", 
    name: "cookit_Cookie"
   })
);
app.use(passport.initialize());
app.use(passport.session());

// Serve up static assets (usually on heroku)
if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/public"));
}

// the view files are JavaScript files, hence the extension
app.set('view engine', 'js');

// the directory containing the view files
app.set('pages', './');

// Add routes, both API and view
app.use(routes);

// Syncing our database and logging a message to the user upon success
db.connection.sync().then(function() {
  console.log("\nDB connected\n")
  // Start the API server
  app.listen(PORT, function() {
    console.log(`  ==> API Server now listening on PORT ${PORT}!`);
  });
});
module.exports = app;

我的password.js代码

//we import passport packages required for authentication
var passport = require("passport");
var LocalStrategy = require("passport-local").Strategy;
//
//We will need the models folder to check passport against
var db = require("../models");

// Telling passport we want to use a Local Strategy. In other words, we want login with a username/email and password
passport.use(
  new LocalStrategy(
    // Our user will sign in using an email, rather than a "username"
    {
      usernameField: "email",
      passwordField: "password",
      passReqToCallback: true
    },
    function(req, username, password, done) {
      // console.log(`loggin in with email: ${username} \n and password: ${password}`)
      // When a user tries to sign in this code runs
      db.User.findOne({
        where: {
          email: username
        }
      }).then(function(dbUser) {
        // console.log(dbUser)
        // If there's no user with the given email
        if (!dbUser) {
          return done(null, false, {
            message: "Incorrect email."
          });
        }
        // If there is a user with the given email, but the password the user gives us is incorrect
        else if (!dbUser.validPassword(password)) {
          return done(null, false, {
            message: "Incorrect password."
          });
        }
        // If none of the above, return the user
        return done(null, dbUser);
      });
    }
  )
);

// serialize determines what to store in the session data so we are storing email, ID and firstName
passport.serializeUser(function(user, done) {
  console.log(`\n\n        serializing ${user.id}\n`)
  done(null, user.id);
});

passport.deserializeUser(function(id, done) {
  console.log(`\n\n        DEserializing ${id}\n`)
  db.User.findOne({where: {id:id}}, function(err, user) {
    done(err, user);
  });
});
// Exporting our configured passport
module.exports = passport;

const router = require("express").Router();
const controller = require("../../controllers/controller.js");
const passport = require("../../config/passport");

router.post(
  "/login",
  passport.authenticate("local", { failureRedirect: "/login" }),
  function(req, res) {
    console.log(`req body -${req.body}`);
    res.json({
      message: "user authenticated",
    });
  }
);


router.post("/saveRecipe", (req, res) => {
  console.log(req.user)
  if (req.isAuthenticated()) {
    controller.saveRecipe;
  } else {
    res.json({ message: "user not signed in" });
  }
});

module.exports = router;

1 个答案:

答案 0 :(得分:0)

问题出在您的router.post('login')中。尝试将其更改为以下内容:

  app.post('/login', passport.authenticate('local-login', {
    successRedirect: '/profile',
    failureRedirect: '/login/failed'})
  )

这将在您的下一个请求中正确设置req.user!