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