2017-10-04 56 views
1

嘗試從React組件獲取異步請求。但由於權限無效,它總是失敗。CanCanCan中的無用戶ability.rb

實施例工作的請求:

Started GET "/" for 127.0.0.1 at 2017-10-04 16:32:00 -0400 
Processing by EventsController#index as HTML 
    User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]] 
    Rendering events/index.html.erb within layouts/application 

例失敗異步請求:

Started GET "/events/search?ne_lat=37.82915414554321&ne_lng=-122.13221051635742&sw_lat=37.72060601151162&sw_lng=-122.70658948364257" for 127.0.0.1 at 2017-10-04 16:32:07 -0400 
Processing by EventsController#search as */* 
    Parameters: {"ne_lat"=>"37.82915414554321", "ne_lng"=>"-122.13221051635742", "sw_lat"=>"37.72060601151162", "sw_lng"=>"-122.70658948364257"} 
    ... #NOTE: printing 'user' from byebug in ability.rb shows it as nil 
CanCan::AccessDenied (You are not authorized to access this page.): 

注意,失敗的請求不選擇/從DB查詢加載用戶。任何想法可能會出錯? Ability.rb權限允許此請求,但用戶在異步調用時未被正確填寫。

此請求以前使用jQuery工作,但我用fetch重寫了它。

這裏是控制器

class EventsController < ApplicationController 
    before_action :set_event, only: [:show, :edit, :update, :destroy] 
    load_and_authorize_resource 

    def index 
    @events = Event.all 
    end 
    ... 
    def search 
    local_events = Event.includes(:address).references(:address) 
     .where("latitude >= ? AND latitude <= ? AND longitude >= ? AND longitude <= ?",  
      params[:sw_lat], params[:ne_lat], params[:sw_lng], params[:ne_lng] 
     ) 
     .limit(50) 

    render json: local_events, only: [:id,:name,:description,:start], include: { address: { only: [:latitude,:longitude,:street_address] }} 
    end 

end 

而ability.rb

class Ability 
    include CanCan::Ability 

    def initialize(user) 
    can :read, :all 
    byebug 
    return if user == nil #user must be logged in after this point 

    #events 
    can [:search], Event 
    ... 
    end 
end 
+0

顯示'EventsController' – chumakoff

+0

完成。你還有什麼建議加入的? –

回答

2

異步請求不查詢從DB用戶因爲沒有在該會話沒有用戶ID。會話中沒有用戶標識,因爲默認情況下,Fetch APIfetch不包含Cookie。

爲了與獲取請求發送cookie設置credentials選項"same-origin""include"

fetch(url, { 
    credentials: 'include' 
}) 

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Sending_a_request_with_credentials_included

+0

令人驚歎的謝謝你!我決定使用'same-origin'而不是'include'。你什麼時候有外國網站的證件?什麼樣的用例需要'include' - 當用戶擁有特殊憑證並且它不是API密鑰時? –

+1

我不確定我可以針對您的問題給出合格的答案。它是StackOverflow上一個新問題的好選擇。祝你好運! – chumakoff