簡體   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