简体   繁体   中英

Ruby on Rails file authorization under RAILS_ROOT/public

I am looking for a way of running a type of check_access to my files located under my public folder. I heard about RAILS_ROOT/private. I believe this directory provides my demands.

But I don't have deep information about it. The core idea of mine is serving files to only use which has the ability to view/download the files. Such as a posted pictures, I don't want them to be public. Currently, all the people who have knowledge of the URL pointing to the correct directory can access all files.

PS: The files under /public dir are uploaded via carrierwave gem.

Thanks.

You can define the permissions in your database and then you can add a check before displaying the url of a file to the users. You shouldn't keep the files in public folder if you want them to be restricted.

If you need access control for your files you don't want to serve them from your public folder. Your public folder is server either by ActionDispatch::StaticFile or directly by your web server - neither of which provide the kind of access controll you want.

Instead you would create a controller which serves up the files:

class FilesController < ActionController::Metal
  before_action :authenticate! # you need to implement this
  before_action :authorize!    # you need to implement this

  # GET /files/:filename
  def show
    path = Rails.root.join(
      'uploads', # can be any directory you want really
       # avoids a malicous user being able to use for example '../../secret/password'
       ActiveStorage::Filename.new(params[:file_name]).sanitized
    )
    if File.exist?(path)
      send_file path
    else
      head :not_found
    end
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM