Restrict access to images in Rails app

旧时模样 提交于 2019-12-18 08:55:45

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/14306035/restrict-access-to-images-in-rails-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!