将用户对象暴露在req对象中

时间:2019-01-08 13:07:11

标签: node.js express passport.js passport-local

我正在尝试将用户对象放入请求中,以便可以在所有路径上使用它。这是我的设置:

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

身份验证控制器的路由:

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 :(得分:1)

您是否可以为此目的创建中间件功能:

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