javascript - 如何创建管理员并允许访问 node.js 中的管理面板?
问题描述
我对编码非常陌生,正在使用 node.js、express、mongoDB 和 mongoose 编写个人项目。我自己写了大部分,但是我雇了人来帮助我完成更高级的部分。我与他失去了联系,并回到后台创建了一个管理面板,我可以用它来写博客文章和其他东西。我正在尝试编写一个只允许我自己访问路由的中间件。但是它不起作用。
function adminAuth(req, res, next){
if(req.user.isAdmin){
return next();
} else {
res.redirect("/");
}
}
我对他用来创建用户模式的语法有点困惑,我不确定如何添加这个 isAdmin 键值对。非常感谢使用 isAdmin 键值更新我的用户的任何帮助,并且还帮助我完成中间件,因为 (req.user.isAdmin) 不起作用!(如果我没有提供必要的代码,请原谅我的经验不足并告诉我你想看什么)。
这是我聘请的编码员写的 Auth 路线,我无法破译如何将新数据传递给用户模型。
const isAdmin = false;
const passwordHash = await bcrypt.hash(req.body.password, saltRounds);
const db = client.db(dbName);
const col = db.collection('users');
const user = {
email, firstName, lastName, password: passwordHash, isAdmin,
};
地方战略
module.exports = function localStrategy() {
passport.use(new Strategy(
{
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true
}, (req, email, password, done) => {
const url = process.env.MONGOLAB_URI;
const dbName = 'giftgrab';
(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();
}());
}
解决方案
这是我聘请的编码员写的 Auth 路线,我无法破译如何将新数据传递给用户模型。
// add logic to check if the user is admin
const isAdmin = false;
// user data collected here. If you want to add an "isAdmin" property, this is the right place
const user = {
email, firstName, lastName, password: passwordHash, isAdmin,
};
// checking if the user already exists
const check = await col.findOne({ email });
if (check) {
req.flash('error', 'The user with this email already exists');
res.redirect('back');
} else {
// the user does not exist, insert a new one and authenticate
const results = await col.insertOne(user);
req.login(results.ops[0], () => {
res.redirect('/');
});
}
这与添加 isAdmin 属性有关。为了使用 req.user 和 req.isAuthenticated() 你需要Passport.js。存储在会话中的用户数据 (req.user) 由您的护照策略定义,因此如果您想以这种方式使用 isAdmin 属性,则需要在此处进行设置。
推荐阅读
- python - 在 Python 中,如何获取一串平均值并对它们进行排序?
- java - java和kotlin之间的getter和setter
- grid-layout - 允许用户创建自己的数据表
- javascript - 用于 Google Apps 脚本的 Ethereum 最小库
- express - Sqlite3 在 Express 中返回带有 GET 请求的空数组
- python - 尝试对数据框进行分组并计算类别的出现次数
- powershell - 如何同时捕获外部命令输出并将其打印到终端
- fortran - 如何让 Doxygen 使用 Fortran 接口语句?
- python - 是否有机会在包含未知字母的字符串中进行搜索?
- c# - C#计算器“输入字符串的格式不正确”除了加法之外的每个操作