Предоставление пользовательского объекта внутри объекта req - PullRequest
0 голосов
/ 08 января 2019

Я пытаюсь получить пользовательский объект внутри req, чтобы иметь его на всех моих маршрутах. Это моя установка:

app.js:

// Use the passport middleware
app.use(passport.initialize());

// load passport strategies
const localSignupStrategy = require('./server/passport/local-signup');
const localLoginStrategy = require('./server/passport/local-login');
passport.use('local-signup', localSignupStrategy);
passport.use('local-login', localLoginStrategy);


// View engine setup
app.set('views', path.join(__dirname, '/server/views'));
app.set('view engine', 'pug');

// Serve static assets normally
app.use(express.static(path.join(__dirname, '/dist')));

// Define routes
app.use('/auth', auth); //Auth controller
app.use('/api', api);

Маршрут для контроллера Auth:

const express = require('express');
const router = express.Router();

const authController = require('../main/controllers/authController');

// POST /auth/signup
router.post('/signup', authController.postSignup);

// POST /auth/login
router.post('/login', authController.postLogin);

module.exports = router;

authController.postLogin

exports.postLogin = function(req, res, next) {
  const validationResult = validateLoginForm(req.body);
  if (!validationResult.success) {
    return res.status(400).json({
      success: false,
      message: validationResult.message,
      errors: validationResult.errors
    });
  }

  return passport.authenticate('local-login', (err, token, userData) => {
    if (err) {
      if (err.name === 'IncorrectCredentialsError') {
        return res.status(400).json({
          success: false,
          message: err.message
        });
      }

      return res.status(400).json({
        success: false,
        message: 'Could not process the form.'
      });
    }

    return res.json({
      success: true,
      message: 'Login success.',
      token,
      user: userData
    });
  })(req, res, next);
};

Это мой обычный маршрут контроллера:

// GET /api/cms
router.get('/cms/', authCheck(), getCmsDataController.getCmsData);

module.exports = router;

authcheck.js

module.exports = function(roles) {

  // Return middleware
  return (req, res, next) => {
    if (!req.headers.authorization) {
      return res.status(401).end();
    }

    // Get the last part from a authorization header string like "bearer token-value"
    const token = req.headers.authorization.split(' ')[1];

    // Decode the token using a secret key-phrase
    return jwt.verify(token, config.jwtSecret, (err, decoded) => {

      // 401 not unauthorized
      if (err) return res.status(401).end();

      const userId = decoded.sub;

      // Check if user exists
      return User.findById(userId, (err2, user) => {
        if (err2 || !user) return res.status(401).end();
        req.currentLoggedUser = user;
        console.log(user.role);
        if (roles) {
          if (roles.indexOf(user.role) > -1) return next();
          else return res.status(401).end();
        }
        return next();

      });
    });

  };
};

И сам контроллер:

// GET /api/cms-data/
exports.getCmsData = function(req, res, next) {

  return res.json({
    message: 'Lets see does this thing work or not!!!'
  });
};

Проблема в том, что когда я достигаю контроллера getCmsData, я хотел бы иметь объект пользователя внутри объекта req. У моего пользователя есть некоторые свойства, такие как роль и пол, к которым мне нужен доступ. У меня есть одно хакерское решение, но я думаю, что есть способ сделать это.

1 Ответ

0 голосов
/ 08 января 2019

Не могли бы вы создать функцию промежуточного программного обеспечения для этой цели:

function getRequestUser(req) {
    // In reality you'd load from data store based on request.
    return {id: 1, name: "Jim Smith"};
}

function addUserMiddleWare(req, res, next) {
    req.user = getRequestUser(req);
    next();
}

// Then add it to your route.
// GET /api/cms
router.get('/cms/', authCheck(), addUserMiddleWare, getCmsDataController.getCmsData);

module.exports = router;

// Or, apply to all paths on router
router.use(addUserMiddleWare);
...