在Rails应用程序中限制对图像的访问 [英] Restrict access to images in Rails app

查看:142
本文介绍了在Rails应用程序中限制对图像的访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有rails项目。在我的项目中,我在服务器上加载图像(rails 3 + paperclip + devise + cancan)。我想限制对文件的访问(例如,原始图像只能由管理员查看)。我应该怎么做?

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?

推荐答案

如果您要限制数据库中的属性,那么一种方法是提供图像通过控制器。它不是最高效的,但它是安全的。

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

然后你可以创建一个路线你的应用程序使用文件名属性响应 / images 并通过控制器提供所有这些图像。

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.

例如

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

您可能希望确保消毒然而, params [:filename] ,否则用户就可以下载服务器上的任何文件了!

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!

send_file 上的文档位于: http:/ /apidock.com/rails/ActionController/DataStreaming/send_file

这篇关于在Rails应用程序中限制对图像的访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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