簡體   English   中英

CanCanCanbility.rb中的零用戶

[英]Nil user in CanCanCan ability.rb

試圖從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.):

請注意,失敗的請求不會從數據庫查詢中選擇/加載用戶。 任何想法可能出什么問題嗎? 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

和capability.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

異步請求不會從數據庫查詢用戶,因為會話中沒有用戶ID。 會話中沒有用戶ID,因為默認情況下Fetch APIfetch不包含cookie。

為了發送帶有“獲取請求"same-origin" 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM