我一直在使用Passport,Express 4和Jade创建应用。我想向用户显示一个导航栏,这些导航栏在登录时会发生变化。
但是,除了调用isLoggedIn的个人资料页面之外,我无法访问req.user:
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")
}
使用任何其他功能在未登录时不重定向用户会导致req.user为undefined
。我得到这样的用户:
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
})
})
没有调用isLoggedIn(这不起作用):
router.get("/", function(req, res) {
// serve index.html
res.render("index", {
title: 'Home',
user: req.user,
message: req.flash("message")
})
})
isLoggedIn
在module.exports = function(passport) { /* all routes */ }
之外,其余的(当然)在其中。
应用程序的设置如下:
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)
})
我尝试了各种各样的东西,包括在app.js中添加中间件以将用户添加到res.locals.user,但到目前为止,没有一个对我有效。
我做错了什么?
编辑:我没见过很多人提到它,但StormPath可能是更好的解决方案吗?
编辑2 :我现在正在使用Stormpath,但如果有人有任何建议,我仍然会很乐意接受如何解决这个问题的建议。
编辑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);
});
});
答案 0 :(得分:0)
我已经解决了这个问题。这是我链接我的网站页面的方式,这使得它从个人资料页面开始新的会话到网站的其余部分。
答案可以在这里找到: https://stackoverflow.com/a/27314240/1218007