sissy
sissy

Reputation: 3008

Rails4: how to restrict streaming video files access?

I would like to put some html5 videos inside my page, but the access to this video can be given only to logged in users (so non-logged in users must not see the video, also if they have the url):

<video width="320" height="240" controls>
  <source src="/video.mp4" type="video/mp4">
  <source src="/video.m4v" type="video/m4v">
Your browser does not support the video tag.
</video>

I tried with something like this in my action (with a before filter for access restriction):

  def video
    respond_to do |format|
      format.m4v{
        send_data File.join([Rails.root, "public", "videos", "sample.m4v"]), type: 'video/m4v', disposition: :inline
      }
      format.mp4{
        send_data File.join([Rails.root, "public", "videos", "sample.mp4"]), type: 'video/mp4', disposition: :inline
      }
    end
  end

but this is sending the file as an attachment, and not just serving it.

Is it possible? and, if yes, how can it be done?

thank you

Upvotes: 6

Views: 1565

Answers (2)

sissy
sissy

Reputation: 3008

Now this is working, i was missing an option, that is :stream => true. With that videos are served the right way.

send_file File.join([Rails.root, "private/videos", @lesson.link_video1 + ".#{extension}"]), 
      :disposition => :inline, :stream => true

The problem now is another one, that i asked here

Rails serving large files

Upvotes: 1

Joe Kennedy
Joe Kennedy

Reputation: 9443

Don't you want to use video_tag to render the video as part of a view?

If so, just use the devise helper user_signed_in? in the ERB file you'd like the video to display in. This makes sure only signed in users can see the video in the video_tag.

<% if user_signed_in? %>
  <%= video_tag ['/video.mp4', '/video.m4v'], controls: true, height: '240', width: '320' %>
<% end %>

For more information on video_tag, see: http://api.rubyonrails.org/classes/ActionView/Helpers/AssetTagHelper.html#method-i-video_tag http://guides.rubyonrails.org/layouts_and_rendering.html#linking-to-videos-with-the-video-tag

Upvotes: 0

Related Questions