Getting a csrf token in a form

Problem

This open source chat project https://github.com/meatspaces/meatspace-chat uses the jade index file below. You'll notice that the form has an input value for a #{csrf} token. Where would this csrf value be coming from? Is it part of the browser environment? I don't see any javascript in the project that inserts that csrf token into that input field.

For example, when you visit the root, it just renders the index like this

  app.get('/', function (req, res) {
    res.render('index');
  });

index

extend layout

block content
  form(method='post', id='add-chat-form')
    input(type='hidden', name='picture', id='picture')
    .message-content
      input(name='message', id='add-chat', class='input', maxlength='250', autocomplete='off', placeholder='Send a public message')
      input(type='hidden', name='_csrf', value='#{csrf}')
      input(type='hidden', name='fingerprint', id='fp')
      input(type='hidden', name='userid', id='userid')
      #add-chat-blocker.hidden
        span Sending, please wait!
  #counter 250
Problem courtesy of: Leahcim

Solution

The tokens are created by the connect csrf middleware. You can see this in settings.js. On line 7:

  var csrf = express.csrf();

and line 13:

  var clientBypassCSRF = function (req, res, next) {
    if (req.body.apiKey && nativeClients.indexOf(req.body.apiKey) > -1) {
      next();
    } else {
      csrf(req, res, next);
    }
  };

This exposes a function csrfToken on the req object, which is used on line 45:

        res.locals.csrf = req.csrfToken();

The express templating engine (res.render('index'); in the code you showed in your question) extends the templates scope with the res.locals object, which is how that field gets filled in during templating.

Solution courtesy of: Aaron Dufour

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.