trevorturk / flash_cookie_session

Rails 3 cookie sessions can cooperate with Flash
79 stars 16 forks source link

=== Rails 3 cookie sessions can cooperate with Flash

This is useful for Flash-based file uploaders (SWFUpload, Uploadify, Plupload, etc)

The problem is that Rails uses cookie-based sessions to keep track of the current_user, etc. You may also have to worry about the +authenticity_token+ being passed around if you're using +protect_from_forgery+ and you'd like to avoid those pesky +InvalidAuthenticityToken+ errors.

There are many, many blog posts about this: http://www.google.co.uk/search?q=rails+flash+upload

I'm not sure who first figured everything out, so I won't bother trying to credit anyone. Thank you, though, kind person who figured all of this out in the first place. This gem represents a meager attempt to make this all a bit easier to deal with in Rails 3. No need for special routes, no need to manually configure FlashSessionCookieMiddleware, etc.

=== Installation

1) Add this gem to your Gemfile:

gem 'flash_cookie_session', github: 'trevorturk/flash_cookie_session'

2) Convince your Flash uploader to pass in the additional params necessary. This is going to be different given the Flash uploader you're using, but see the provided SWFUpload example below, and note the +post_params+ section:

var swfu = new SWFUpload({
  debug : false,
  flash_url : '/flash/swfupload.swf',
  upload_url: '<%= upload_url %>',

  post_params : {
    "<%= key = Rails.application.config.session_options[:key] %>" : "<%= cookies[key] %>",
    "<%= request_forgery_protection_token %>" : "<%= form_authenticity_token %>",
  },

  button_image_url: "/images/swfupload.png",
  button_width: "100",
  button_height: "100",
  button_placeholder_id: "swfupload",

  file_size_limit : "20 MB",
  file_types : "*",
  file_types_description : "Files",
  file_upload_limit : 20,
  file_queue_limit : 20,

  file_queued_handler : fileQueued,
  file_queue_error_handler : fileQueueError,
  upload_start_handler : uploadStart,
  upload_progress_handler : uploadProgress,
  upload_success_handler : uploadSuccess,
  upload_complete_handler : uploadComplete
});

function fileQueued(file){
  this.startUpload();
}

function fileQueueError(file, errorCode, message) {
  alert(message);
}

function uploadStart(file) {
  alert('uploadStart');
}

function uploadProgress(file, bytesLoaded, bytesTotal){
  alert('uploadProgress');
}

function uploadSuccess(file, serverData){
  alert('uploadSuccess');
}

function uploadComplete(file){
  if (this.getStats().files_queued > 0) {
    this.startUpload();
  }
  else {
    alert('uploadComplete');
  }
}

With SWFUpload, the post_params are sent along with the file upload, which would be in params[:Filedata] in this example.

Let's break this down a little so you understand it better:

post_params : {
  "<%= key = Rails.application.config.session_options[:key] %>" : "<%= cookies[key] %>",
  "<%= request_forgery_protection_token %>" : "<%= form_authenticity_token %>",
},

The first key is your cookie session key which is passed along with every request when the user changes pages. If the server does not know about this session key then it cannot authenticate the user properly and therefore thinks you are not logged in. Since Flash has it's own set of cookies separate from the browser and effectively acts as it's own web browser when making requests to your app, we need to explicitly pass along the web browsersession key along with the Flash request so that the Rails server has all the info it needs to authenticate the user.

The second key is the standard authentication token that is passed along to prevent cross-site request forgeries.

If CSRF issues persist, try url_encoding the form_authenticity_token to make this work properly (<%= u form_authenticity_token %>). You might want to rename the request_forgery_protection_token to authenticity_token as well.

=== Optional Parameters

The key has to be named remember_token but your cookie may be named something other than :remember_token so change that accordingly based on your implementation.

=== Additional info

This is frustrating and annoying stuff, and I'm sorry that we have to deal with it. If you have an idea about how to improve the situation or example for additional Flash uploaders, pull requests that expand on the README and/or Rails 3 gem are more than welcome.

In additional frustration, Chrome now sandboxes the Flash player and the HTTP_USER_AGENT does not correctly come across as Adobe/Shockwave Flash. This gem now includes an additional check on the HTTP_REFERER to see if it is a SWF file.

=== License

Released under the MIT License: http://en.wikipedia.org/wiki/MIT_License