dasfmi
dasfmi

Reputation: 531

sometimes i get invalid csrf token with multipart forms

i am using expressjs 4 with csurf and formidable, sometimes i when i use a multipart form to upload:

Error: invalid csrf token at createToken (/Users/mecha/projects/sherka/maktabi/node_modules/csurf/index.js:94:19) at Layer.handle (/Users/mecha/projects/sherka/maktabi/node_modules/csurf/index.js:59:24) at trim_prefix (/Users/mecha/projects/sherka/maktabi/node_modules/express/lib/router/index.js:240:15) at /Users/mecha/projects/sherka/maktabi/node_modules/express/lib/router/index.js:208:9 at Function.proto.process_params (/Users/mecha/projects/sherka/maktabi/node_modules/express/lib/router/index.js:269:12) at next (/Users/mecha/projects/sherka/maktabi/node_modules/express/lib/router/index.js:199:19) at /Users/mecha/projects/sherka/maktabi/node_modules/express-session/index.js:226:9 at Object._onImmediate (/Users/mecha/projects/sherka/maktabi/node_modules/express-session/session/memory.js:58:9) at processImmediate [as _immediateCallback] (timers.js:330:15)

but sometimes it just works fine without any errors, any idea what is it i am doing wrong ?

here is my code

app.use(function(req, res, next){
    res.locals.session = req.session;
    res.locals.messages = req.flash('success');
    res.locals.errors = req.flash('error');
    res.locals.csrftoken = req.csrfToken();
    next();
});

here is an html form

<form id="new_desk_form" class="form" method="post" action="/space/{{ space.id}}/add/desk?_csrf={{ csrftoken }}" enctype="multipart/form-data">

here is the route handler

app.post('/space/:id/add/desk', helpers.ensureAuth, function(req, res){
    var id = req.params.id;
    var form = new formidable.IncomingForm();
    form.uploadDir = __dirname+'/../public/uploads/spaces/'+id;
    form.keepExtensions = true;
    form.encoding = 'utf-8';
    form.parse(req, function(err, fields, files){
        if(err){
            console.log(err);
            res.render('505.html')
        }
        var name = files.photo1.path.split('/');
        name = name[name.length-1];
        var pathToStore = "/uploads/spaces/"+id+'/'+name;
        var workspace = {};
        workspace.title = req.body.title;
        workspace.type = 'desk';
        workspace.photos = [];
        workspace.photos.push(pathToStore);
        workspace.currency = req.body.currency;
        workspace.quantity = req.body.quantity;
        workspace.prices = {};
        if(req.body.hourly){
            workspace.prices.hourly = req.body.hourly;
        }
        if(req.body.daily){
            workspace.prices.daily = req.body.daily;
        }
        if(req.body.monthly){
            workspace.prices.monthly = req.body.monthly;
        }
        Space.findOne({_id: id}, {}, function(err, space){
            if(err){
                console.log(err);
                    res.render('505.html');
            }
            space.workspaces.push(workspace);
            space.save(function(){
                res.redirect('/edit/'+req.id);
            })
        });
    });
});

Upvotes: 0

Views: 3136

Answers (1)

freewil
freewil

Reputation: 56

The problem you're having is an encoding issue. When the CSRF token fails to validate, it is most likely due to the CSRF token having a forward slash / or other character that needs to be encoded properly in a URL query string. This encoding is different from the escaping done by handlebars for variables with the two curly braces.

I would recommend using a hidden input instead, the browser should then encode it properly when the form is submitted:

<input type="hidden" name="_csrf" value="{{ csrftoken }}">

Alternatively, you could also make sure that csrftoken is run through encodeURIComponent() before being included in the action attribute of the form. You'd probably want to do this with a handlebars helper, which I believe you will need a third-party helper to do, here is one option: handlebars-helpers

Upvotes: 4

Related Questions