问题
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.
However, I cannot access req.user for any other page than the profile page, which calls 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:
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):
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.
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.
What am I doing wrong?
Edit: I've not seen many people mention it, but would StormPath maybe be a better solution?
Edit 2: I am using Stormpath for now, but would still happily take suggestion on how to solve this, if anyone has any.
Edit 3: I have gotten a number of requests to see the (de)serializeUser functions. They are as follows:
// 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:
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://stackoverflow.com/a/27314240/1218007
来源:https://stackoverflow.com/questions/27216731/unable-to-access-req-user-with-passport-js-and-express-4