【发布时间】:2017-03-27 10:00:28
【问题描述】:
我在 mongoose 模式文档中使用护照 js 进行用户凭证管理:
var customerSchema = new Schema({
info: {
firstname: String,
lastname: String,
telephone: String,
fax: String
},
local: {
email: {
type: String
},
password: {
type: String
}
},
facebook: {
id: String,
token: String,
email: String,
name: String,
photo: String
},
google: {
id: String,
token: String,
email: String,
name: String,
photo: String
},
status: String
}, {
timestamps: true
});
使用passportjs登录并添加提供者名称时:
passport.use('local.login', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, function(req, email, password, done) {
req.checkBody('email', 'Email address invalid.').notEmpty().isEmail();
req.checkBody('password', 'Password invalid.').notEmpty();
var errors = req.validationErrors();
if (errors) {
var messages = [];
errors.forEach(function(error) {
messages.push(error.msg);
});
return done(null, false, req.flash('error', messages));
}
//find user
Customer.findOne({
'local.email': email
}, function(err, customer) {
if (err) {
return done(err);
}
if (!customer) {
return done(null, false, {
message: 'Customer not found.'
});
}
if (!customer.validPassword(password)) {
return done(null, false, {
message: 'Customer info invalid.'
});
}
customer.provider = "local"; //Add more var to customer info
console.log("User Info: " + customer.provider);
return done(null, customer);
});
}));
passport.serializeUser(function(user, done) {
console.log("Serialize User: " + user);
done(null, user._id);
});
当通过本地护照或 Facebook 登录时,我想将自定义字段添加到护照会话返回提供者信息传递到模板。
那么我如何在 Passport 中做到这一点?
更新 1:
定义变量:
var provider = null;
在:
...
if (!customer.validPassword(password)) {
return done(null, false, {
message: 'Customer info invalid.'
});
}
provider = "local"; //Add more var to customer info
return done(null, customer);
...
我使用了@Love-Kesh 帮助代码:
passport.deserializeUser(function(customerId, done) {
Customer.findById(customerId, function(err, user) {
var newUser = user.toObject();
newUser['provider'] = provider;
done(err, newUser);
});
});
这对我来说很正常。提供者通过本地方法返回动态值,facebook ...
【问题讨论】:
标签: node.js mongodb passport.js mongoose-schema