我正在使用MEAN Stack和猫鼬。使用护照进行身份验证我想获取当前登录的用户并显示他的详细信息。例如,如果我已登录,并且如果我转到配置文件页面,我想获取我的详细信息。互联网上的资源很少。
Login.js(护照和路线在这里)
var express = require('express');
var router = express.Router();
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var User = require('../models/user');
var ConnectRoles = require('connect-roles');
router.get('/', function(req, res, next) {
res.render('Login', { title: 'Login' });
});
passport.serializeUser(function(user, done) {
done(null, user._id);
});
passport.deserializeUser(function(id, done) {
User.findById(id, function(err, user) {
done(err, user);
});
});
passport.use("/", new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false,
{ message: "No user has that username!" });
}
user.checkPassword(password, function(err, isMatch) {
if (err) { return done(err); }
if (isMatch) {
return done(null, user);
} else {
return done(null, false,
{ message: "Invalid password." });
}
});
});
}));
router.use(function(req, res, next) {
res.locals.currentUser = req.user;
res.locals.errors = req.flash("error");
res.locals.infos = req.flash("info");
next();
});
router.post("/", passport.authenticate("/", {
successRedirect: "/SubmitSurvey",
failureRedirect: "/",
session: false,
failureFlash: true
}));
router.get("/AdminDatabase", function(req, res) {
res.render('AdminDatabase', { title: 'AdminDatabase' });
});
router.get('/CreateSurvey', function(req, res, next) {
res.render('CreateSurvey', { title: 'CreateSurvey' });
});
router.get('/SubmitSurvey', function(req, res, next) {
res.render('SubmitSurvey', { title: 'SubmitSurvey' });
});
router.get('/profile', function(req, res, next) {
res.render('profile', { title: 'profile' });
});
router.get("/Logout", function(req, res) {
req.logout();
res.redirect("/");
});
module.exports = router;
我如何在nodejs
中执行此操作答案 0 :(得分:3)
它位于req.user
对象
router.get('/profile', function(req, res, next) {
//here it is
var user = req.user;
//you probably also want to pass this to your view
res.render('profile', { title: 'profile', user: user });
});
答案 1 :(得分:2)
通行证通过中间件管道向当前用户填充req.user
对象,以便您可以从那里提取。
答案 2 :(得分:2)
正如Alex所说,你可以在调用req.user
时明确传递一些变量(例如你的res.render
):
router.get('/profile', function(req, res, next) {
res.render('profile', { title: 'profile', user: req.user });
});
相反,您可能希望在对req.user
的所有调用中访问某些变量(例如res.render
),而无需每次都指定它们?在这种情况下,您可以使用res.locals
,例如通过添加此中间件:
app.use(function(req, res, next){
res.locals.user = req.user;
next();
});
最后,为了完整性 - 在上述两种方法中,变量user
在视图中可用。例如,如果您使用的是pug模板,那么现在可以执行以下操作:
if user
p Hello, #{user.id}, good to see you!
else
p Please log in...