3

Lets say I have an image at app/assets/images/privateimages/myrestrictedimage1.jpg If I try to go directly to the image via url say with something like

 http://localhost:5555/assets/privateimages/myrestrictedimage1.jpg

I am able to view the image.

I would like to have a way to inspect any http request to decide if the user is allowed access to it.

I know I can use before_filter in controllers to do some preprocessing before continuing onto any of the controller actions but I dont think this will help me because I need to be attempting to do a controller action for this to take effect.

I have heard I might be able to do it with a rake task but after much searching I haven't found anything like what I am trying to do. Perhaps I have to create a ruby gem to do this but I have no clue how to do this.

Can anyone point me in the right direction? Thanks.

snowleopard
  • 781
  • 3
  • 13
  • 36

2 Answers2

4

I used Rack Middleware

The middleware class looks like this:

class MyChecker  
  def initialize(app)
    @app = app       
  end                

  def call(env)
    if (docheck)
      #do stuff here such as check the path.
      #For example @path = env['PATH_INFO'] and compare against your okay paths  
      #if youre good and are able to continue then
      @app.call(env)
    else
      #redirect such as
      [301, {"Location" => /somewhere, "Content-Type" => "text/html"}, []]
    end
  end  

end 

make sure to make your middleware visible by adding the following to application.rb

class Application < Rails::Application
  ...
  config.autoload_paths += %W(#{config.root}/lib)  #if MyChecker is located in lib othewise substitute lib with wherever you have your middleware class
  config.middleware.use "MyChecker"
end
snowleopard
  • 781
  • 3
  • 13
  • 36
2

You want to look at Rack (not rake).

olore
  • 4,687
  • 3
  • 28
  • 40
  • After much reading up on Rack, I believe this is probably the way to go I just have no idea how. So far most of the Rack examples simply display some text using a Rack application. I can't find an example of how to do some other kind of logic with Rack and then continue. So for example, if user goes to http://localhost:3000/* then some code that performs a check on the url is run and if the check passes then the user is able to continue on to /* normally otherwise they are redirected to some other url. – snowleopard Jul 13 '12 at 17:23