1

Using Fine Uploader with Rails 3.2, I don't know how to configure Fine Uploader to make upload requests that the Rails backend can authorise.

The Fine Uploader front-end element works fine and targets my resource (uploads), but because the uploads#create endpoint is guarded by authorisation (user must be logged in) the request has to contain valid session information to be let through. And it doesn't, so the upload of course fails.

How do I make Fine Uploader make requests that contain the necessary information for Rails to accept this as part of the user's session?

For what it's worth I initialise the uploader like this:

app/views/uploads/index.html.haml

[ ...template... ]

:javascript
    var uploader = new qq.FineUploader({
        debug:true,
        element: document.getElementById("uploader"),
        request: {
            endpoint: '/uploads',
        }
    })

It makes a POST /upload request which is routed to upload#create, but fails authorisation because of checks in the controller like this:

def session_exists?
    return true if !session[:user_id].blank?`

Any insights appreciated.

Jon Lauridsen
  • 2,521
  • 5
  • 31
  • 38

1 Answers1

3

The crucial bit here is to understand Rails' authenticity token and its role in CSRF (Cross-Site Request Forgery) protection. The AJAX request going out of Fine Uploader must contain the correct token for Rails to accept it as a legitimate request coming from the site.

To that end you must first include the token somewhere in rendered HTML.

E.g. use this in the HAML template:

%div#uploader{data: {authenticity: {token: form_authenticity_token}}}
:javascript
    var uploader = new qq.FineUploader({
        debug:true,
        element: document.getElementById("uploader"),
        request: {
            endpoint: '/uploads',
            params: {authenticity_token: $('#uploader').data('authenticity-token')}
        }
    })

This generates the token into the HTML's #uploader element, and configures Fine Uploader to pass that value back when it makes requests using a JQuery data accessor.

This is all probably basic stuff but I'm new to Rails so this had me confused for a spell. The SO question "Fine Uploader with Rails form" touches on this, but I was not able to understand its answer until after I pieced together the larger context.

Community
  • 1
  • 1
Jon Lauridsen
  • 2,521
  • 5
  • 31
  • 38
  • 1
    You can also set the upload request params dynamically using the [`setParams` API method](http://docs.fineuploader.com/branch/master/api/methods.html#setParams). – Ray Nicholus Oct 28 '16 at 15:55