如何用cancan保护send_file动作

时间:2012-11-10 00:03:38

标签: ruby-on-rails ruby-on-rails-3 cancan sendfile x-sendfile

我似乎无法批准web_videos_display行动的授权。我可以使用skip_authorize_resource使其工作,但任何用户都可以通过了解:id来访问该文件的URL。我需要访问asset以“查看”该文件。

感谢您对此进行调查。

assets_controller.rb

...
class AssetsController < ApplicationController

  load_and_authorize_resource :team
  load_and_authorize_resource :through => :team

  # skip_authorize_resource :only => [:web_videos_display, ...]
  # skip_authorize_resource :team, :only => [:web_videos_display, ...]
  ...
  def web_videos_display
    # @asset = Asset.find(params[:id]) #loaded by cancan
    @file = "#{Rails.root}#{@asset.webVideos.last.file}"
    send_file @file, :disposition => 'inline', :x_sendfile=>true
  end
  ...

的routes.rb

  resources :teams, :path => '', :except => [:index] do
  ...
    resources :assets, :path => '' do
      ...
      get 'web_videos_display'
      ...
    end
  end

show.html.erb

...
<%= team_asset_web_videos_display_path(@team, @asset, :id => @asset.id, :team_id => @team.id) %>
...

ability.rb

...
can :read, Team, :memberships => {:id => user.membership_ids}
can :manage, Asset, :team => { :id => user.team_ids }
can :web_videos_display, Asset, :team => { :id => user.team_ids }
...

更新以响应@ryanb评论

返回

1.9.2p318 :006 > ability.can?(:web_videos_display, asset)
  Team Load (0.2ms)  SELECT "teams".* FROM "teams" WHERE "teams"."id" = 1 LIMIT 1
 => true

在开发模式下它仍会返回

Started GET "/video-pros/test-1/web_videos_display?id=10" for 127.0.0.1 at 2012-11-09 16:40:19 -0800
  Processing by AssetsController#web_videos_display as */*
  Parameters: {"id"=>"10", "team_id"=>"video-pros", "asset_id"=>"test-1"}
  Team Load (0.1ms)  SELECT "teams".* FROM "teams" WHERE "teams"."slug" = 'video-pros' LIMIT 1
  Team Load (0.2ms)  SELECT "teams".* FROM "teams" WHERE "teams"."admin_user_id" = 1 LIMIT 1
  CACHE (0.0ms)  SELECT "teams".* FROM "teams" WHERE "teams"."slug" = 'video-pros' LIMIT 1
Access denied on show #<Team id: 1, name: "Video Pros", email: nil, phone: nil, website: nil, slug: "video-pros", admin_user_id: 1, created_at: "2012-11-06 22:43:11", updated_at: "2012-11-06 22:43:11", payment_received: nil>
Redirected to http://0.0.0.0:3000/
Completed 302 Found in 73ms>

谢谢Ryan

1 个答案:

答案 0 :(得分:1)

send_file不应该有所不同,因为授权发生在触发操作之前的before_filter中。据我所知,它看起来是正确的,所以可能还有其他事情发生。您是否尝试过这个debugging页面?如果您模仿控制器授权在控制台中执行的操作会发生什么?

user = User.first # fetch any user you want to test abilities on
team = Team.first # any model you want to test against
asset = team.assets.first
ability = Ability.new(user)
ability.can?(:show, team) # see if it allows access
ability.can?(:web_videos_display, asset) # see if it allows access

为团队

更新:read:show行动