访问req.user以将id保存到mongoDB

时间:2018-03-22 06:31:12

标签: javascript node.js express

我目前在弄清楚如何访问req.user时遇到问题,因此我可以获取登录用户ID并将其保存在网页上保存的项目中。这样,当他们加载网页时,他们只获得他们的项目。我知道访问req.user的唯一地方是我的/router/auth.js文件。我想弄清楚在不同的路由器文件中访问它的方法。

路由器/ auth.js

const express = require('express');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');

const config = require('../config');

const router = express.Router();

const createAuthToken = function (user) {
  return jwt.sign({ user }, config.JWT_SECRET, {
    subject: user.username,
    expiresIn: config.JWT_EXPIRY,
    algorithm: 'HS256'
  });
};

const localAuth = passport.authenticate('local', { session: false });
router.use(bodyParser.json());

router.post('/login', localAuth, (req, res) => {
  const authToken = createAuthToken(req.user.serialize());
  res.json({ authToken });
});

const jwtAuth = passport.authenticate('jwt', { session: false });

router.post('/refresh', jwtAuth, (req, res) => {
  const authToken = createAuthToken(req.user);
  res.json({ authToken });
});

/router/portfolio.js

router.post('/:id', (req, res) => {
  const id = req.params.id;
  const { holdings } = req.body;

  CryptoPortfolio.findOne({ id }, (err, existingCoin) => {
    if (existingCoin === null) {
      getCoins(id)
        .then(x => x[0])
        .then(value =>
          CryptoPortfolio.create({
            id: value.id,
            holdings,
            _creator: this is where I want to add req.user.id
              }).then(() => value))
        .then(newItem => {
          res.status(201).json(newItem);
        })
        .catch(err => {
          console.error(err);
          res.status(500).json({ message: 'Internal server error' });
        });
    } else {
      const capitalizedId = id.charAt(0).toUpperCase() + id.slice(1);
      res.json(`${capitalizedId} already in watchlist`);
    }
  });
});

2 个答案:

答案 0 :(得分:1)

您可以定义全局变量并使用中间件来使用它。

app.js

// Global Vars
app.use(function (req, res, next) {
    res.locals.user = req.user
    next();
});

route.js

router.get('/', function(req, res) {
    CryptoPortfolio.find({}, function(err, crypto) {
        console.log('CryptoPortfolio : ',crypto);
        res.render('view/crypto', {
            user : res.locals.user   // <= here
        });
    });
});

我希望它会有所帮助:)

答案 1 :(得分:0)

我发现我没有在任何必要的路线上使用下面的代码。实现它,我现在可以访问req.user。

const jwtAuth = passport.authenticate('jwt', { session: false });