Ibt*_*man 7 javascript api node.js passport-twitter passport-local
因为我可以req.user通过传入来获取任何路由中的登录用户:
passport.authenticate("jwt", { session: false })
Run Code Online (Sandbox Code Playgroud)
我想允许用户使用除本地登录之外的Twitter登录,因此我在node.js API中有一个passport-twitter策略.如何使用req.user访问本地登录用户?
module.exports = passport => {
passport.use(
new Strategy({
consumerKey: "",
consumerSecret: "",
callbackURL: "http://localhost:3000"
},
function(token, tokenSecret, profile, cb) {
Profile.findOne({
user: req.user._id
}).then(
userdetail => {
userdetail.twuser = profile._json.screen_name;
userdetail.token = token;
userdetail.tokenSecret = tokenSecret;
userdetail.save().then();
return cb(null, profile);
}
)
}
)
);
};
Run Code Online (Sandbox Code Playgroud)
小智 3
首先,我会检查您的系统中是否已经存在具有给定 Twitter 个人资料 ID 的用户。然后我会检查是否有具有相同电子邮件地址的用户。这意味着用户已经使用他的电子邮件进行了注册。如果您的数据库中不存在具有给定电子邮件地址或 Twitter ID 的用户,请创建一个新用户并将 Twitter ID 和电子邮件分配给此配置文件。
不要忘记将 includeEmail 选项添加到策略中:
TwitterStrategy({
consumerKey: "",
consumerSecret: "",
callbackURL: "http://localhost:3000"
includeEmail: true, // <======= this
}
)
Run Code Online (Sandbox Code Playgroud)
twitter oauth 的回调可能如下所示:
async (token, tokenSecret, profile, cb) => {
const existingProfileWithTwitterId = await Profile.findOne({ twid: profile.id }
if (existingProfileWithTwitterId) {
return callback(null, profile)
}
const existingProfileWithEmail = await Profile.findOne({ email: profile.emails[0].value }
if (existingProfileWithEmail) {
existingProfileWithEmail.twid = profile.id
// Add some more stuff from twitter profile if you want
await existingProfileWithEmail.save()
return callback(null, existingProfileWithEmail)
}
// Create a new Profile
const profile = new Profile({
twid: profile.id,
// add some more properties
})
return callback(null, profile)
})
Run Code Online (Sandbox Code Playgroud)
之后,您可以在下一个中间件中使用 req.user 访问用户配置文件。
| 归档时间: |
|
| 查看次数: |
249 次 |
| 最近记录: |