Add csrf token handling to api mixin

This commit is contained in:
Ray Schamp 2015-10-07 15:00:47 -04:00
parent 31fb5911ea
commit 7b3874ffd5
3 changed files with 52 additions and 17 deletions

View file

@ -2,10 +2,11 @@
{
"root": "/",
"paths": [
"/session/",
"/accounts/login/",
"/accounts/logout/",
"/get_image/"
"/accounts/",
"/accounts/",
"/csrf_token/",
"/get_image/",
"/session/"
]
}
]

View file

@ -1,6 +1,5 @@
var React = require('react');
var classNames = require('classnames');
var cookie = require('cookie');
var xhr = require('xhr');
var log = require('../../log.js');
@ -35,13 +34,11 @@ module.exports = React.createClass({
this.setState({'loginOpen': false});
},
handleLogIn: function (formData) {
var csrftoken = cookie.parse(document.cookie)['scratchcsrftoken'];
formData['csrftoken'] = csrftoken;
this.api({
method: 'post',
uri: '/accounts/login/',
json: formData,
headers: {'X-CSRFToken': csrftoken}
useCsrf: true
}, function (err, body) {
if (body) {
body = body[0];

View file

@ -1,18 +1,55 @@
var cookie = require('cookie');
var defaults = require('lodash.defaults');
var xhr = require('xhr');
var log = require('../log.js');
module.exports = {
getCsrf: function (callback) {
var obj = cookie.parse(document.cookie) || {};
if (typeof obj.scratchcsrftoken === 'undefined') return callback('Cookie not found.');
callback(null, obj.scratchcsrftoken);
},
useCsrf: function (callback) {
this.getCsrf(function (err, csrftoken) {
if (csrftoken) return callback(null, csrftoken);
xhr({
'uri': '/csrf_token/'
}, function (err) {
if (err) return callback(err);
this.getCsrf(function (err, csrftoken) {
if (err) return callback(err);
callback(err, csrftoken);
});
}.bind(this));
}.bind(this));
},
api: function (opts, callback) {
opts = defaults(opts, {json: {}});
opts.headers = defaults(opts.headers, {'X-Requested-With': 'XMLHttpRequest'});
xhr(opts, function (err, res, body) {
if (err) {
log.error(err);
callback(err);
} else {
callback(err, body);
}
defaults(opts, {
headers: {},
json: {},
useCsrf: false
});
defaults(opts.headers, {
'X-Requested-With': 'XMLHttpRequest'
});
var apiRequest = function (opts) {
xhr(opts, function (err, res, body) {
if (err) log.error(err);
callback(err, body);
});
}.bind(this);
if (opts.useCsrf) {
this.useCsrf(function (err, csrftoken) {
if (err) return log.error('Error while retrieving CSRF token', err);
opts.json.csrftoken = csrftoken;
opts.headers['X-CSRFToken'] = csrftoken;
apiRequest(opts);
}.bind(this));
} else {
apiRequest(opts);
}
}
};