jpatel701
jpatel701

Reputation: 73

Access req.user to save id to mongoDB

I'm currently having an issue with figuring out how I can access req.user so I can get the logged in users id and save it with the items that they save on the web page. That way when they load the web page they only get their items. The only place I know where I have access to req.user is in my /router/auth.js file. I want to figure out a way to access it in a different router file.

router/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`);
    }
  });
});

Upvotes: 0

Views: 804

Answers (2)

jpatel701
jpatel701

Reputation: 73

I figured out that I wasn't using the code below on any of the necessary routes. Implemented it and I can now access req.user.

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

Upvotes: 0

Jihoon Kwon
Jihoon Kwon

Reputation: 755

You can define global variable and use it using middleware.

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
        });
    });
});

I hope it would be helpful :)

Upvotes: 1

Related Questions