【问题标题】:Rails 3: How to intercept any http requestRails 3:如何拦截任何http请求
【发布时间】:2012-07-11 15:38:32
【问题描述】:

假设我在 app/assets/images/privateimages/myrestrictedimage1.jpg 有一张图片 如果我尝试通过 url 直接转到图像,请说类似

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

我可以查看图像。

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

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

我听说我可以通过 rake 任务来完成它,但经过大量搜索后,我没有找到任何像我想要做的事情。也许我必须创建一个红宝石来做到这一点,但我不知道如何做到这一点。

谁能指出我正确的方向?谢谢。

【问题讨论】:

    标签: ruby ruby-on-rails-3.1 rubygems rake-task


    【解决方案1】:

    我使用了机架中间件

    中间件类如下所示:

    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 来使您的中间件可见

    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 版本 5 中引发错误。
    【解决方案2】:

    你想看看Rack(不是rake)。

    【讨论】:

    • 在 Rack 上大量阅读之后,我相信这可能是要走的路,我只是不知道该怎么做。到目前为止,大多数 Rack 示例只是使用 Rack 应用程序显示一些文本。我找不到如何用 Rack 做一些其他类型的逻辑然后继续的例子。因此,例如,如果用户转到localhost:3000*,则运行一些对 url 执行检查的代码,如果检查通过,则用户可以正常继续到 /*,否则他们将被重定向到其他一些 url。
    猜你喜欢
    • 1970-01-01
    • 2017-07-13
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多