我想保护上传的文件,它们保留在公共/上传目录中并且可以访问,因此用户未按以下方式登录http://localhost:3000/uploads/video/1/test.mp4
。我想防止发生这种情况,用户看到内容已登录并且只有当它有权查看时才能看到该视频
我的应用是用户有一个研讨会,这个研讨会有很多会议,每个会议都有一个视频。在这里,我保留模型的内容**enter code here**
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :recoverable,
:rememberable, :trackable, :validatable
belongs_to :workshop
mount_uploader :avatar, AvatarUploader
enum role: [:student, :teacher]
end
class Workshop < ApplicationRecord
has_many :sessions
has_many :users
validates :name, presence: true
end
class Session < ApplicationRecord
belongs_to :workshop
mount_uploader :video, WsvideoUploader
before_create :default_name
def default_name
self.video ||= File.basename(video.filename, '.*').titleize if video
end
end
目前文件存储在carrierwave的默认路由中,我留下了继承自carrierwave的类的代码。
class WsvideoUploader < CarrierWave::Uploader::Base
# Choose what kind of storage to use for this uploader:
storage :file
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
end
答案 0 :(得分:0)
可以使用before_filter保护控制器操作,以便由经过身份验证的用户调用。但是,由于访问carrierwave上传的文件不会调用任何控制器操作,因此无论如何都不能使用before_filter,而不是直接使用。 为了做你想做的事情,你需要将上传的文件保存在不在公共场所的目录中,然后使用控制器访问文件。
由于您使用的是Devise,只需添加before_action :authenticate_user!
Carrierwave Wiki页面上给出了更详细的解释。你可以在secure-upload-using-carrierwave
找到它