Rails 3: How to intercept any http request

坚强是说给别人听的谎言 提交于 2019-12-24 00:23:55

问题


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.


回答1:


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



回答2:


You want to look at Rack (not rake).



来源:https://stackoverflow.com/questions/11442491/rails-3-how-to-intercept-any-http-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!