403在执行AJAX调用restful controller中的非restful动作时禁止

时间:2016-10-30 21:30:20

标签: jquery ruby-on-rails ajax ruby-on-rails-5 cancancan

我有一个Profile模型,我试图通过AJAX更新。

这是我的routes.rb

  resources :profiles do
    member do
      patch :speed_rating
      patch :dribbling_rating
      patch :passing_rating
      patch :tackling_rating
    end
  end

生成以下路线:

speed_rating_profile_path   PATCH   /profiles/:id/speed_rating(.:format)    
profiles#speed_rating

dribbling_rating_profile_path   PATCH   /profiles/:id/dribbling_rating(.:format)    
profiles#dribbling_rating

passing_rating_profile_path PATCH   /profiles/:id/passing_rating(.:format)  
profiles#passing_rating

tackling_rating_profile_path    PATCH   /profiles/:id/tackling_rating(.:format) 
profiles#tackling_rating

这是我的ProfilesController

class ProfilesController < ApplicationController
  before_action :set_profile, only: [:show, :edit, :update, :destroy, :invite_user, :speed_rating, :tackling_rating, :dribbling_rating, :passing_rating]
  authorize_resource except: [:dashboard]
  skip_authorization_check only: :dashboard

  def speed_rating
    binding.pry
  end

  def dribbling_rating
    binding.pry
  end

  def passing_rating
    binding.pry
  end

  def tackling_rating
    binding.pry
  end

  private
    def set_profile
      @profile = Profile.friendly.find(params[:id])
    end

    def profile_params
      params.require(:profile).permit(:id, :first_name, :last_name, :dob, :height, :weight, :bib_color, videos_attributes: [:id, :url, :video, :vimeo_url, :vimeo_embed_code, :official, :video_cache, :remove_video, :_destroy], transcripts_attributes: [:id, :url, :name, :transcript, :remove_transcript, :url_cache, :_destroy])
    end

在我的profile.js中,我这样做:

  var url = "/profiles/" + _profile_id + "/" + _rating_type + "_rating/?" + _rating_type + "=" + button.innerText

  $.ajax({
    type: "PATCH",
    url: url,
    success: function(result){
      console.log(_profile_id + "'s " + _rating_type + " was successfully updated.");
      console.log(result);
    },
    error: function(result){
      console.log(_profile_id + "'s " + _rating_type + " was successfully updated.");
      console.log(result);
    }
  })

这是我得到的错误:

jquery.self-bd7ddd3….js?body=1:10255 PATCH http://localhost:3000/profiles/rebecca-nitzsche-st-george-s-college/dribbling_rating/?dribbling=6 403 (Forbidden)

修改1

我正在使用CanCanCan进行授权。

我尝试过的一件事是我将这些新动作添加到授权例外列表中,特别是这样:

authorize_resource except: [:dashboard, :speed_rating, :dribbling_rating, :tackling_rating, :passing_rating]

到目前为止似乎有效。但是,这会让我的应用程序不安全吗?

如何在我的正确授权范围内使其工作,以确保用户在发现这些路线时不会滥用这些路线?

1 个答案:

答案 0 :(得分:0)

我将假设这一行:

authorize_resource except: [:dashboard]

正在进行某种形式的身份验证或授权,这可能需要用户详细信息。我在AJAX请求中看不到任何用户名或密码或会话cookie的规定。您需要确保使用AJAX请求发送会话cookie,以便成功授权请求。

您可以通过在xhrFields的通话中加入$.ajax对象来实现此目的:

$.ajax({
    'type': 'PATCH',
    'url': 'whatever',
    'xhrFields': {
        'withCredentials': true
    }
    // whatever other AJAX options you need
});