[英]Passport.js strategy with no field required
I'm surprised that it's so hard to find, or maybe something wrong with me. 我很惊讶它很难找到,或者说我可能有些不对劲。
I need a passport.js
strategy
that requires no fields - to run authentication with it on simple user GET
request to '/'
and manipulate user session data to, for example, make a new 'guest' user. 我需要一个不需要字段的passport.js
strategy
- 在简单的用户GET
请求上运行身份验证到'/'
并操纵用户会话数据,例如,创建一个新的'guest'用户。
Maybe i can do this via passport local-strategy
? 也许我可以通过护照local-strategy
来做到这一点? Or am i need to create a custom one? 或者我需要创建一个自定义的?
I saw this Configure Passport to accept request without body? 我看到这个配置Passport接受没有正文的请求? question, yet i just simply can't figure out how the suggested in answer wrapping will change anything. 问题,但我只是无法弄清楚答案包装中的建议将如何改变任何东西。
Edit: here's what I'm trying to achieve 编辑:这是我想要实现的目标
passport.use('guest', new LocalStrategy({
passReqToCallback: true
},
function (req, NOusername, NOpassword, done) {
////NO PASSWORD OR USERNAME checks here, just deciding what kind of temporary user needs to be created///
if (req.session.passport) {
///create new user with previous session data
done(null,user)
}
else {
///create clean user
done(null, user)
})
)
and then in routes.js
然后在routes.js
app.get('/', passport.authenticate('guest'), function (req, res) {
res.render('PeerRoom.ejs', req.user);
});
Edit: Another approach could be using req.logIn
and skip dealing with the strategies altogether 编辑:另一种方法可能是使用req.logIn
并完全跳过处理策略
app.get('/', yourCustomGuestAuthenticationMiddleware, function (req, res) {
res.render('PeerRoom.ejs', req.user);
});
function yourCustomGuestAuthenticationMiddleware(req, res, next){
// No need to do anything if a user already exists.
if(req.user) return next();
// Create a new user and login with that
var user = new User({name: 'guest'+Math.random().toString() });
user.save();
req.logIn(user, next);
}
To make a new guest user, simply do it instead of rejecting an authentication 要创建新的访客用户,只需执行此操作而不是拒绝身份验证
Here's a modified example from the docs 这是文档中的修改示例
var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
passport.use(new LocalStrategy(
function(username, password, done) {
User.findOne({ username: username }, function(err, user) {
if (err) return done(err);
if (!user) {
/* HERE, INSTEAD OF REJECTING THE AUTHENTICATION */
// return done(null, false, { message: 'Incorrect username.' });
/* SIMPLY CREATE A NEW USER */
var user = new User({ name: 'guest'+Math.random().toString() });
user.save();
/* AND AUTHENTICATE WITH THAT */
return done(null, user);
}
if (!user.validPassword(password)) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
});
}
));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.