无法使用Passport.js和Express 4访问req.user

时间:2022-01-10 23:57:22

I've been creating an app with Passport, Express 4 and Jade. I would like to show the user a navbar that changes when they log in.

我一直在用Passport,Express 4和Jade创建一个应用程序。我想向用户显示一个在登录时更改的导航栏。

However, I cannot access req.user for any other page than the profile page, which calls isLoggedIn:

但是,我无法访问req.user以查找除调用isLoggedIn的配置文件页面之外的任何其他页面:

function isLoggedIn(req, res, next) {
    // if user is authenticated in the session, carry on
    if (req.isAuthenticated())
        return next()

    // if they aren't redirect them to the home page
    res.redirect("/login")
}

Using any other function to not redirect the user when not logged in results in req.user being undefined. I get the user like this:

使用任何其他功能在未登录时不重定向用户会导致req.user未定义。我得到这样的用户:

router.get("/profile", isLoggedIn, function(req, res) {
    res.render("profile", {
    title: 'Gebruikersprofiel van ' + req.user.firstname + " " + req.user.lastname,
    user: req.user // get the user out of session and pass to template
    })
})

And without the call to isLoggedIn (this doesn't work):

并且没有调用isLoggedIn(这不起作用):

router.get("/", function(req, res) {
    // serve index.html
    res.render("index", {
        title: 'Home',
        user: req.user,
        message: req.flash("message") 
    })
})

isLoggedIn is outside module.exports = function(passport) { /* all routes */ }, the rest is (of course) in it.

isLoggedIn在module.exports = function(passport){/ *所有路由* /}之外,其余的(当然)在其中。

Setup of the app is as follows:

该应用程序的设置如下:

var express = require("express"),
    bodyParser = require("body-parser"),
    mongodb = require("mongodb"),
    mongoose = require("mongoose"),
    uriUtil = require("mongodb-uri"),
    morgan = require("morgan"),
    cookieParser = require("cookie-parser"),
    session = require("express-session"),
    passport = require("passport"),
    flash = require("connect-flash"),
    ip = "okay",
    port = process.env.PORT || 80

require("./includes/passport")(passport)
require("./includes/subject")
require("./includes/user")

var app = new express()
app.disable("x-powered-by")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
    extended: true
}))

app.use(morgan("dev")); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)

// required for passport
app.use(session({ secret: "yep" })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session


app.set("view engine", "jade")
app.use(express.static(__dirname + "/views"))

/**
 * CORS support.
 */
//skipped

//Database setup skipped

/**
 * App setup
 */
// make our db accessible to our router - globals
app.use(function(req, res, next) {
    req.db = db
    next()
})

var api = require("./routes/api")(passport),
    web = require("./routes/web")(passport)

// /api for api routes and / for web routes
app.use("/api", api)
app.use("/", web)

//Error handling skipped

// fire in the hole!
app.listen(port, ip, function() {
    console.log("Listening on port " + port)
})

I have tried various things, including adding middleware in app.js to add the user to res.locals.user, but none have worked for me, so far.

我尝试了各种各样的东西,包括在app.js中添加中间件以将用户添加到res.locals.user,但到目前为止,没有一个对我有用。

What am I doing wrong?

我究竟做错了什么?

Edit: I've not seen many people mention it, but would StormPath maybe be a better solution?

编辑:我没有看到很多人提到它,但StormPath可能是一个更好的解决方案吗?

Edit 2: I am using Stormpath for now, but would still happily take suggestion on how to solve this, if anyone has any.

编辑2:我现在正在使用Stormpath,但如果有人有任何建议,我仍然会很乐意接受如何解决这个问题的建议。

Edit 3: I have gotten a number of requests to see the (de)serializeUser functions. They are as follows:

编辑3:我收到了许多要求查看(de)serializeUser函数的请求。它们如下:

// used to serialize the user for the session
passport.serializeUser(function(user, done) {
    done(null, user._id);
});

// used to deserialize the user
passport.deserializeUser(function(id, done) {
    User.findById(id, function(err, user) {
        done(err, user);
    });
});

1 个解决方案

#1


0  

I have solved the issue. It was in the way I linked the pages of my site, which made it start a new session from the profile page onto the rest of the site.

我已经解决了这个问题。这是我链接我的网站页面的方式,这使得它从个人资料页面开始新的会话到网站的其余部分。

The answer can be found here: https://*.com/a/27314240/1218007

答案可以在这里找到:https://*.com/a/27314240/1218007

#1


0  

I have solved the issue. It was in the way I linked the pages of my site, which made it start a new session from the profile page onto the rest of the site.

我已经解决了这个问题。这是我链接我的网站页面的方式,这使得它从个人资料页面开始新的会话到网站的其余部分。

The answer can be found here: https://*.com/a/27314240/1218007

答案可以在这里找到:https://*.com/a/27314240/1218007