在 req 对象中公开用户对象

Exposing user object inside the req object

我试图在请求中获取用户对象,这样我就可以在我的所有路由中使用它。这是我的设置:

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 对象中有一个用户对象。我的用户有一些我需要访问的属性,例如角色和性别。我有一个 hacky 解决方案,但我认为有一种方法可以做到这一点。

您能否为此目的创建一个中间件函数:

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