我正在使用快递和护照登录用户,在我的一个控制器中,我想访问当前登录的用户,但我对如何访问它们感到困惑。 req.user似乎不存在
答案 0 :(得分:0)
每次用户每次请求时都必须进行身份验证,并使用策略设置req.user。我使用带有令牌的策略。
令牌在标头中发送。 而不是令牌可能是cookie或其他策略。
以下不完整的代码,但您可以提供帮助:
var bodyParser = require('body-parser');
var express = require('express');
var jwt = require('jsonwebtoken');
var LocalStrategy = require('passport-local').Strategy;
var BearerStrategy = require('passport-http-bearer').Strategy;
var app = express();
app.use(bodyParser.json());
//Local Strategy to login user with email and password
passport.use(new LocalStrategy({
usernameField: 'email',
passwordField: 'password'
},
function(email, password, done) {
usersRepository
.getUserByEmail(email)
.then(function(user) {
if (!!user && passwordHelper.verify(password, user.password, user.salt)) {
done(null, user);
} else {
done(null, false);
}
});
}));
//Bearer Strategy to auth user with token - run with every request
passport.use(new BearerStrategy(function(token, done) {
jwt.verify(token, 'secret', function(err, decoded) {
if (!err && decoded) {
done(null, decoded); // !!! here is set req.user - decode is my user from token
} else {
done(null, false);
}
});
}));
app.use(passport.initialize());
var bearerAuth = passport.authenticate('bearer', {
session: false
});
bearerAuth.unless = require('express-unless');
//Adding Bearer Strategy to all routing unless login
app.use(bearerAuth.unless({
path: [
'/login'
]
}));
passport.serializeUser(function(user, done) {
done(null, user);
});
passport.deserializeUser(function(user, done) {
done(null, user);
});
//Login - use Local Strategy
app.post('/login', passport.authenticate('local'), function(req, res) {
var accessToken = jwt.sign(req.user, 'secret', {
expiresIn: '7d'
});
res.send({
id: req.user.id,
accessToken: accessToken,
email: req.user.email,
isAdmin: req.user.is_admin
});
});