你好,我需要一些帮助来设置一个功能,以检查用户是否登录了Passport.js使用松弛策略。
我有一个本地策略,它工作得很好,但我也想实现一个带有slack的登录。
我已经将我的应用程序添加到slack并设置了重定向URL。但是,一切都很正常,无论用户是否登录,他们仍然可以从URL访问主页。
例如,我有我的登录页面123.456.7.891:3000/login,当用户通过本地登录或slack登录时,它会重定向到123.456.891:3000/index。嗯,如果你知道索引的URL,你可以直接导航到它。
对于本地策略,我使用此函数来防止这种情况。它检查用户是否已登录。
function isLoggedIn(req, res, next){
if(req.isAuthenticated()){
return next();
}
req.flash("error", "Must be signed in first to access this page.");
res.redirect("/login");
}然后我简单地将isLoggedIn函数添加到路由中,如下所示。
app.get("/QAApplicationHub", isLoggedIn, (req, res) => {
Application.find({}, (err, allApplications) => {
if(err){
console.log(err);
} else {
res.render("index", { application: allApplications });
// username: req.user.name
}
});
});我有一个问题,当一个用户登录与松弛是,当他们被重定向到重定向网址,它只是把他们带回登录页面,说明用户必须登录才能访问该页面。出现此消息是因为我设置了闪存,以便向用户显示错误。在我当前的代码中,isLoggedIn似乎只检查本地登录,而不是空闲的。
那么,如何为本地和松弛策略实现isLoggedIn函数呢?或者我需要实现什么方法才能让它同时适用于这两种情况。
这是我的Passport-slack代码。
// Configure the Slack Strategy
passport.use(new SlackStrategy({
clientID: process.env.SLACK_CLIENT_ID = '123456',
clientSecret: process.env.SLACK_CLIENT_SECRET ='123abc',
}, (accessToken, scopes, team, extra, profiles, done) => {
done(null, profiles.user);
}));
//=============================
//LOCAL LOGIN MIDDLEWARE
//=============================
app.post("/login", passport.authenticate("local", {
successRedirect: "/QAApplicationHub",
failureRedirect: "/login",
failureFlash: true
}));
app.get("/logout", (req, res) => {
req.logout();
req.flash("success", "Successfuly signed out!")
res.redirect("/login");
});
// =============================
// PASSPORT-SLACK MIDDLEWARE
// =============================
// path to start the OAuth flow
app.post('/auth/slack', passport.authorize('slack', {
successRedirect: "/QAApplicationHub",
failureRedirect: "/login",
failureFlash: true
}));
// OAuth callback url
app.get('/auth/slack/callback',
passport.authorize('slack',
(req, res) => {
res.redirect('/QAApplicationHub')
}));发布于 2018-01-27 00:27:57
我相信用户存储在req.user属性中。试试这个:
function isLoggedIn(req, res, next){
if(!req.user){
req.flash("error", "Must be signed in first to access this page.");
res.redirect("/login");
} else {
return next();
}
}发布于 2018-01-29 05:44:33
因此,我遗漏了一些代码来完成这项工作。首先,我需要添加slack的用户模式。其次,需要添加一个函数来创建用户并将其保存到我的数据库中,以及一个函数来检查用户是否已经使用slack登录,并只比较ID,而不是向数据库创建用户的新实例。还需要更新序列化用户和反序列化用户。
这是我的方案
let mongoose = require("mongoose"),
passportLocalMongoose = require("passport-local-mongoose");
let UserSchema = new mongoose.Schema({
local: {
name: String,
username: String,
password: String
},
slack: {
username: String,
slackid: Number,
name: String
}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);而不是护照策略的设置。
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
User.findById(id).then((user) => {
done(null, user.id);
});
});
passport.use(new LocalStrategy(User.authenticate()));
// Configure the Slack Strategy
passport.use(
new SlackStrategy({
callbackURL: "/auth/slack/redirect",
clientID: keys.slack.clientID,
clientSecret: keys.slack.clientSecret
}, (accessToken, refreshToken, profile, done) => {
console.log(profile);
// Check if user already exist in DB
User.findOne({username: profile.displayName}).then((currentUser) => {
if(currentUser){
// already have the user
console.log('User is', currentUser);
done(null, currentUser);
} else {
// If not, create new user in DB
new User({
username: profile.displayName,
slackid: profile.id
}).save().then((newUser) => {
console.log("new user created: " + newUser);
done(null, newUser);
});
}
});
})); 还需要更新身份验证和回调的路由。
app.post('/auth/slack',
passport.authenticate('Slack', {
scope:['identity.basic'],
}));
// OAuth callback url
app.get('/auth/slack/redirect', passport.authenticate('Slack'), (req, res) => {
res.redirect("/QAApplicationHub");
});希望这对其他需要passport.js帮助的人有所帮助。有关详细信息,我建议在YT上查找网络忍者。他对我的代码差距帮助很大,并帮助我理解了实际发生的事情。
https://stackoverflow.com/questions/48464821
复制相似问题