我正在尝试创建一个中间件,以仅允许管理员访问node.js项目中的某些路由。我的中间件当前看起来像这样。
function adminAuth(req, res, next){
if(req.user.isAdmin){
return next();
} else {
res.redirect("/");
}
}
问题在于,即使用户数据包含isAdmin:true,也无法识别req.user.isAdmin。我相信我需要在我的护照策略中定义user.isAdmin,但是我不确定该怎么做。任何帮助将不胜感激!
这是我的本地策略
(async function addUser() {
let client;
try {
client = await MongoClient.connect(url);
const db = client.db(dbName);
const col = db.collection('users');
const user = await col.findOne({ email });
debug('Found user by email');
debug(user);
if (!user) {
req.flash('error', 'The username or password is wrong');
done(null, false);
} else {
const match = await bcrypt.compare(password, user.password);
if (match) {
done(null, user);
} else {
req.flash('error', 'The username or password is wrong');
// we pass null because it did not error, just failed
done(null, false);
}
}
} catch (e) {
debug(e.stack);
}
client.close();
}());
}
));
};
这是我的护照。
passport.serializeUser((user, done) => {
done(null, user.email);
});
passport.deserializeUser((email, done) => {
done(null, email);
});
};