如何在node.js中创建管理员并允许访问管理员面板?

时间:2019-02-24 14:17:59

标签: javascript node.js mongodb mongoose ecmascript-6

我对编码非常陌生,正在使用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();
  }());
}

1 个答案:

答案 0 :(得分:0)

  

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

相关问题