Express JS授权中间件

时间:2015-05-06 20:55:59

标签: javascript node.js express

我正在使用Express JS编写API并使用JSON Web令牌进行授权。是否有更可读的方式向用户显示正确的错误消息?您将如何重构以下授权中间件?

module.exports.authorize = function (request, response, next) {
    var apiToken = request.headers['x-api-token'];

    if(apiToken) {
        var decoded = token.verify(apiToken);
        
        if(decoded) {
            if(decoded.exp <= moment().format('x')) {
                next();
            } else {
                var expiredTokenError = new Error('Token has expired');
                expiredTokenError.status = 419;
                return next(expiredTokenError);
            }
        } else {
            var invalidTokenError = new Error('Token is invalid');
            invalidTokenError.status = 401;
            return next(invalidTokenError);
        }
    } else {
        var notFoundError = new Error('Token not found');
        notFoundError.status = 404;
        return next(notFoundError);
    }
};

2 个答案:

答案 0 :(得分:2)

为了便于阅读,我建议首先处理所有错误,如果一切正常,请在最后调用。此外,您可能希望将错误处理移动到单独的功能,以避免重复自己。简而言之:

var ERRORS = {
  EXPIRED: {
    message: 'Token has expired',
    status: 419
  },
  NOT_FOUND: {
    message: 'Token not found',
    status: 404
  },
  INVALID: {
    message: 'Token is invalid',
    status: 401
  }
}

var errorHandler = function(err,next) {
  var error = new Error(err.message);
  error.status = err.status;
  next(error);
};

module.exports.authorize = function (request, response, next) {
  var apiToken = request.headers['x-api-token'];

  if(!apiToken){
    return errorHandler(ERRORS.NOT_FOUND,next);
  }

  var decoded = token.verify(apiToken);

  if(!decoded){
    return errorHandler(ERRORS.INVALID,next);
  }

  if(decoded.exp > moment().format('x')){
    return errorHandler(ERRORS.EXPIRED,next);
  }

  next();
};

答案 1 :(得分:0)

我会phantomjs2

module.exports.authorize = function (request, response, next) {
    var apiToken = request.headers['x-api-token'];

    if (!apiToken) {
        var notFoundError = new Error('Token not found');
        notFoundError.status = 404;
        return next(notFoundError);
    }

    var decoded = token.verify(apiToken);

    if (!decoded) {
        var invalidTokenError = new Error('Token is invalid');
        invalidTokenError.status = 401;
        return next(invalidTokenError);
    }

    if (decoded.exp > moment().format('x')) {
        var expiredTokenError = new Error('Token has expired');
        expiredTokenError.status = 419;
        return next(expiredTokenError);
    }

    next();
};

我知道这是JavaScript,但概念上avoid using else after a return statement可能会让您感兴趣。