当我在我的节点js + passport app中打开任何url时,我有2个数据库请求(可能是deserialze方法调用)。
我的日志:
NEW QUERY____________________
SELECT * FROM users WHERE id=$1
[ '1' ]
GET / 200 248ms - 829b
NEW QUERY____________________
SELECT * FROM users WHERE id=$1
[ '1' ]
GET /stylesheets/style.css 404 3ms
反序列化方法和中间件:
app.configure(function() {
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.cookieParser());
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(express.session({
secret: "thisismysecretkey",
store: new RedisStore({ host: 'localhost', port: 6379, client: redisClient })
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);
});
passport.serializeUser(function(user, done){
done(null, user.id);
});
passport.deserializeUser(function(id, done){
user.get(id, function(err, user){
done(err, user);
});
});
这似乎是issue,但它不适合我。
我使用护照js进行身份验证看起来有点害怕:
exports.authenticate = function (req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, fields) {
var userEmail = fields.email[0];
var userPassword = fields.password[0];
if (err) throw err;
userProvider.isBlockedEmail(userEmail, function(err, blocked) {
if (err) throw err;
if (blocked) {
res.send({error: true, description: 'you did too much attempts'});
} else {
userProvider.authenticate(userEmail, userPassword, function (err, user) {
if (err) throw err;
else if (user === undefined) res.send({error: true, description: 'wrong login or password'});
else if (user) {
req.login(user, function (err) {
if (err) throw err;
else if (user.banned === true) res.send({error: true, description: 'access denied'});
else {
userProvider.resetAttemptsCounter(userEmail, function(err) {
if (err) throw err;
res.send(req.user);
});
}
});
} else {
userProvider.checkAndBlock(userEmail, function(err, isBlocked, descriptions) {
if (err) throw err;
if (isBlocked) {
res.send({error: true, description: descriptions});
} else {
userProvider.increaseAttemptsCounter(userEmail, function(err) {
if (err) throw err;
res.send({error: true, description: 'wrong login or password'});
});
}
});
}
});
}
});
});
};
请帮我避免这种开销。
答案 0 :(得分:5)
我认为这是一个类似的问题:
app.use(passport.initialize());
app.use(passport.session());
app.use(express.favicon()); <---- !!
app.use(app.router);
这意味着将为/favicon.ico
的每个请求调用Passport中间件(这几乎适用于每个页面)。
您应该重新订购它,以便在 Passport中间件之前将express.favicon
称为:
app.use(express.favicon());
app.use(passport.initialize());
app.use(passport.session());
app.use(app.router);