代码之家  ›  专栏  ›  技术社区  ›  James L.

CanCanCan能力中无用户。rb型

  •  2
  • James L.  · 技术社区  · 8 年前

    尝试从React组件获取异步请求。但是,由于权限无效,它总是失败。

    工作请求示例:

    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查询中选择/加载用户。你知道会出什么问题吗?能力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
    

    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
    
    1 回复  |  直到 8 年前
        1
  •  2
  •   chumakoff    8 年前

    异步请求不会从DB查询用户,因为会话中没有用户ID。会话中没有用户ID,因为 Fetch API fetch 默认情况下不包括Cookie。

    为了发送带有获取请求集的Cookie credentials 选择 "same-origin" "include" :

    fetch(url, {  
      credentials: 'include'  // or 'same-origin' (see the link below)
    })
    

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