Restrict access to images in Rails app

后端 未结 2 448
自闭症患者
自闭症患者 2020-12-21 04:08

I have rails project. In my project I load images on server (rails 3 + paperclip + devise + cancan). I want to limit access to files (for example, the original image can be

相关标签:
2条回答
  • 2020-12-21 04:12

    If you are limiting by an attribute in your database then one way would be to serve the image via a controller. It's not the most performant but it is secure.

    I haven't tried this out, but if you were serving the image from a URL like

    /images/picture_of_mickey_mouse.png

    then you could create a route in your app that responds to /images with a filename attribute and serve all those images through a controller.

    e.g.

    class ImagesController < ApplicationController
      before_filter :authenticate_admin!, :only => [:show]
      def show
        send_file "/images/#{params[:filename]}", :disposition => 'inline'
      end
    end
    

    You would want to make sure you sanitize the params[:filename] however, otherwise the user would be able to download any file on your server!

    The docs on send_file are here: http://apidock.com/rails/ActionController/DataStreaming/send_file

    0 讨论(0)
  • 2020-12-21 04:22

    Files are handled with ActionDispatch::Static. IMO the best solution is provide similar middleware (basing on Rails source code) but with some authentication and insert it before ActionDispatch::Static. This would work with Warden-based solutions (like Devise) since they do authentication in middleware; just ensure your middleware is put after Warden and old plain ActionDispatch::Static is run just after them.

    EDIT: One more thing worth noting. It's quite common in production that Nginx (I'm not sure about Apache and others) is configured to serve all the static files by itself, without passing those requests to rack stack. You may need to disable this Nginx' feature.

    0 讨论(0)
提交回复
热议问题