Question

I use ruby 1.9.3, Rails 4.0.4, and Redmine 1.4.4

I want to access to downloading a PDF only if I have the right.

My controller:

class MyController < ApplicationController
  unloadable

  def myFunction
    # code that create a pdf

    File.open(myPdf, 'r') do |file|
      send_file file, :filename => myPdf, :type => "application/pdf", :disposition => "attachment"
      end
    end
  end

end

If I try to access to my PDF without being logged, I can download it, so I need to check the authentication.

I tried http_basic_authenticate_with :name => "name", :password => "psw" and it give me (undefined method 'http_basic_authenticate_with' for myController:Class.

I tried before_action :authenticate, it give me undefined method 'before_action' for myController:Class.

I tried before_filter :authenticate_user ... and it give me undefined method 'authenticate_user' for #<myController:0x000000064f20d0>

I should use before_action because it's Rails 4, why it dosen't work ?

How can I do ?

EDIT: I don't want that all users could access to the pdf, just the ones I give right...

Was it helpful?

Solution

I use this feature in my project:

class DownloadController < ApplicationController
  before_action :authenticate, only: :billing_pdf

  def billing_pdf
    # i save my pdf file in private folder
    send_file Rails.root.join('private', "billing_pdf"), type: "application/pdf", x_sendfile: true
  end

   def authenticate
    authenticate_or_request_with_http_basic('Administration') do |username, password|
      username == 'admin' && password == 'password'
    end
  end
end

in views:

<%= link_to 'Download Billing', download_billing_pdf_path %>

in routes:

namespace :download do
  get 'billing_pdf'
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top