2014년 12월 1일 월요일

hackathon-starter using Lusca - where is csrf value being calculated/stored?

I'm very new to Node so please forgive me if this is a noob question.  I'm trying to use convert this project on github over to use ejs views , but struggling to understand how they're creating the csrf token.

Seed project I'm using - 

Uses lusca for csrf generation


The code I'm seeing in their seed proejct (at least what I think is relevant)

var csrf = require('lusca').csrf();

/**
 * CSRF whitelist.
 */

//app.js
var csrfExclude = ['/url1', '/url2'];

//original project uses jade
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');   //i'm going to change this to ejs, but don't know where to get the csrf value(below) from

app.use(function(req, res, next) {
  // CSRF protection.
  if (_.contains(csrfExclude, req.path)) return next();
  csrf(req, res, next);
});
app.use(function(req, res, next) {
  // Make user object available in templates.
  res.locals.user = req.user;
  next();
});
app.use(function(req, res, next) {
  // Remember original destination before login.
  var path = req.path.split('/')[1];
  if (/auth|login|logout|signup|fonts|favicon/i.test(path)) {
    return next();
  }
  req.session.returnTo = req.path;
  next();
});

//route controllers
app.get('/', homeController.index);



//in separate controller file - home.js

exports.index = function(req, res) {
  res.render('home', {
    title: 'Home'
  });
};


//inside their jade file - this is converted to html tag --- <meta name="csrf-token" content="cRcgih7Vl1Ms2Xz0zgIeAyWwQm6s4kp3/8OS4=">
meta(name='csrf-token', content=_csrf)

//so value _csrf is converted to cRcgih7Vl1Ms2Xz0zgIeAyWwQm6s4kp3/8OS4=

My confusion is where is the _csrf tag being pulled from?  I tried to grep that keywork through all the files and don't actually see it set anywhere (might be missing something?).  I'm looking through my inspector and able to see that a session variable is set req.session._csrfSecret = nLzJqL3YIAJVzA==  , but this doesn't look to be the same key as used above.  Based on the /8OS4 I'm thinking the value is actually concatenated somewhere.

My question is - in the jade template, where does this _csrf value come from?  I don't see where jade is grabbing it from in the js code anywhere (I don't see _csrf set in the response anywhere).

Or what's the normal way to create and persist the csrf value using lusca?



With the middleware loaded, it generates a token and stores it in res.locals: see https://github.com/krakenjs/lusca/blob/master/lib/csrf.js#L33 (Line 20 defaults the key to _csrf, and the highlighted line adds the token to the locals)




Ahhhh perfect!   I somehow looked past this.

Thanks so much!


댓글 없음:

댓글 쓰기