繁体   English   中英

如何在 Mean Stack (Node.js + Mongodb) 上的用户身份验证中检查当前登录的用户?

[英]How can I check currently logged user in user authentication on Mean Stack (Node.js + Mongodb)?

我有一个带有令牌的登录系统。 登录时,它会检查此类用户是否存在,在登录会话期间没有有关当前用户的信息。 检查它并向前端发送响应的最简单方法是什么?

路线:

function verifyToken(req, res, next) {
  if (!req.headers.authorization) {
    return res.status(401).send('Unauthorized request');
  }
  let token = req.headers.authorization.split(' ')[1];
  if (token === 'null') {
    return res.status(401).send('Unauthorized request');
  }
  let payload = jwt.verify(token, 'secretKey');
  if (!payload) {
    return res.status(401).send('Unauthorized request');
  }
  req.userId = payload.subject;
  next();
}
router.post('/register', (req, res) => {
  let userData = req.body;
  let user = new User(userData);
  user.save((error, registeredUser) => {
    if (error) {
      console.log(error);
    } else {
      let payload = { subject: registeredUser._id };
      let token = jwt.sign(payload, 'secretKey');
      res.status(200).send({ token });
    }
  })
})
router.post('/login', (req, res) => {
  let userData = req.body;

  User.findOne({ email: userData.email }, (error, user) => {
    if (error) {
      console.log(error);
    } else {
      if (!user) {
        res.status(401).send('Invalid email');
      } else
        if (user.password !== userData.password) {
          res.status(401).send('Invalid password')
        } else {
          let payload = { subject: user._id };
          let token = jwt.sign(payload, 'secretKey');
          res.status(200).send({ token });
        }
    }
  })
})

您可以尝试使用中间件从 Authorization 标头中检索令牌并从那里检索 userId,中间件可能如下所示:

const decodeToken = (token) => {
    return jwt.verify(token, 'secretKey', (err, decoded) => {
        if (err) {
            return undefined;
        }
        return decoded;
    });
};

const authorize = (req, res, next) => {
    if (!req.headers.authorization) {
        return res.status(401).send({message: 'UNAUTHORIZED'});
    }
    const token = req.headers.authorization.split(' ')[1];
    if (!token) {
        return res.status(401).send({message: 'UNAUTHORIZED'});
    }
    const decodedToken = decodeToken(token);
    if (!decodedToken) {
        return res.status(401).send({message: 'UNAUTHORIZED'});
    }
    req.userId = decodedToken.subject;
    next();
};

module.exports = authorize;

希望这对你有帮助,如果没有,我希望你能找到你的答案:)

编辑

要使用中间件,您只需将其添加到您的路由中,我将给您留下一个带有 get 请求的示例:

const authorize = require('../middleware/authorize');

router.get('/someroute', authorize, (req, res) => {
  // authorize will verify the token and attach the userId to your request
  // so to use it you'll only need to call req.userId
  // something like this
  console.log('current logged user id', req.userId);

  // YOUR CODE HERE
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM