Rails 3:如何拦截任何http请求 [英] Rails 3: How to intercept any http request

查看:124
本文介绍了Rails 3:如何拦截任何http请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在app/assets/images/privateimages/myrestrictedimage1.jpg中有一张图片 如果我尝试直接通过网址转到图片,请使用类似

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

我能够查看图像.

我想有一种方法可以检查任何http请求,以确定是否允许用户访问它.

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

我知道我可以在控制器中使用before_filter进行一些预处理,然后再继续执行任何控制器操作,但是我认为这不会对我有帮助,因为我需要尝试执行控制器操作才能使其生效.

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.

我听说我可以用rake任务来完成任务,但是经过大量搜索之后,我没有发现想要执行的操作.也许我必须制造一颗红宝石才能做到这一点,但我不知道如何做到这一点.

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.

推荐答案

我使用了机架中间件

中间件类如下:

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 

通过在application.rb中添加以下内容,确保中间件可见.

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

这篇关于Rails 3:如何拦截任何http请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆