2017-10-04 20 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 

예 실패한 비동기 요청 : 실패한 요청이 DB 쿼리에서 사용자를로드/선택하지 않는

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.): 

참고. 어떤 아이디어가 잘못 될 수 있습니까? 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

세션에는 사용자 ID가 없기 때문에 비동기 요청이 DB에서 사용자를 쿼리하지 않습니다이다. Fetch APIfetch에는 기본적으로 쿠키가 포함되어 있지 않기 때문에 세션에 사용자 ID가 없습니다. 가져 오기에 요청과 함께 쿠키를 전송하기 위해

"same-origin" 또는 "include"credentials 옵션을 설정

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

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

+0

놀라운 고맙습니다! 나는'include' 대신'same-origin'을 사용하기로 결정했습니다. 외국 사이트에 대한 자격은 언제 갖게됩니까? 어떤 종류의 유스 케이스가'include'를 필요로 하는가? 사용자가 특별한 자격증을 가지고 API 키가 아닌 경우? –

+1

귀하의 질문에 대해 자격을 갖춘 답을 줄 수 있는지 확실하지 않습니다. 그것은 StackOverflow에 대한 새로운 질문에 대한 좋은 후보입니다. 행운을 빕니다! – chumakoff