dox-foundation-demo node_modules/express/node_modules/connect/lib/middleware/csrf.js

utils

declaration
utils

    Description

    Module dependencies.

    Source

    var utils = require('../utils');
    var uid = require('uid2');
    var crypto = require('crypto');

    exports

    method
    module.exports()
    • @param: {Object}options

    Description

    Anti CSRF:

    CSRF protection middleware.

    This middleware adds a req.csrfToken() function to make a token
    which should be added to requests which mutate
    state, within a hidden form field, query-string etc. This
    token is validated against the visitor's session.

    The default value function checks req.body generated
    by the bodyParser() middleware, req.query generated
    by query(), and the "X-CSRF-Token" header field.

    This middleware requires session support, thus should be added
    somewhere below session() and cookieParser().

    Options:

    • value a function accepting the request, returning the token

    Source

    module.exports = function csrf(options) {
      options = options || {};
      var value = options.value || defaultValue;
    
      return function(req, res, next){
        
        // already have one
        var secret = req.session._csrfSecret;
        if (secret) return createToken(secret);
    
        // generate secret
        uid(24, function(err, secret){
          if (err) return next(err);
          req.session._csrfSecret = secret;
          createToken(secret);
        });
        
        // generate the token
        function createToken(secret) {
          var token;
    
          // lazy-load token
          req.csrfToken = function(fn){
            if (fn) {
              if (token) return fn(null, token);
              saltedToken(secret, function(err, tok){
                token = tok;
                fn(err, tok);
              });
              return;
            }
    
            return token || (token = saltedTokenSync(secret));
          };
          
          // compatibility with old middleware
          Object.defineProperty(req.session, '_csrf', {
            configurable: true,
            get: function() {
              console.warn('req.session._csrf is deprecated, use req.csrfToken([callback]) instead');
              return req.csrfToken();
            }
          });
          
          // ignore these methods
          if ('GET' == req.method || 'HEAD' == req.method || 'OPTIONS' == req.method) return next();
          
          // determine user-submitted value
          var val = value(req);
          
          // check
          if (!checkToken(val, secret)) return next(utils.error(403));
          
          next();
        }
      }
    };