Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Hack lusca CSRF store
/**
* @fileOverview A CSRF Implementation for WebSocket calls.
*/
var Promise = require('bluebird');
var config = require('config');
var lusca = require('lusca');
var Middleware = require('./middleware');
/**
* A CSRF Implementation for WebSocket calls.
*
* @contructor
* @extends {cc.Middleware}
*/
var WsCsrf = module.exports = Middleware.extendSingleton(function() {
this.luscaMidd = lusca.csrf({key: '_ws_csrf'});
// run once to get the lusca secret
this.luscaSecret = null;
var self = this;
var req = this._getReqMock();
var res = this._getResMock();
this.luscaMidd(req, res, function() {
self.luscaSecret = req.session._csrfSecret;
});
});
/**
* Use as middleware, will populate the CSRF token on "res.locals._ws_csrf"
*/
WsCsrf.prototype.use = function() {
return this.luscaMidd;
};
/**
* Get a websocket CSRF token.
*
* @return {Promise(string)} A promise with the token.
*/
WsCsrf.prototype.getToken = function() {
var req = this._getReqMock();
var res = this._getResMock();
var self = this;
return new Promise(function(resolve, reject) {
self.luscaMidd(req, res, function(err) {
if (err) {
reject(err);
return;
}
resolve(res.locals['_ws_csrf']);
});
});
};
/**
* Validate a CSRF token.
*
* @param {string} token The token to validate.
* @return {Promise} A promise.
*/
WsCsrf.prototype.validate = function(token) {
var req = this._getReqMock();
var res = this._getResMock();
var self = this;
return new Promise(function(resolve, reject) {
// switch on validation
req.method = 'POST';
req.body['_ws_csrf'] = token;
self.luscaMidd(req, res, function(err) {
if (err) {
reject(err);
return;
}
resolve();
});
});
};
/**
* Hack lusca by stubbing the request and response objects.
*
* @return {Object} A new request stub object.
* @private
*/
WsCsrf.prototype._getReqMock = function() {
return {
session: {
_csrfSecret: this.luscaSecret,
secret: config.cookies.web.session.secret,
},
method: 'GET',
body: {}
};
};
/**
* Hack lusca by stubbing the request and response objects.
*
* @return {Object} A new response stub object.
* @private
*/
WsCsrf.prototype._getResMock = function() {
return {
locals: {},
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment