我有以下Express.js文件
var express = require('express');
var favicon = require('serve-favicon');
var morgan = require('morgan');
var compression = require('compression');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var cookieParser = require('cookie-parser');
var errorHandler = require('errorhandler');
var path = require('path');
var config = require('./environment');
var passport = require('passport');
module.exports = function(app) {
var env = app.get('env');
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.use(compression());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(methodOverride());
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session()); // passport session middleware
if ('production' === env) {
app.use(favicon(path.join(config.root, 'public', 'favicon.ico')));
app.use(express.static(path.join(config.root, 'public')));
app.set('appPath', config.root + '/public');
app.use(morgan('dev'));
}
if ('development' === env || 'test' === env) {
app.use(require('connect-livereload')());
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(path.join(config.root, 'client')));
app.set('appPath', 'client');
app.use(morgan('dev'));
app.use(errorHandler()); // Error handler - has to be last
}
};
用户使用Facebook登录后,在我尝试操作时在我的控制器中
req.user
或req.session.passport.user
获得undefined
。
如何获取当前登录用户?
答案 0 :(得分:1)
验证成功后 req.user 会自动设置为用户
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
mongoose = require("mongoose"),
passport = require("passport"),
flash = require("connect-flash"),
localStrategy = require("passport-local"),
User = require("./models/user"),
passportLocalMongoose = require("passport-local-mongoose")
app.use(require("express-session")({
secret: "demoapp",
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
app.use(bodyParser.urlencoded({extended: true}));
app.set("view engine", "ejs")
app.use(express.static(__dirname + "/public"));
app.use(express.static(__dirname + "/dashboard"));
获取当前用户详细信息。您可以将currentUser设置为您自己的 文字
app.use(function(req,res,next){
res.locals.currentUser = req.user;
next();
})
如果您使用的是ejs,请在浏览器中显示用户个人资料
<p> <%= currentUser.username %> </p>
<p> <%= currentUser.country %> </p>
答案 1 :(得分:0)
您需要定义身份验证策略并调用passport.authenticate来验证您的用户身份。 请参阅the passport guide
中的示例