问题
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