首页 > 解决方案 > 如何创建管理员并允许访问 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();
  }());
}

标签: javascriptnode.jsmongodbmongooseecmascript-6

解决方案


这是我聘请的编码员写的 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 属性,则需要在此处进行设置。


推荐阅读