簡體   English   中英

Pundit authorizaton用於使用Refile gem上傳的文件

[英]Pundit authorizaton for files uploaded with Refile gem

如何使用Pundit對使用Refile gem上傳的文件進行授權? 我上傳的文件應該僅限於上傳它們的用戶,但是任何擁有Refile的attachment_url生成的網址的人都可以訪問該文件。 由於Refile使用它自己的Sinatra應用程序,因此我沒有使用rails控制器來調用Pundit的授權方法。

在您的控制器中,您可以使用下載文件的方法。 對於更復雜的示例,假設您在UsersController控制器中有download操作。 從這里開始,您可以像往常一樣使用pundit download操作會抓取用戶的圖像。

免責聲明:這是一個生產實踐的可怕例子,因為如果這個動作被大量調用,你將會敲擊服務器。 實際上,每次調用此操作時,您都要調整圖像大小。 但是,作為一個概念證明,除了重新refile文件下載通常如何工作,並添加您正在尋求的授權。

我們創建一個processor變量來初始化ImageProcessor填充選項。 然后,我們創建一個臨時文件並將其設置為二進制模式。 我們從用戶模型中獲取文件並將其讀入臨時文件。 將臨時文件倒回到文件的開頭並將其讀入MiniMagick 然后我們調用我們的processor來轉換臨時文件(保留原始文件)。 然后我們將文件發送給用戶。

  def download
    @user = User.find(params[:id])
    authorize @user
    processor = Refile.processor(:fill, Refile::ImageProcessor.new(:fill))
    temp_file = Tempfile.new('profile_image')
    temp_file.binmode
    temp_file.write @user.profile_image.read
    temp_file.rewind
    image_file = MiniMagick::Image.new(temp_file.path)
    file = processor.fill(image_file, 150, 150)
    temp_file.close
    send_file file.path
  end  

以下是將文件呈現為image_tag的示例

在此輸入圖像描述

以及調用要調整大小和下載的圖像的代碼。

<%= image_tag user_download_path(@user), class: 'img-circle img-thumbnail' %>

您可以將操作設置為接受各種其他處理選項和維度。 對於此示例,我將展示如何填充150x150像素的大小。

編輯以增加更多清晰度:

temp_file的功能是保留原始圖像。 如果您只想提供原始文件的未經處理的下載,您可以在下面執行以下操作。 您還應該閱讀send_filesend_data因為它們提供了其他內容,如filenamedispositioncontent_type等,用於自定義下載以及如何處理下載。

  def download
    @user = User.find(params[:id])
    authorize @user
    send_file @user.profile_image.download
  end

編輯:我進一步研究了Refile源代碼,發現文件鏈接的創建是由引擎在路徑中的安裝引起的。 創建初始化文件並將下面的代碼放在那里。 這將允許您在刪除上傳文件的公共鏈接時保留上述現有功能。

Refile.configure do |config|
  # config.direct_upload = ["cache"]
  # config.allow_origin = "*"
  # config.logger = Logger.new(STDOUT)
  # config.mount_point = "attachments"
  config.automount = false
  # config.content_max_age = 60 * 60 * 24 * 365
  # config.types[:image] = Refile::Type.new(:image, content_type: %w[image/jpeg image/gif image/png])
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM