Restrict access to images in Rails app

2019-01-28 10:10发布

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 viewed only by the administrator). How should I do it?

2条回答
霸刀☆藐视天下
2楼-- · 2019-01-28 10:16

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.

查看更多
一夜七次
3楼-- · 2019-01-28 10:37

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

查看更多
登录 后发表回答