Beware respond_to format with redirects in shared systems before_filter - DoubleRenderError

If you use an authenticated_system on your Rails site, with global before_filters for things like requiring login to access pages, be careful of missing formats in the respond_to.  I just tracked down a bug on an app where we were getting DoubleRenderErrors because of unauthenticated request directly to a csv file.  We had a before_filter that was denying request and redirecting them to login, in different ways, depending on the format, but hadn’t thought to include csv.  In this case, it is wise to include a catch-all at the end using .any

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 
def anon_access_denied
  respond_to do |accepts|
    accepts.html do
      store_location
      redirect_to login_path
    end
    accepts.xml do
      headers[“Status”] = “Unauthorized”
      headers[“WWW-Authenticate”] = %(Basic realm=”Web Password”)
      render :text => “Could’t authenticate you”, :status => ‘401 Unauthorized’
    end
    accepts.js do
      render(:update) { |page| page.redirect_to login_path }
    end
  end
end

Posted via web from a timocracy of one | Comment »